drupal_web_test_case.php 132 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780
  1. <?php
  2. /**
  3. * Global variable that holds information about the tests being run.
  4. *
  5. * An array, with the following keys:
  6. * - 'test_run_id': the ID of the test being run, in the form 'simpletest_%"
  7. * - 'in_child_site': TRUE if the current request is a cURL request from
  8. * the parent site.
  9. *
  10. * @var array
  11. */
  12. global $drupal_test_info;
  13. /**
  14. * Base class for Drupal tests.
  15. *
  16. * Do not extend this class, use one of the subclasses in this file.
  17. */
  18. abstract class DrupalTestCase {
  19. /**
  20. * The test run ID.
  21. *
  22. * @var string
  23. */
  24. protected $testId;
  25. /**
  26. * The database prefix of this test run.
  27. *
  28. * @var string
  29. */
  30. protected $databasePrefix = NULL;
  31. /**
  32. * The original file directory, before it was changed for testing purposes.
  33. *
  34. * @var string
  35. */
  36. protected $originalFileDirectory = NULL;
  37. /**
  38. * Time limit for the test.
  39. */
  40. protected $timeLimit = 500;
  41. /**
  42. * Current results of this test case.
  43. *
  44. * @var Array
  45. */
  46. public $results = array(
  47. '#pass' => 0,
  48. '#fail' => 0,
  49. '#exception' => 0,
  50. '#debug' => 0,
  51. );
  52. /**
  53. * Assertions thrown in that test case.
  54. *
  55. * @var Array
  56. */
  57. protected $assertions = array();
  58. /**
  59. * This class is skipped when looking for the source of an assertion.
  60. *
  61. * When displaying which function an assert comes from, it's not too useful
  62. * to see "drupalWebTestCase->drupalLogin()', we would like to see the test
  63. * that called it. So we need to skip the classes defining these helper
  64. * methods.
  65. */
  66. protected $skipClasses = array(__CLASS__ => TRUE);
  67. /**
  68. * Flag to indicate whether the test has been set up.
  69. *
  70. * The setUp() method isolates the test from the parent Drupal site by
  71. * creating a random prefix for the database and setting up a clean file
  72. * storage directory. The tearDown() method then cleans up this test
  73. * environment. We must ensure that setUp() has been run. Otherwise,
  74. * tearDown() will act on the parent Drupal site rather than the test
  75. * environment, destroying live data.
  76. */
  77. protected $setup = FALSE;
  78. protected $setupDatabasePrefix = FALSE;
  79. protected $setupEnvironment = FALSE;
  80. /**
  81. * Constructor for DrupalTestCase.
  82. *
  83. * @param $test_id
  84. * Tests with the same id are reported together.
  85. */
  86. public function __construct($test_id = NULL) {
  87. $this->testId = $test_id;
  88. }
  89. /**
  90. * Internal helper: stores the assert.
  91. *
  92. * @param $status
  93. * Can be 'pass', 'fail', 'exception'.
  94. * TRUE is a synonym for 'pass', FALSE for 'fail'.
  95. * @param $message
  96. * The message string.
  97. * @param $group
  98. * Which group this assert belongs to.
  99. * @param $caller
  100. * By default, the assert comes from a function whose name starts with
  101. * 'test'. Instead, you can specify where this assert originates from
  102. * by passing in an associative array as $caller. Key 'file' is
  103. * the name of the source file, 'line' is the line number and 'function'
  104. * is the caller function itself.
  105. */
  106. protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
  107. // Convert boolean status to string status.
  108. if (is_bool($status)) {
  109. $status = $status ? 'pass' : 'fail';
  110. }
  111. // Increment summary result counter.
  112. $this->results['#' . $status]++;
  113. // Get the function information about the call to the assertion method.
  114. if (!$caller) {
  115. $caller = $this->getAssertionCall();
  116. }
  117. // Creation assertion array that can be displayed while tests are running.
  118. $this->assertions[] = $assertion = array(
  119. 'test_id' => $this->testId,
  120. 'test_class' => get_class($this),
  121. 'status' => $status,
  122. 'message' => $message,
  123. 'message_group' => $group,
  124. 'function' => $caller['function'],
  125. 'line' => $caller['line'],
  126. 'file' => $caller['file'],
  127. );
  128. // Store assertion for display after the test has completed.
  129. self::getDatabaseConnection()
  130. ->insert('simpletest')
  131. ->fields($assertion)
  132. ->execute();
  133. // We do not use a ternary operator here to allow a breakpoint on
  134. // test failure.
  135. if ($status == 'pass') {
  136. return TRUE;
  137. }
  138. else {
  139. return FALSE;
  140. }
  141. }
  142. /**
  143. * Returns the database connection to the site running Simpletest.
  144. *
  145. * @return DatabaseConnection
  146. * The database connection to use for inserting assertions.
  147. */
  148. public static function getDatabaseConnection() {
  149. try {
  150. $connection = Database::getConnection('default', 'simpletest_original_default');
  151. }
  152. catch (DatabaseConnectionNotDefinedException $e) {
  153. // If the test was not set up, the simpletest_original_default
  154. // connection does not exist.
  155. $connection = Database::getConnection('default', 'default');
  156. }
  157. return $connection;
  158. }
  159. /**
  160. * Store an assertion from outside the testing context.
  161. *
  162. * This is useful for inserting assertions that can only be recorded after
  163. * the test case has been destroyed, such as PHP fatal errors. The caller
  164. * information is not automatically gathered since the caller is most likely
  165. * inserting the assertion on behalf of other code. In all other respects
  166. * the method behaves just like DrupalTestCase::assert() in terms of storing
  167. * the assertion.
  168. *
  169. * @return
  170. * Message ID of the stored assertion.
  171. *
  172. * @see DrupalTestCase::assert()
  173. * @see DrupalTestCase::deleteAssert()
  174. */
  175. public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = array()) {
  176. // Convert boolean status to string status.
  177. if (is_bool($status)) {
  178. $status = $status ? 'pass' : 'fail';
  179. }
  180. $caller += array(
  181. 'function' => t('Unknown'),
  182. 'line' => 0,
  183. 'file' => t('Unknown'),
  184. );
  185. $assertion = array(
  186. 'test_id' => $test_id,
  187. 'test_class' => $test_class,
  188. 'status' => $status,
  189. 'message' => $message,
  190. 'message_group' => $group,
  191. 'function' => $caller['function'],
  192. 'line' => $caller['line'],
  193. 'file' => $caller['file'],
  194. );
  195. return self::getDatabaseConnection()
  196. ->insert('simpletest')
  197. ->fields($assertion)
  198. ->execute();
  199. }
  200. /**
  201. * Delete an assertion record by message ID.
  202. *
  203. * @param $message_id
  204. * Message ID of the assertion to delete.
  205. * @return
  206. * TRUE if the assertion was deleted, FALSE otherwise.
  207. *
  208. * @see DrupalTestCase::insertAssert()
  209. */
  210. public static function deleteAssert($message_id) {
  211. return (bool) self::getDatabaseConnection()
  212. ->delete('simpletest')
  213. ->condition('message_id', $message_id)
  214. ->execute();
  215. }
  216. /**
  217. * Cycles through backtrace until the first non-assertion method is found.
  218. *
  219. * @return
  220. * Array representing the true caller.
  221. */
  222. protected function getAssertionCall() {
  223. $backtrace = debug_backtrace();
  224. // The first element is the call. The second element is the caller.
  225. // We skip calls that occurred in one of the methods of our base classes
  226. // or in an assertion function.
  227. while (($caller = $backtrace[1]) &&
  228. ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
  229. substr($caller['function'], 0, 6) == 'assert')) {
  230. // We remove that call.
  231. array_shift($backtrace);
  232. }
  233. return _drupal_get_last_caller($backtrace);
  234. }
  235. /**
  236. * Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
  237. *
  238. * @param $value
  239. * The value on which the assertion is to be done.
  240. * @param $message
  241. * The message to display along with the assertion.
  242. * @param $group
  243. * The type of assertion - examples are "Browser", "PHP".
  244. * @return
  245. * TRUE if the assertion succeeded, FALSE otherwise.
  246. */
  247. protected function assertTrue($value, $message = '', $group = 'Other') {
  248. return $this->assert((bool) $value, $message ? $message : t('Value @value is TRUE.', array('@value' => var_export($value, TRUE))), $group);
  249. }
  250. /**
  251. * Check to see if a value is false (an empty string, 0, NULL, or FALSE).
  252. *
  253. * @param $value
  254. * The value on which the assertion is to be done.
  255. * @param $message
  256. * The message to display along with the assertion.
  257. * @param $group
  258. * The type of assertion - examples are "Browser", "PHP".
  259. * @return
  260. * TRUE if the assertion succeeded, FALSE otherwise.
  261. */
  262. protected function assertFalse($value, $message = '', $group = 'Other') {
  263. return $this->assert(!$value, $message ? $message : t('Value @value is FALSE.', array('@value' => var_export($value, TRUE))), $group);
  264. }
  265. /**
  266. * Check to see if a value is NULL.
  267. *
  268. * @param $value
  269. * The value on which the assertion is to be done.
  270. * @param $message
  271. * The message to display along with the assertion.
  272. * @param $group
  273. * The type of assertion - examples are "Browser", "PHP".
  274. * @return
  275. * TRUE if the assertion succeeded, FALSE otherwise.
  276. */
  277. protected function assertNull($value, $message = '', $group = 'Other') {
  278. return $this->assert(!isset($value), $message ? $message : t('Value @value is NULL.', array('@value' => var_export($value, TRUE))), $group);
  279. }
  280. /**
  281. * Check to see if a value is not NULL.
  282. *
  283. * @param $value
  284. * The value on which the assertion is to be done.
  285. * @param $message
  286. * The message to display along with the assertion.
  287. * @param $group
  288. * The type of assertion - examples are "Browser", "PHP".
  289. * @return
  290. * TRUE if the assertion succeeded, FALSE otherwise.
  291. */
  292. protected function assertNotNull($value, $message = '', $group = 'Other') {
  293. return $this->assert(isset($value), $message ? $message : t('Value @value is not NULL.', array('@value' => var_export($value, TRUE))), $group);
  294. }
  295. /**
  296. * Check to see if two values are equal.
  297. *
  298. * @param $first
  299. * The first value to check.
  300. * @param $second
  301. * The second value to check.
  302. * @param $message
  303. * The message to display along with the assertion.
  304. * @param $group
  305. * The type of assertion - examples are "Browser", "PHP".
  306. * @return
  307. * TRUE if the assertion succeeded, FALSE otherwise.
  308. */
  309. protected function assertEqual($first, $second, $message = '', $group = 'Other') {
  310. return $this->assert($first == $second, $message ? $message : t('Value @first is equal to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
  311. }
  312. /**
  313. * Check to see if two values are not equal.
  314. *
  315. * @param $first
  316. * The first value to check.
  317. * @param $second
  318. * The second value to check.
  319. * @param $message
  320. * The message to display along with the assertion.
  321. * @param $group
  322. * The type of assertion - examples are "Browser", "PHP".
  323. * @return
  324. * TRUE if the assertion succeeded, FALSE otherwise.
  325. */
  326. protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
  327. return $this->assert($first != $second, $message ? $message : t('Value @first is not equal to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
  328. }
  329. /**
  330. * Check to see if two values are identical.
  331. *
  332. * @param $first
  333. * The first value to check.
  334. * @param $second
  335. * The second value to check.
  336. * @param $message
  337. * The message to display along with the assertion.
  338. * @param $group
  339. * The type of assertion - examples are "Browser", "PHP".
  340. * @return
  341. * TRUE if the assertion succeeded, FALSE otherwise.
  342. */
  343. protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
  344. return $this->assert($first === $second, $message ? $message : t('Value @first is identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
  345. }
  346. /**
  347. * Check to see if two values are not identical.
  348. *
  349. * @param $first
  350. * The first value to check.
  351. * @param $second
  352. * The second value to check.
  353. * @param $message
  354. * The message to display along with the assertion.
  355. * @param $group
  356. * The type of assertion - examples are "Browser", "PHP".
  357. * @return
  358. * TRUE if the assertion succeeded, FALSE otherwise.
  359. */
  360. protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
  361. return $this->assert($first !== $second, $message ? $message : t('Value @first is not identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
  362. }
  363. /**
  364. * Fire an assertion that is always positive.
  365. *
  366. * @param $message
  367. * The message to display along with the assertion.
  368. * @param $group
  369. * The type of assertion - examples are "Browser", "PHP".
  370. * @return
  371. * TRUE.
  372. */
  373. protected function pass($message = NULL, $group = 'Other') {
  374. return $this->assert(TRUE, $message, $group);
  375. }
  376. /**
  377. * Fire an assertion that is always negative.
  378. *
  379. * @param $message
  380. * The message to display along with the assertion.
  381. * @param $group
  382. * The type of assertion - examples are "Browser", "PHP".
  383. * @return
  384. * FALSE.
  385. */
  386. protected function fail($message = NULL, $group = 'Other') {
  387. return $this->assert(FALSE, $message, $group);
  388. }
  389. /**
  390. * Fire an error assertion.
  391. *
  392. * @param $message
  393. * The message to display along with the assertion.
  394. * @param $group
  395. * The type of assertion - examples are "Browser", "PHP".
  396. * @param $caller
  397. * The caller of the error.
  398. * @return
  399. * FALSE.
  400. */
  401. protected function error($message = '', $group = 'Other', array $caller = NULL) {
  402. if ($group == 'User notice') {
  403. // Since 'User notice' is set by trigger_error() which is used for debug
  404. // set the message to a status of 'debug'.
  405. return $this->assert('debug', $message, 'Debug', $caller);
  406. }
  407. return $this->assert('exception', $message, $group, $caller);
  408. }
  409. /**
  410. * Logs a verbose message in a text file.
  411. *
  412. * The link to the verbose message will be placed in the test results as a
  413. * passing assertion with the text '[verbose message]'.
  414. *
  415. * @param $message
  416. * The verbose message to be stored.
  417. *
  418. * @see simpletest_verbose()
  419. */
  420. protected function verbose($message) {
  421. if ($id = simpletest_verbose($message)) {
  422. $class_safe = str_replace('\\', '_', get_class($this));
  423. $url = file_create_url($this->originalFileDirectory . '/simpletest/verbose/' . $class_safe . '-' . $id . '.html');
  424. $this->error(l(t('Verbose message'), $url, array('attributes' => array('target' => '_blank'))), 'User notice');
  425. }
  426. }
  427. /**
  428. * Run all tests in this class.
  429. *
  430. * Regardless of whether $methods are passed or not, only method names
  431. * starting with "test" are executed.
  432. *
  433. * @param $methods
  434. * (optional) A list of method names in the test case class to run; e.g.,
  435. * array('testFoo', 'testBar'). By default, all methods of the class are
  436. * taken into account, but it can be useful to only run a few selected test
  437. * methods during debugging.
  438. */
  439. public function run(array $methods = array()) {
  440. // Initialize verbose debugging.
  441. $class = get_class($this);
  442. simpletest_verbose(NULL, variable_get('file_public_path', conf_path() . '/files'), str_replace('\\', '_', $class));
  443. // HTTP auth settings (<username>:<password>) for the simpletest browser
  444. // when sending requests to the test site.
  445. $this->httpauth_method = variable_get('simpletest_httpauth_method', CURLAUTH_BASIC);
  446. $username = variable_get('simpletest_httpauth_username', NULL);
  447. $password = variable_get('simpletest_httpauth_password', NULL);
  448. if ($username && $password) {
  449. $this->httpauth_credentials = $username . ':' . $password;
  450. }
  451. set_error_handler(array($this, 'errorHandler'));
  452. // Iterate through all the methods in this class, unless a specific list of
  453. // methods to run was passed.
  454. $class_methods = get_class_methods($class);
  455. if ($methods) {
  456. $class_methods = array_intersect($class_methods, $methods);
  457. }
  458. foreach ($class_methods as $method) {
  459. // If the current method starts with "test", run it - it's a test.
  460. if (strtolower(substr($method, 0, 4)) == 'test') {
  461. // Insert a fail record. This will be deleted on completion to ensure
  462. // that testing completed.
  463. $method_info = new ReflectionMethod($class, $method);
  464. $caller = array(
  465. 'file' => $method_info->getFileName(),
  466. 'line' => $method_info->getStartLine(),
  467. 'function' => $class . '->' . $method . '()',
  468. );
  469. $completion_check_id = DrupalTestCase::insertAssert($this->testId, $class, FALSE, t('The test did not complete due to a fatal error.'), 'Completion check', $caller);
  470. $this->setUp();
  471. if ($this->setup) {
  472. try {
  473. $this->$method();
  474. // Finish up.
  475. }
  476. catch (Exception $e) {
  477. $this->exceptionHandler($e);
  478. }
  479. $this->tearDown();
  480. }
  481. else {
  482. $this->fail(t("The test cannot be executed because it has not been set up properly."));
  483. }
  484. // Remove the completion check record.
  485. DrupalTestCase::deleteAssert($completion_check_id);
  486. }
  487. }
  488. // Clear out the error messages and restore error handler.
  489. drupal_get_messages();
  490. restore_error_handler();
  491. }
  492. /**
  493. * Handle errors during test runs.
  494. *
  495. * Because this is registered in set_error_handler(), it has to be public.
  496. * @see set_error_handler
  497. */
  498. public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
  499. if ($severity & error_reporting()) {
  500. $error_map = array(
  501. E_STRICT => 'Run-time notice',
  502. E_WARNING => 'Warning',
  503. E_NOTICE => 'Notice',
  504. E_CORE_ERROR => 'Core error',
  505. E_CORE_WARNING => 'Core warning',
  506. E_USER_ERROR => 'User error',
  507. E_USER_WARNING => 'User warning',
  508. E_USER_NOTICE => 'User notice',
  509. E_RECOVERABLE_ERROR => 'Recoverable error',
  510. );
  511. // PHP 5.3 adds new error logging constants. Add these conditionally for
  512. // backwards compatibility with PHP 5.2.
  513. if (defined('E_DEPRECATED')) {
  514. $error_map += array(
  515. E_DEPRECATED => 'Deprecated',
  516. E_USER_DEPRECATED => 'User deprecated',
  517. );
  518. }
  519. $backtrace = debug_backtrace();
  520. $this->error($message, $error_map[$severity], _drupal_get_last_caller($backtrace));
  521. }
  522. return TRUE;
  523. }
  524. /**
  525. * Handle exceptions.
  526. *
  527. * @see set_exception_handler
  528. */
  529. protected function exceptionHandler($exception) {
  530. $backtrace = $exception->getTrace();
  531. // Push on top of the backtrace the call that generated the exception.
  532. array_unshift($backtrace, array(
  533. 'line' => $exception->getLine(),
  534. 'file' => $exception->getFile(),
  535. ));
  536. require_once DRUPAL_ROOT . '/includes/errors.inc';
  537. // The exception message is run through check_plain() by _drupal_decode_exception().
  538. $this->error(t('%type: !message in %function (line %line of %file).', _drupal_decode_exception($exception)), 'Uncaught exception', _drupal_get_last_caller($backtrace));
  539. }
  540. /**
  541. * Generates a random string of ASCII characters of codes 32 to 126.
  542. *
  543. * The generated string includes alpha-numeric characters and common
  544. * miscellaneous characters. Use this method when testing general input
  545. * where the content is not restricted.
  546. *
  547. * Do not use this method when special characters are not possible (e.g., in
  548. * machine or file names that have already been validated); instead,
  549. * use DrupalWebTestCase::randomName().
  550. *
  551. * @param $length
  552. * Length of random string to generate.
  553. *
  554. * @return
  555. * Randomly generated string.
  556. *
  557. * @see DrupalWebTestCase::randomName()
  558. */
  559. public static function randomString($length = 8) {
  560. $str = '';
  561. for ($i = 0; $i < $length; $i++) {
  562. $str .= chr(mt_rand(32, 126));
  563. }
  564. return $str;
  565. }
  566. /**
  567. * Generates a random string containing letters and numbers.
  568. *
  569. * The string will always start with a letter. The letters may be upper or
  570. * lower case. This method is better for restricted inputs that do not
  571. * accept certain characters. For example, when testing input fields that
  572. * require machine readable values (i.e. without spaces and non-standard
  573. * characters) this method is best.
  574. *
  575. * Do not use this method when testing unvalidated user input. Instead, use
  576. * DrupalWebTestCase::randomString().
  577. *
  578. * @param $length
  579. * Length of random string to generate.
  580. *
  581. * @return
  582. * Randomly generated string.
  583. *
  584. * @see DrupalWebTestCase::randomString()
  585. */
  586. public static function randomName($length = 8) {
  587. $values = array_merge(range(65, 90), range(97, 122), range(48, 57));
  588. $max = count($values) - 1;
  589. $str = chr(mt_rand(97, 122));
  590. for ($i = 1; $i < $length; $i++) {
  591. $str .= chr($values[mt_rand(0, $max)]);
  592. }
  593. return $str;
  594. }
  595. /**
  596. * Converts a list of possible parameters into a stack of permutations.
  597. *
  598. * Takes a list of parameters containing possible values, and converts all of
  599. * them into a list of items containing every possible permutation.
  600. *
  601. * Example:
  602. * @code
  603. * $parameters = array(
  604. * 'one' => array(0, 1),
  605. * 'two' => array(2, 3),
  606. * );
  607. * $permutations = DrupalTestCase::generatePermutations($parameters)
  608. * // Result:
  609. * $permutations == array(
  610. * array('one' => 0, 'two' => 2),
  611. * array('one' => 1, 'two' => 2),
  612. * array('one' => 0, 'two' => 3),
  613. * array('one' => 1, 'two' => 3),
  614. * )
  615. * @endcode
  616. *
  617. * @param $parameters
  618. * An associative array of parameters, keyed by parameter name, and whose
  619. * values are arrays of parameter values.
  620. *
  621. * @return
  622. * A list of permutations, which is an array of arrays. Each inner array
  623. * contains the full list of parameters that have been passed, but with a
  624. * single value only.
  625. */
  626. public static function generatePermutations($parameters) {
  627. $all_permutations = array(array());
  628. foreach ($parameters as $parameter => $values) {
  629. $new_permutations = array();
  630. // Iterate over all values of the parameter.
  631. foreach ($values as $value) {
  632. // Iterate over all existing permutations.
  633. foreach ($all_permutations as $permutation) {
  634. // Add the new parameter value to existing permutations.
  635. $new_permutations[] = $permutation + array($parameter => $value);
  636. }
  637. }
  638. // Replace the old permutations with the new permutations.
  639. $all_permutations = $new_permutations;
  640. }
  641. return $all_permutations;
  642. }
  643. }
  644. /**
  645. * Test case for Drupal unit tests.
  646. *
  647. * These tests can not access the database nor files. Calling any Drupal
  648. * function that needs the database will throw exceptions. These include
  649. * watchdog(), module_implements(), module_invoke_all() etc.
  650. */
  651. class DrupalUnitTestCase extends DrupalTestCase {
  652. /**
  653. * Constructor for DrupalUnitTestCase.
  654. */
  655. function __construct($test_id = NULL) {
  656. parent::__construct($test_id);
  657. $this->skipClasses[__CLASS__] = TRUE;
  658. }
  659. /**
  660. * Sets up unit test environment.
  661. *
  662. * Unlike DrupalWebTestCase::setUp(), DrupalUnitTestCase::setUp() does not
  663. * install modules because tests are performed without accessing the database.
  664. * Any required files must be explicitly included by the child class setUp()
  665. * method.
  666. */
  667. protected function setUp() {
  668. global $conf;
  669. // Store necessary current values before switching to the test environment.
  670. $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
  671. // Reset all statics so that test is performed with a clean environment.
  672. drupal_static_reset();
  673. // Generate temporary prefixed database to ensure that tests have a clean starting point.
  674. $this->databasePrefix = Database::getConnection()->prefixTables('{simpletest' . mt_rand(1000, 1000000) . '}');
  675. // Create test directory.
  676. $public_files_directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10);
  677. file_prepare_directory($public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  678. $conf['file_public_path'] = $public_files_directory;
  679. // Clone the current connection and replace the current prefix.
  680. $connection_info = Database::getConnectionInfo('default');
  681. Database::renameConnection('default', 'simpletest_original_default');
  682. foreach ($connection_info as $target => $value) {
  683. $connection_info[$target]['prefix'] = array(
  684. 'default' => $value['prefix']['default'] . $this->databasePrefix,
  685. );
  686. }
  687. Database::addConnectionInfo('default', 'default', $connection_info['default']);
  688. // Set user agent to be consistent with web test case.
  689. $_SERVER['HTTP_USER_AGENT'] = $this->databasePrefix;
  690. // If locale is enabled then t() will try to access the database and
  691. // subsequently will fail as the database is not accessible.
  692. $module_list = module_list();
  693. if (isset($module_list['locale'])) {
  694. // Transform the list into the format expected as input to module_list().
  695. foreach ($module_list as &$module) {
  696. $module = array('filename' => drupal_get_filename('module', $module));
  697. }
  698. $this->originalModuleList = $module_list;
  699. unset($module_list['locale']);
  700. module_list(TRUE, FALSE, FALSE, $module_list);
  701. }
  702. $this->setup = TRUE;
  703. }
  704. protected function tearDown() {
  705. global $conf;
  706. // Get back to the original connection.
  707. Database::removeConnection('default');
  708. Database::renameConnection('simpletest_original_default', 'default');
  709. $conf['file_public_path'] = $this->originalFileDirectory;
  710. // Restore modules if necessary.
  711. if (isset($this->originalModuleList)) {
  712. module_list(TRUE, FALSE, FALSE, $this->originalModuleList);
  713. }
  714. }
  715. }
  716. /**
  717. * Test case for typical Drupal tests.
  718. */
  719. class DrupalWebTestCase extends DrupalTestCase {
  720. /**
  721. * The profile to install as a basis for testing.
  722. *
  723. * @var string
  724. */
  725. protected $profile = 'standard';
  726. /**
  727. * The URL currently loaded in the internal browser.
  728. *
  729. * @var string
  730. */
  731. protected $url;
  732. /**
  733. * The handle of the current cURL connection.
  734. *
  735. * @var resource
  736. */
  737. protected $curlHandle;
  738. /**
  739. * The headers of the page currently loaded in the internal browser.
  740. *
  741. * @var Array
  742. */
  743. protected $headers;
  744. /**
  745. * The content of the page currently loaded in the internal browser.
  746. *
  747. * @var string
  748. */
  749. protected $content;
  750. /**
  751. * The content of the page currently loaded in the internal browser (plain text version).
  752. *
  753. * @var string
  754. */
  755. protected $plainTextContent;
  756. /**
  757. * The value of the Drupal.settings JavaScript variable for the page currently loaded in the internal browser.
  758. *
  759. * @var Array
  760. */
  761. protected $drupalSettings;
  762. /**
  763. * The parsed version of the page.
  764. *
  765. * @var SimpleXMLElement
  766. */
  767. protected $elements = NULL;
  768. /**
  769. * The current user logged in using the internal browser.
  770. *
  771. * @var bool
  772. */
  773. protected $loggedInUser = FALSE;
  774. /**
  775. * The current cookie file used by cURL.
  776. *
  777. * We do not reuse the cookies in further runs, so we do not need a file
  778. * but we still need cookie handling, so we set the jar to NULL.
  779. */
  780. protected $cookieFile = NULL;
  781. /**
  782. * The cookies of the page currently loaded in the internal browser.
  783. *
  784. * @var array
  785. */
  786. protected $cookies = array();
  787. /**
  788. * Additional cURL options.
  789. *
  790. * DrupalWebTestCase itself never sets this but always obeys what is set.
  791. */
  792. protected $additionalCurlOptions = array();
  793. /**
  794. * The original user, before it was changed to a clean uid = 1 for testing purposes.
  795. *
  796. * @var object
  797. */
  798. protected $originalUser = NULL;
  799. /**
  800. * The original shutdown handlers array, before it was cleaned for testing purposes.
  801. *
  802. * @var array
  803. */
  804. protected $originalShutdownCallbacks = array();
  805. /**
  806. * HTTP authentication method
  807. */
  808. protected $httpauth_method = CURLAUTH_BASIC;
  809. /**
  810. * HTTP authentication credentials (<username>:<password>).
  811. */
  812. protected $httpauth_credentials = NULL;
  813. /**
  814. * The current session name, if available.
  815. */
  816. protected $session_name = NULL;
  817. /**
  818. * The current session ID, if available.
  819. */
  820. protected $session_id = NULL;
  821. /**
  822. * Whether the files were copied to the test files directory.
  823. */
  824. protected $generatedTestFiles = FALSE;
  825. /**
  826. * The number of redirects followed during the handling of a request.
  827. */
  828. protected $redirect_count;
  829. /**
  830. * Constructor for DrupalWebTestCase.
  831. */
  832. function __construct($test_id = NULL) {
  833. parent::__construct($test_id);
  834. $this->skipClasses[__CLASS__] = TRUE;
  835. }
  836. /**
  837. * Get a node from the database based on its title.
  838. *
  839. * @param $title
  840. * A node title, usually generated by $this->randomName().
  841. * @param $reset
  842. * (optional) Whether to reset the internal node_load() cache.
  843. *
  844. * @return
  845. * A node object matching $title.
  846. */
  847. function drupalGetNodeByTitle($title, $reset = FALSE) {
  848. $nodes = node_load_multiple(array(), array('title' => $title), $reset);
  849. // Load the first node returned from the database.
  850. $returned_node = reset($nodes);
  851. return $returned_node;
  852. }
  853. /**
  854. * Creates a node based on default settings.
  855. *
  856. * @param $settings
  857. * An associative array of settings to change from the defaults, keys are
  858. * node properties, for example 'title' => 'Hello, world!'.
  859. * @return
  860. * Created node object.
  861. */
  862. protected function drupalCreateNode($settings = array()) {
  863. // Populate defaults array.
  864. $settings += array(
  865. 'title' => $this->randomName(8),
  866. 'comment' => 2,
  867. 'changed' => REQUEST_TIME,
  868. 'moderate' => 0,
  869. 'promote' => 0,
  870. 'revision' => 1,
  871. 'log' => '',
  872. 'status' => 1,
  873. 'sticky' => 0,
  874. 'type' => 'page',
  875. 'revisions' => NULL,
  876. 'language' => LANGUAGE_NONE,
  877. );
  878. // Add the body after the language is defined so that it may be set
  879. // properly.
  880. $settings += array(
  881. 'body' => array($settings['language'] => array(array())),
  882. );
  883. // Use the original node's created time for existing nodes.
  884. if (isset($settings['created']) && !isset($settings['date'])) {
  885. $settings['date'] = format_date($settings['created'], 'custom', 'Y-m-d H:i:s O');
  886. }
  887. // If the node's user uid is not specified manually, use the currently
  888. // logged in user if available, or else the user running the test.
  889. if (!isset($settings['uid'])) {
  890. if ($this->loggedInUser) {
  891. $settings['uid'] = $this->loggedInUser->uid;
  892. }
  893. else {
  894. global $user;
  895. $settings['uid'] = $user->uid;
  896. }
  897. }
  898. // Merge body field value and format separately.
  899. $body = array(
  900. 'value' => $this->randomName(32),
  901. 'format' => filter_default_format(),
  902. );
  903. $settings['body'][$settings['language']][0] += $body;
  904. $node = (object) $settings;
  905. node_save($node);
  906. // Small hack to link revisions to our test user.
  907. db_update('node_revision')
  908. ->fields(array('uid' => $node->uid))
  909. ->condition('vid', $node->vid)
  910. ->execute();
  911. return $node;
  912. }
  913. /**
  914. * Creates a custom content type based on default settings.
  915. *
  916. * @param $settings
  917. * An array of settings to change from the defaults.
  918. * Example: 'type' => 'foo'.
  919. * @return
  920. * Created content type.
  921. */
  922. protected function drupalCreateContentType($settings = array()) {
  923. // Find a non-existent random type name.
  924. do {
  925. $name = strtolower($this->randomName(8));
  926. } while (node_type_get_type($name));
  927. // Populate defaults array.
  928. $defaults = array(
  929. 'type' => $name,
  930. 'name' => $name,
  931. 'base' => 'node_content',
  932. 'description' => '',
  933. 'help' => '',
  934. 'title_label' => 'Title',
  935. 'has_title' => 1,
  936. );
  937. // Imposed values for a custom type.
  938. $forced = array(
  939. 'orig_type' => '',
  940. 'old_type' => '',
  941. 'module' => 'node',
  942. 'custom' => 1,
  943. 'modified' => 1,
  944. 'locked' => 0,
  945. );
  946. $type = $forced + $settings + $defaults;
  947. $type = (object) $type;
  948. $saved_type = node_type_save($type);
  949. node_types_rebuild();
  950. menu_rebuild();
  951. node_add_body_field($type);
  952. $this->assertEqual($saved_type, SAVED_NEW, t('Created content type %type.', array('%type' => $type->type)));
  953. // Reset permissions so that permissions for this content type are available.
  954. $this->checkPermissions(array(), TRUE);
  955. return $type;
  956. }
  957. /**
  958. * Get a list files that can be used in tests.
  959. *
  960. * @param $type
  961. * File type, possible values: 'binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'.
  962. * @param $size
  963. * File size in bytes to match. Please check the tests/files folder.
  964. * @return
  965. * List of files that match filter.
  966. */
  967. protected function drupalGetTestFiles($type, $size = NULL) {
  968. if (empty($this->generatedTestFiles)) {
  969. // Generate binary test files.
  970. $lines = array(64, 1024);
  971. $count = 0;
  972. foreach ($lines as $line) {
  973. simpletest_generate_file('binary-' . $count++, 64, $line, 'binary');
  974. }
  975. // Generate text test files.
  976. $lines = array(16, 256, 1024, 2048, 20480);
  977. $count = 0;
  978. foreach ($lines as $line) {
  979. simpletest_generate_file('text-' . $count++, 64, $line, 'text');
  980. }
  981. // Copy other test files from simpletest.
  982. $original = drupal_get_path('module', 'simpletest') . '/files';
  983. $files = file_scan_directory($original, '/(html|image|javascript|php|sql)-.*/');
  984. foreach ($files as $file) {
  985. file_unmanaged_copy($file->uri, variable_get('file_public_path', conf_path() . '/files'));
  986. }
  987. $this->generatedTestFiles = TRUE;
  988. }
  989. $files = array();
  990. // Make sure type is valid.
  991. if (in_array($type, array('binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'))) {
  992. $files = file_scan_directory('public://', '/' . $type . '\-.*/');
  993. // If size is set then remove any files that are not of that size.
  994. if ($size !== NULL) {
  995. foreach ($files as $file) {
  996. $stats = stat($file->uri);
  997. if ($stats['size'] != $size) {
  998. unset($files[$file->uri]);
  999. }
  1000. }
  1001. }
  1002. }
  1003. usort($files, array($this, 'drupalCompareFiles'));
  1004. return $files;
  1005. }
  1006. /**
  1007. * Compare two files based on size and file name.
  1008. */
  1009. protected function drupalCompareFiles($file1, $file2) {
  1010. $compare_size = filesize($file1->uri) - filesize($file2->uri);
  1011. if ($compare_size) {
  1012. // Sort by file size.
  1013. return $compare_size;
  1014. }
  1015. else {
  1016. // The files were the same size, so sort alphabetically.
  1017. return strnatcmp($file1->name, $file2->name);
  1018. }
  1019. }
  1020. /**
  1021. * Create a user with a given set of permissions.
  1022. *
  1023. * @param array $permissions
  1024. * Array of permission names to assign to user. Note that the user always
  1025. * has the default permissions derived from the "authenticated users" role.
  1026. *
  1027. * @return object|false
  1028. * A fully loaded user object with pass_raw property, or FALSE if account
  1029. * creation fails.
  1030. */
  1031. protected function drupalCreateUser(array $permissions = array()) {
  1032. // Create a role with the given permission set, if any.
  1033. $rid = FALSE;
  1034. if ($permissions) {
  1035. $rid = $this->drupalCreateRole($permissions);
  1036. if (!$rid) {
  1037. return FALSE;
  1038. }
  1039. }
  1040. // Create a user assigned to that role.
  1041. $edit = array();
  1042. $edit['name'] = $this->randomName();
  1043. $edit['mail'] = $edit['name'] . '@example.com';
  1044. $edit['pass'] = user_password();
  1045. $edit['status'] = 1;
  1046. if ($rid) {
  1047. $edit['roles'] = array($rid => $rid);
  1048. }
  1049. $account = user_save(drupal_anonymous_user(), $edit);
  1050. $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
  1051. if (empty($account->uid)) {
  1052. return FALSE;
  1053. }
  1054. // Add the raw password so that we can log in as this user.
  1055. $account->pass_raw = $edit['pass'];
  1056. return $account;
  1057. }
  1058. /**
  1059. * Creates a role with specified permissions.
  1060. *
  1061. * @param $permissions
  1062. * Array of permission names to assign to role.
  1063. * @param $name
  1064. * (optional) String for the name of the role. Defaults to a random string.
  1065. * @return
  1066. * Role ID of newly created role, or FALSE if role creation failed.
  1067. */
  1068. protected function drupalCreateRole(array $permissions, $name = NULL) {
  1069. // Generate random name if it was not passed.
  1070. if (!$name) {
  1071. $name = $this->randomName();
  1072. }
  1073. // Check the all the permissions strings are valid.
  1074. if (!$this->checkPermissions($permissions)) {
  1075. return FALSE;
  1076. }
  1077. // Create new role.
  1078. $role = new stdClass();
  1079. $role->name = $name;
  1080. user_role_save($role);
  1081. user_role_grant_permissions($role->rid, $permissions);
  1082. $this->assertTrue(isset($role->rid), t('Created role of name: @name, id: @rid', array('@name' => $name, '@rid' => (isset($role->rid) ? $role->rid : t('-n/a-')))), t('Role'));
  1083. if ($role && !empty($role->rid)) {
  1084. $count = db_query('SELECT COUNT(*) FROM {role_permission} WHERE rid = :rid', array(':rid' => $role->rid))->fetchField();
  1085. $this->assertTrue($count == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
  1086. return $role->rid;
  1087. }
  1088. else {
  1089. return FALSE;
  1090. }
  1091. }
  1092. /**
  1093. * Check to make sure that the array of permissions are valid.
  1094. *
  1095. * @param $permissions
  1096. * Permissions to check.
  1097. * @param $reset
  1098. * Reset cached available permissions.
  1099. * @return
  1100. * TRUE or FALSE depending on whether the permissions are valid.
  1101. */
  1102. protected function checkPermissions(array $permissions, $reset = FALSE) {
  1103. $available = &drupal_static(__FUNCTION__);
  1104. if (!isset($available) || $reset) {
  1105. $available = array_keys(module_invoke_all('permission'));
  1106. }
  1107. $valid = TRUE;
  1108. foreach ($permissions as $permission) {
  1109. if (!in_array($permission, $available)) {
  1110. $this->fail(t('Invalid permission %permission.', array('%permission' => $permission)), t('Role'));
  1111. $valid = FALSE;
  1112. }
  1113. }
  1114. return $valid;
  1115. }
  1116. /**
  1117. * Log in a user with the internal browser.
  1118. *
  1119. * If a user is already logged in, then the current user is logged out before
  1120. * logging in the specified user.
  1121. *
  1122. * Please note that neither the global $user nor the passed-in user object is
  1123. * populated with data of the logged in user. If you need full access to the
  1124. * user object after logging in, it must be updated manually. If you also need
  1125. * access to the plain-text password of the user (set by drupalCreateUser()),
  1126. * e.g. to log in the same user again, then it must be re-assigned manually.
  1127. * For example:
  1128. * @code
  1129. * // Create a user.
  1130. * $account = $this->drupalCreateUser(array());
  1131. * $this->drupalLogin($account);
  1132. * // Load real user object.
  1133. * $pass_raw = $account->pass_raw;
  1134. * $account = user_load($account->uid);
  1135. * $account->pass_raw = $pass_raw;
  1136. * @endcode
  1137. *
  1138. * @param $account
  1139. * User object representing the user to log in.
  1140. *
  1141. * @see drupalCreateUser()
  1142. */
  1143. protected function drupalLogin(stdClass $account) {
  1144. if ($this->loggedInUser) {
  1145. $this->drupalLogout();
  1146. }
  1147. $edit = array(
  1148. 'name' => $account->name,
  1149. 'pass' => $account->pass_raw
  1150. );
  1151. $this->drupalPost('user', $edit, t('Log in'));
  1152. // If a "log out" link appears on the page, it is almost certainly because
  1153. // the login was successful.
  1154. $pass = $this->assertLink(t('Log out'), 0, t('User %name successfully logged in.', array('%name' => $account->name)), t('User login'));
  1155. if ($pass) {
  1156. $this->loggedInUser = $account;
  1157. }
  1158. }
  1159. /**
  1160. * Generate a token for the currently logged in user.
  1161. */
  1162. protected function drupalGetToken($value = '') {
  1163. $private_key = drupal_get_private_key();
  1164. return drupal_hmac_base64($value, $this->session_id . $private_key);
  1165. }
  1166. /*
  1167. * Logs a user out of the internal browser, then check the login page to confirm logout.
  1168. */
  1169. protected function drupalLogout() {
  1170. // Make a request to the logout page, and redirect to the user page, the
  1171. // idea being if you were properly logged out you should be seeing a login
  1172. // screen.
  1173. $this->drupalGet('user/logout');
  1174. $this->drupalGet('user');
  1175. $pass = $this->assertField('name', t('Username field found.'), t('Logout'));
  1176. $pass = $pass && $this->assertField('pass', t('Password field found.'), t('Logout'));
  1177. if ($pass) {
  1178. $this->loggedInUser = FALSE;
  1179. }
  1180. }
  1181. /**
  1182. * Generates a database prefix for running tests.
  1183. *
  1184. * The generated database table prefix is used for the Drupal installation
  1185. * being performed for the test. It is also used as user agent HTTP header
  1186. * value by the cURL-based browser of DrupalWebTestCase, which is sent
  1187. * to the Drupal installation of the test. During early Drupal bootstrap, the
  1188. * user agent HTTP header is parsed, and if it matches, all database queries
  1189. * use the database table prefix that has been generated here.
  1190. *
  1191. * @see DrupalWebTestCase::curlInitialize()
  1192. * @see drupal_valid_test_ua()
  1193. * @see DrupalWebTestCase::setUp()
  1194. */
  1195. protected function prepareDatabasePrefix() {
  1196. $this->databasePrefix = 'simpletest' . mt_rand(1000, 1000000);
  1197. // As soon as the database prefix is set, the test might start to execute.
  1198. // All assertions as well as the SimpleTest batch operations are associated
  1199. // with the testId, so the database prefix has to be associated with it.
  1200. db_update('simpletest_test_id')
  1201. ->fields(array('last_prefix' => $this->databasePrefix))
  1202. ->condition('test_id', $this->testId)
  1203. ->execute();
  1204. }
  1205. /**
  1206. * Changes the database connection to the prefixed one.
  1207. *
  1208. * @see DrupalWebTestCase::setUp()
  1209. */
  1210. protected function changeDatabasePrefix() {
  1211. if (empty($this->databasePrefix)) {
  1212. $this->prepareDatabasePrefix();
  1213. // If $this->prepareDatabasePrefix() failed to work, return without
  1214. // setting $this->setupDatabasePrefix to TRUE, so setUp() methods will
  1215. // know to bail out.
  1216. if (empty($this->databasePrefix)) {
  1217. return;
  1218. }
  1219. }
  1220. // Clone the current connection and replace the current prefix.
  1221. $connection_info = Database::getConnectionInfo('default');
  1222. Database::renameConnection('default', 'simpletest_original_default');
  1223. foreach ($connection_info as $target => $value) {
  1224. $connection_info[$target]['prefix'] = array(
  1225. 'default' => $value['prefix']['default'] . $this->databasePrefix,
  1226. );
  1227. }
  1228. Database::addConnectionInfo('default', 'default', $connection_info['default']);
  1229. // Indicate the database prefix was set up correctly.
  1230. $this->setupDatabasePrefix = TRUE;
  1231. }
  1232. /**
  1233. * Prepares the current environment for running the test.
  1234. *
  1235. * Backups various current environment variables and resets them, so they do
  1236. * not interfere with the Drupal site installation in which tests are executed
  1237. * and can be restored in tearDown().
  1238. *
  1239. * Also sets up new resources for the testing environment, such as the public
  1240. * filesystem and configuration directories.
  1241. *
  1242. * @see DrupalWebTestCase::setUp()
  1243. * @see DrupalWebTestCase::tearDown()
  1244. */
  1245. protected function prepareEnvironment() {
  1246. global $user, $language, $conf;
  1247. // Store necessary current values before switching to prefixed database.
  1248. $this->originalLanguage = $language;
  1249. $this->originalLanguageDefault = variable_get('language_default');
  1250. $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
  1251. $this->originalProfile = drupal_get_profile();
  1252. $this->originalCleanUrl = variable_get('clean_url', 0);
  1253. $this->originalUser = $user;
  1254. // Set to English to prevent exceptions from utf8_truncate() from t()
  1255. // during install if the current language is not 'en'.
  1256. // The following array/object conversion is copied from language_default().
  1257. $language = (object) array('language' => 'en', 'name' => 'English', 'native' => 'English', 'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => '');
  1258. // Save and clean the shutdown callbacks array because it is static cached
  1259. // and will be changed by the test run. Otherwise it will contain callbacks
  1260. // from both environments and the testing environment will try to call the
  1261. // handlers defined by the original one.
  1262. $callbacks = &drupal_register_shutdown_function();
  1263. $this->originalShutdownCallbacks = $callbacks;
  1264. $callbacks = array();
  1265. // Create test directory ahead of installation so fatal errors and debug
  1266. // information can be logged during installation process.
  1267. // Use temporary files directory with the same prefix as the database.
  1268. $this->public_files_directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10);
  1269. $this->private_files_directory = $this->public_files_directory . '/private';
  1270. $this->temp_files_directory = $this->private_files_directory . '/temp';
  1271. // Create the directories
  1272. file_prepare_directory($this->public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  1273. file_prepare_directory($this->private_files_directory, FILE_CREATE_DIRECTORY);
  1274. file_prepare_directory($this->temp_files_directory, FILE_CREATE_DIRECTORY);
  1275. $this->generatedTestFiles = FALSE;
  1276. // Log fatal errors.
  1277. ini_set('log_errors', 1);
  1278. ini_set('error_log', $this->public_files_directory . '/error.log');
  1279. // Set the test information for use in other parts of Drupal.
  1280. $test_info = &$GLOBALS['drupal_test_info'];
  1281. $test_info['test_run_id'] = $this->databasePrefix;
  1282. $test_info['in_child_site'] = FALSE;
  1283. // Indicate the environment was set up correctly.
  1284. $this->setupEnvironment = TRUE;
  1285. }
  1286. /**
  1287. * Sets up a Drupal site for running functional and integration tests.
  1288. *
  1289. * Generates a random database prefix and installs Drupal with the specified
  1290. * installation profile in DrupalWebTestCase::$profile into the
  1291. * prefixed database. Afterwards, installs any additional modules specified by
  1292. * the test.
  1293. *
  1294. * After installation all caches are flushed and several configuration values
  1295. * are reset to the values of the parent site executing the test, since the
  1296. * default values may be incompatible with the environment in which tests are
  1297. * being executed.
  1298. *
  1299. * @param ...
  1300. * List of modules to enable for the duration of the test. This can be
  1301. * either a single array or a variable number of string arguments.
  1302. *
  1303. * @see DrupalWebTestCase::prepareDatabasePrefix()
  1304. * @see DrupalWebTestCase::changeDatabasePrefix()
  1305. * @see DrupalWebTestCase::prepareEnvironment()
  1306. */
  1307. protected function setUp() {
  1308. global $user, $language, $conf;
  1309. // Create the database prefix for this test.
  1310. $this->prepareDatabasePrefix();
  1311. // Prepare the environment for running tests.
  1312. $this->prepareEnvironment();
  1313. if (!$this->setupEnvironment) {
  1314. return FALSE;
  1315. }
  1316. // Reset all statics and variables to perform tests in a clean environment.
  1317. $conf = array();
  1318. drupal_static_reset();
  1319. // Change the database prefix.
  1320. // All static variables need to be reset before the database prefix is
  1321. // changed, since DrupalCacheArray implementations attempt to
  1322. // write back to persistent caches when they are destructed.
  1323. $this->changeDatabasePrefix();
  1324. if (!$this->setupDatabasePrefix) {
  1325. return FALSE;
  1326. }
  1327. // Preset the 'install_profile' system variable, so the first call into
  1328. // system_rebuild_module_data() (in drupal_install_system()) will register
  1329. // the test's profile as a module. Without this, the installation profile of
  1330. // the parent site (executing the test) is registered, and the test
  1331. // profile's hook_install() and other hook implementations are never invoked.
  1332. $conf['install_profile'] = $this->profile;
  1333. // Perform the actual Drupal installation.
  1334. include_once DRUPAL_ROOT . '/includes/install.inc';
  1335. drupal_install_system();
  1336. $this->preloadRegistry();
  1337. // Set path variables.
  1338. variable_set('file_public_path', $this->public_files_directory);
  1339. variable_set('file_private_path', $this->private_files_directory);
  1340. variable_set('file_temporary_path', $this->temp_files_directory);
  1341. // Set the 'simpletest_parent_profile' variable to add the parent profile's
  1342. // search path to the child site's search paths.
  1343. // @see drupal_system_listing()
  1344. // @todo This may need to be primed like 'install_profile' above.
  1345. variable_set('simpletest_parent_profile', $this->originalProfile);
  1346. // Include the testing profile.
  1347. variable_set('install_profile', $this->profile);
  1348. $profile_details = install_profile_info($this->profile, 'en');
  1349. // Install the modules specified by the testing profile.
  1350. module_enable($profile_details['dependencies'], FALSE);
  1351. // Install modules needed for this test. This could have been passed in as
  1352. // either a single array argument or a variable number of string arguments.
  1353. // @todo Remove this compatibility layer in Drupal 8, and only accept
  1354. // $modules as a single array argument.
  1355. $modules = func_get_args();
  1356. if (isset($modules[0]) && is_array($modules[0])) {
  1357. $modules = $modules[0];
  1358. }
  1359. if ($modules) {
  1360. $success = module_enable($modules, TRUE);
  1361. $this->assertTrue($success, t('Enabled modules: %modules', array('%modules' => implode(', ', $modules))));
  1362. }
  1363. // Run the profile tasks.
  1364. $install_profile_module_exists = db_query("SELECT 1 FROM {system} WHERE type = 'module' AND name = :name", array(
  1365. ':name' => $this->profile,
  1366. ))->fetchField();
  1367. if ($install_profile_module_exists) {
  1368. module_enable(array($this->profile), FALSE);
  1369. }
  1370. // Reset/rebuild all data structures after enabling the modules.
  1371. $this->resetAll();
  1372. // Run cron once in that environment, as install.php does at the end of
  1373. // the installation process.
  1374. drupal_cron_run();
  1375. // Ensure that the session is not written to the new environment and replace
  1376. // the global $user session with uid 1 from the new test site.
  1377. drupal_save_session(FALSE);
  1378. // Login as uid 1.
  1379. $user = user_load(1);
  1380. // Restore necessary variables.
  1381. variable_set('install_task', 'done');
  1382. variable_set('clean_url', $this->originalCleanUrl);
  1383. variable_set('site_mail', 'simpletest@example.com');
  1384. variable_set('date_default_timezone', date_default_timezone_get());
  1385. // Set up English language.
  1386. unset($conf['language_default']);
  1387. $language = language_default();
  1388. // Use the test mail class instead of the default mail handler class.
  1389. variable_set('mail_system', array('default-system' => 'TestingMailSystem'));
  1390. drupal_set_time_limit($this->timeLimit);
  1391. $this->setup = TRUE;
  1392. }
  1393. /**
  1394. * Preload the registry from the testing site.
  1395. *
  1396. * This method is called by DrupalWebTestCase::setUp(), and preloads the
  1397. * registry from the testing site to cut down on the time it takes to
  1398. * set up a clean environment for the current test run.
  1399. */
  1400. protected function preloadRegistry() {
  1401. // Use two separate queries, each with their own connections: copy the
  1402. // {registry} and {registry_file} tables over from the parent installation
  1403. // to the child installation.
  1404. $original_connection = Database::getConnection('default', 'simpletest_original_default');
  1405. $test_connection = Database::getConnection();
  1406. foreach (array('registry', 'registry_file') as $table) {
  1407. // Find the records from the parent database.
  1408. $source_query = $original_connection
  1409. ->select($table, array(), array('fetch' => PDO::FETCH_ASSOC))
  1410. ->fields($table);
  1411. $dest_query = $test_connection->insert($table);
  1412. $first = TRUE;
  1413. foreach ($source_query->execute() as $row) {
  1414. if ($first) {
  1415. $dest_query->fields(array_keys($row));
  1416. $first = FALSE;
  1417. }
  1418. // Insert the records into the child database.
  1419. $dest_query->values($row);
  1420. }
  1421. $dest_query->execute();
  1422. }
  1423. }
  1424. /**
  1425. * Reset all data structures after having enabled new modules.
  1426. *
  1427. * This method is called by DrupalWebTestCase::setUp() after enabling
  1428. * the requested modules. It must be called again when additional modules
  1429. * are enabled later.
  1430. */
  1431. protected function resetAll() {
  1432. // Reset all static variables.
  1433. drupal_static_reset();
  1434. // Reset the list of enabled modules.
  1435. module_list(TRUE);
  1436. // Reset cached schema for new database prefix. This must be done before
  1437. // drupal_flush_all_caches() so rebuilds can make use of the schema of
  1438. // modules enabled on the cURL side.
  1439. drupal_get_schema(NULL, TRUE);
  1440. // Perform rebuilds and flush remaining caches.
  1441. drupal_flush_all_caches();
  1442. // Reload global $conf array and permissions.
  1443. $this->refreshVariables();
  1444. $this->checkPermissions(array(), TRUE);
  1445. }
  1446. /**
  1447. * Refresh the in-memory set of variables. Useful after a page request is made
  1448. * that changes a variable in a different thread.
  1449. *
  1450. * In other words calling a settings page with $this->drupalPost() with a changed
  1451. * value would update a variable to reflect that change, but in the thread that
  1452. * made the call (thread running the test) the changed variable would not be
  1453. * picked up.
  1454. *
  1455. * This method clears the variables cache and loads a fresh copy from the database
  1456. * to ensure that the most up-to-date set of variables is loaded.
  1457. */
  1458. protected function refreshVariables() {
  1459. global $conf;
  1460. cache_clear_all('variables', 'cache_bootstrap');
  1461. $conf = variable_initialize();
  1462. }
  1463. /**
  1464. * Delete created files and temporary files directory, delete the tables created by setUp(),
  1465. * and reset the database prefix.
  1466. */
  1467. protected function tearDown() {
  1468. global $user, $language;
  1469. // In case a fatal error occurred that was not in the test process read the
  1470. // log to pick up any fatal errors.
  1471. simpletest_log_read($this->testId, $this->databasePrefix, get_class($this), TRUE);
  1472. $emailCount = count(variable_get('drupal_test_email_collector', array()));
  1473. if ($emailCount) {
  1474. $message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.');
  1475. $this->pass($message, t('E-mail'));
  1476. }
  1477. // Delete temporary files directory.
  1478. file_unmanaged_delete_recursive($this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10));
  1479. // Remove all prefixed tables.
  1480. $tables = db_find_tables($this->databasePrefix . '%');
  1481. $connection_info = Database::getConnectionInfo('default');
  1482. $tables = db_find_tables($connection_info['default']['prefix']['default'] . '%');
  1483. if (empty($tables)) {
  1484. $this->fail('Failed to find test tables to drop.');
  1485. }
  1486. $prefix_length = strlen($connection_info['default']['prefix']['default']);
  1487. foreach ($tables as $table) {
  1488. if (db_drop_table(substr($table, $prefix_length))) {
  1489. unset($tables[$table]);
  1490. }
  1491. }
  1492. if (!empty($tables)) {
  1493. $this->fail('Failed to drop all prefixed tables.');
  1494. }
  1495. // Get back to the original connection.
  1496. Database::removeConnection('default');
  1497. Database::renameConnection('simpletest_original_default', 'default');
  1498. // Restore original shutdown callbacks array to prevent original
  1499. // environment of calling handlers from test run.
  1500. $callbacks = &drupal_register_shutdown_function();
  1501. $callbacks = $this->originalShutdownCallbacks;
  1502. // Return the user to the original one.
  1503. $user = $this->originalUser;
  1504. drupal_save_session(TRUE);
  1505. // Ensure that internal logged in variable and cURL options are reset.
  1506. $this->loggedInUser = FALSE;
  1507. $this->additionalCurlOptions = array();
  1508. // Reload module list and implementations to ensure that test module hooks
  1509. // aren't called after tests.
  1510. module_list(TRUE);
  1511. module_implements('', FALSE, TRUE);
  1512. // Reset the Field API.
  1513. field_cache_clear();
  1514. // Rebuild caches.
  1515. $this->refreshVariables();
  1516. // Reset public files directory.
  1517. $GLOBALS['conf']['file_public_path'] = $this->originalFileDirectory;
  1518. // Reset language.
  1519. $language = $this->originalLanguage;
  1520. if ($this->originalLanguageDefault) {
  1521. $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault;
  1522. }
  1523. // Close the CURL handler and reset the cookies array so test classes
  1524. // containing multiple tests are not polluted.
  1525. $this->curlClose();
  1526. $this->cookies = array();
  1527. }
  1528. /**
  1529. * Initializes the cURL connection.
  1530. *
  1531. * If the simpletest_httpauth_credentials variable is set, this function will
  1532. * add HTTP authentication headers. This is necessary for testing sites that
  1533. * are protected by login credentials from public access.
  1534. * See the description of $curl_options for other options.
  1535. */
  1536. protected function curlInitialize() {
  1537. global $base_url;
  1538. if (!isset($this->curlHandle)) {
  1539. $this->curlHandle = curl_init();
  1540. // Some versions/configurations of cURL break on a NULL cookie jar, so
  1541. // supply a real file.
  1542. if (empty($this->cookieFile)) {
  1543. $this->cookieFile = $this->public_files_directory . '/cookie.jar';
  1544. }
  1545. $curl_options = array(
  1546. CURLOPT_COOKIEJAR => $this->cookieFile,
  1547. CURLOPT_URL => $base_url,
  1548. CURLOPT_FOLLOWLOCATION => FALSE,
  1549. CURLOPT_RETURNTRANSFER => TRUE,
  1550. CURLOPT_SSL_VERIFYPEER => FALSE, // Required to make the tests run on HTTPS.
  1551. CURLOPT_SSL_VERIFYHOST => FALSE, // Required to make the tests run on HTTPS.
  1552. CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'),
  1553. CURLOPT_USERAGENT => $this->databasePrefix,
  1554. );
  1555. if (isset($this->httpauth_credentials)) {
  1556. $curl_options[CURLOPT_HTTPAUTH] = $this->httpauth_method;
  1557. $curl_options[CURLOPT_USERPWD] = $this->httpauth_credentials;
  1558. }
  1559. // curl_setopt_array() returns FALSE if any of the specified options
  1560. // cannot be set, and stops processing any further options.
  1561. $result = curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
  1562. if (!$result) {
  1563. throw new Exception('One or more cURL options could not be set.');
  1564. }
  1565. // By default, the child session name should be the same as the parent.
  1566. $this->session_name = session_name();
  1567. }
  1568. // We set the user agent header on each request so as to use the current
  1569. // time and a new uniqid.
  1570. if (preg_match('/simpletest\d+/', $this->databasePrefix, $matches)) {
  1571. curl_setopt($this->curlHandle, CURLOPT_USERAGENT, drupal_generate_test_ua($matches[0]));
  1572. }
  1573. }
  1574. /**
  1575. * Initializes and executes a cURL request.
  1576. *
  1577. * @param $curl_options
  1578. * An associative array of cURL options to set, where the keys are constants
  1579. * defined by the cURL library. For a list of valid options, see
  1580. * http://www.php.net/manual/function.curl-setopt.php
  1581. * @param $redirect
  1582. * FALSE if this is an initial request, TRUE if this request is the result
  1583. * of a redirect.
  1584. *
  1585. * @return
  1586. * The content returned from the call to curl_exec().
  1587. *
  1588. * @see curlInitialize()
  1589. */
  1590. protected function curlExec($curl_options, $redirect = FALSE) {
  1591. $this->curlInitialize();
  1592. if (!empty($curl_options[CURLOPT_URL])) {
  1593. // Forward XDebug activation if present.
  1594. if (isset($_COOKIE['XDEBUG_SESSION'])) {
  1595. $options = drupal_parse_url($curl_options[CURLOPT_URL]);
  1596. $options += array('query' => array());
  1597. $options['query'] += array('XDEBUG_SESSION_START' => $_COOKIE['XDEBUG_SESSION']);
  1598. $curl_options[CURLOPT_URL] = url($options['path'], $options);
  1599. }
  1600. // cURL incorrectly handles URLs with a fragment by including the
  1601. // fragment in the request to the server, causing some web servers
  1602. // to reject the request citing "400 - Bad Request". To prevent
  1603. // this, we strip the fragment from the request.
  1604. // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
  1605. if (strpos($curl_options[CURLOPT_URL], '#')) {
  1606. $original_url = $curl_options[CURLOPT_URL];
  1607. $curl_options[CURLOPT_URL] = strtok($curl_options[CURLOPT_URL], '#');
  1608. }
  1609. }
  1610. $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
  1611. if (!empty($curl_options[CURLOPT_POST])) {
  1612. // This is a fix for the Curl library to prevent Expect: 100-continue
  1613. // headers in POST requests, that may cause unexpected HTTP response
  1614. // codes from some webservers (like lighttpd that returns a 417 error
  1615. // code). It is done by setting an empty "Expect" header field that is
  1616. // not overwritten by Curl.
  1617. $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
  1618. }
  1619. curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
  1620. if (!$redirect) {
  1621. // Reset headers, the session ID and the redirect counter.
  1622. $this->session_id = NULL;
  1623. $this->headers = array();
  1624. $this->redirect_count = 0;
  1625. }
  1626. $content = curl_exec($this->curlHandle);
  1627. $status = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  1628. // cURL incorrectly handles URLs with fragments, so instead of
  1629. // letting cURL handle redirects we take of them ourselves to
  1630. // to prevent fragments being sent to the web server as part
  1631. // of the request.
  1632. // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
  1633. if (in_array($status, array(300, 301, 302, 303, 305, 307)) && $this->redirect_count < variable_get('simpletest_maximum_redirects', 5)) {
  1634. if ($this->drupalGetHeader('location')) {
  1635. $this->redirect_count++;
  1636. $curl_options = array();
  1637. $curl_options[CURLOPT_URL] = $this->drupalGetHeader('location');
  1638. $curl_options[CURLOPT_HTTPGET] = TRUE;
  1639. return $this->curlExec($curl_options, TRUE);
  1640. }
  1641. }
  1642. $this->drupalSetContent($content, isset($original_url) ? $original_url : curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL));
  1643. $message_vars = array(
  1644. '!method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
  1645. '@url' => isset($original_url) ? $original_url : $url,
  1646. '@status' => $status,
  1647. '!length' => format_size(strlen($this->drupalGetContent()))
  1648. );
  1649. $message = t('!method @url returned @status (!length).', $message_vars);
  1650. $this->assertTrue($this->drupalGetContent() !== FALSE, $message, t('Browser'));
  1651. return $this->drupalGetContent();
  1652. }
  1653. /**
  1654. * Reads headers and registers errors received from the tested site.
  1655. *
  1656. * @see _drupal_log_error().
  1657. *
  1658. * @param $curlHandler
  1659. * The cURL handler.
  1660. * @param $header
  1661. * An header.
  1662. */
  1663. protected function curlHeaderCallback($curlHandler, $header) {
  1664. // Header fields can be extended over multiple lines by preceding each
  1665. // extra line with at least one SP or HT. They should be joined on receive.
  1666. // Details are in RFC2616 section 4.
  1667. if ($header[0] == ' ' || $header[0] == "\t") {
  1668. // Normalize whitespace between chucks.
  1669. $this->headers[] = array_pop($this->headers) . ' ' . trim($header);
  1670. }
  1671. else {
  1672. $this->headers[] = $header;
  1673. }
  1674. // Errors are being sent via X-Drupal-Assertion-* headers,
  1675. // generated by _drupal_log_error() in the exact form required
  1676. // by DrupalWebTestCase::error().
  1677. if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
  1678. // Call DrupalWebTestCase::error() with the parameters from the header.
  1679. call_user_func_array(array(&$this, 'error'), unserialize(urldecode($matches[1])));
  1680. }
  1681. // Save cookies.
  1682. if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
  1683. $name = $matches[1];
  1684. $parts = array_map('trim', explode(';', $matches[2]));
  1685. $value = array_shift($parts);
  1686. $this->cookies[$name] = array('value' => $value, 'secure' => in_array('secure', $parts));
  1687. if ($name == $this->session_name) {
  1688. if ($value != 'deleted') {
  1689. $this->session_id = $value;
  1690. }
  1691. else {
  1692. $this->session_id = NULL;
  1693. }
  1694. }
  1695. }
  1696. // This is required by cURL.
  1697. return strlen($header);
  1698. }
  1699. /**
  1700. * Close the cURL handler and unset the handler.
  1701. */
  1702. protected function curlClose() {
  1703. if (isset($this->curlHandle)) {
  1704. curl_close($this->curlHandle);
  1705. unset($this->curlHandle);
  1706. }
  1707. }
  1708. /**
  1709. * Parse content returned from curlExec using DOM and SimpleXML.
  1710. *
  1711. * @return
  1712. * A SimpleXMLElement or FALSE on failure.
  1713. */
  1714. protected function parse() {
  1715. if (!$this->elements) {
  1716. // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
  1717. // them.
  1718. $htmlDom = new DOMDocument();
  1719. @$htmlDom->loadHTML($this->drupalGetContent());
  1720. if ($htmlDom) {
  1721. $this->pass(t('Valid HTML found on "@path"', array('@path' => $this->getUrl())), t('Browser'));
  1722. // It's much easier to work with simplexml than DOM, luckily enough
  1723. // we can just simply import our DOM tree.
  1724. $this->elements = simplexml_import_dom($htmlDom);
  1725. }
  1726. }
  1727. if (!$this->elements) {
  1728. $this->fail(t('Parsed page successfully.'), t('Browser'));
  1729. }
  1730. return $this->elements;
  1731. }
  1732. /**
  1733. * Retrieves a Drupal path or an absolute path.
  1734. *
  1735. * @param $path
  1736. * Drupal path or URL to load into internal browser
  1737. * @param $options
  1738. * Options to be forwarded to url().
  1739. * @param $headers
  1740. * An array containing additional HTTP request headers, each formatted as
  1741. * "name: value".
  1742. * @return
  1743. * The retrieved HTML string, also available as $this->drupalGetContent()
  1744. */
  1745. protected function drupalGet($path, array $options = array(), array $headers = array()) {
  1746. $options['absolute'] = TRUE;
  1747. // We re-using a CURL connection here. If that connection still has certain
  1748. // options set, it might change the GET into a POST. Make sure we clear out
  1749. // previous options.
  1750. $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers));
  1751. $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
  1752. // Replace original page output with new output from redirected page(s).
  1753. if ($new = $this->checkForMetaRefresh()) {
  1754. $out = $new;
  1755. }
  1756. $this->verbose('GET request to: ' . $path .
  1757. '<hr />Ending URL: ' . $this->getUrl() .
  1758. '<hr />' . $out);
  1759. return $out;
  1760. }
  1761. /**
  1762. * Retrieve a Drupal path or an absolute path and JSON decode the result.
  1763. */
  1764. protected function drupalGetAJAX($path, array $options = array(), array $headers = array()) {
  1765. return drupal_json_decode($this->drupalGet($path, $options, $headers));
  1766. }
  1767. /**
  1768. * Execute a POST request on a Drupal page.
  1769. * It will be done as usual POST request with SimpleBrowser.
  1770. *
  1771. * @param $path
  1772. * Location of the post form. Either a Drupal path or an absolute path or
  1773. * NULL to post to the current page. For multi-stage forms you can set the
  1774. * path to NULL and have it post to the last received page. Example:
  1775. *
  1776. * @code
  1777. * // First step in form.
  1778. * $edit = array(...);
  1779. * $this->drupalPost('some_url', $edit, t('Save'));
  1780. *
  1781. * // Second step in form.
  1782. * $edit = array(...);
  1783. * $this->drupalPost(NULL, $edit, t('Save'));
  1784. * @endcode
  1785. * @param $edit
  1786. * Field data in an associative array. Changes the current input fields
  1787. * (where possible) to the values indicated. A checkbox can be set to
  1788. * TRUE to be checked and FALSE to be unchecked. Note that when a form
  1789. * contains file upload fields, other fields cannot start with the '@'
  1790. * character.
  1791. *
  1792. * Multiple select fields can be set using name[] and setting each of the
  1793. * possible values. Example:
  1794. * @code
  1795. * $edit = array();
  1796. * $edit['name[]'] = array('value1', 'value2');
  1797. * @endcode
  1798. * @param $submit
  1799. * Value of the submit button whose click is to be emulated. For example,
  1800. * t('Save'). The processing of the request depends on this value. For
  1801. * example, a form may have one button with the value t('Save') and another
  1802. * button with the value t('Delete'), and execute different code depending
  1803. * on which one is clicked.
  1804. *
  1805. * This function can also be called to emulate an Ajax submission. In this
  1806. * case, this value needs to be an array with the following keys:
  1807. * - path: A path to submit the form values to for Ajax-specific processing,
  1808. * which is likely different than the $path parameter used for retrieving
  1809. * the initial form. Defaults to 'system/ajax'.
  1810. * - triggering_element: If the value for the 'path' key is 'system/ajax' or
  1811. * another generic Ajax processing path, this needs to be set to the name
  1812. * of the element. If the name doesn't identify the element uniquely, then
  1813. * this should instead be an array with a single key/value pair,
  1814. * corresponding to the element name and value. The callback for the
  1815. * generic Ajax processing path uses this to find the #ajax information
  1816. * for the element, including which specific callback to use for
  1817. * processing the request.
  1818. *
  1819. * This can also be set to NULL in order to emulate an Internet Explorer
  1820. * submission of a form with a single text field, and pressing ENTER in that
  1821. * textfield: under these conditions, no button information is added to the
  1822. * POST data.
  1823. * @param $options
  1824. * Options to be forwarded to url().
  1825. * @param $headers
  1826. * An array containing additional HTTP request headers, each formatted as
  1827. * "name: value".
  1828. * @param $form_html_id
  1829. * (optional) HTML ID of the form to be submitted. On some pages
  1830. * there are many identical forms, so just using the value of the submit
  1831. * button is not enough. For example: 'trigger-node-presave-assign-form'.
  1832. * Note that this is not the Drupal $form_id, but rather the HTML ID of the
  1833. * form, which is typically the same thing but with hyphens replacing the
  1834. * underscores.
  1835. * @param $extra_post
  1836. * (optional) A string of additional data to append to the POST submission.
  1837. * This can be used to add POST data for which there are no HTML fields, as
  1838. * is done by drupalPostAJAX(). This string is literally appended to the
  1839. * POST data, so it must already be urlencoded and contain a leading "&"
  1840. * (e.g., "&extra_var1=hello+world&extra_var2=you%26me").
  1841. */
  1842. protected function drupalPost($path, $edit, $submit, array $options = array(), array $headers = array(), $form_html_id = NULL, $extra_post = NULL) {
  1843. $submit_matches = FALSE;
  1844. $ajax = is_array($submit);
  1845. if (isset($path)) {
  1846. $this->drupalGet($path, $options);
  1847. }
  1848. if ($this->parse()) {
  1849. $edit_save = $edit;
  1850. // Let's iterate over all the forms.
  1851. $xpath = "//form";
  1852. if (!empty($form_html_id)) {
  1853. $xpath .= "[@id='" . $form_html_id . "']";
  1854. }
  1855. $forms = $this->xpath($xpath);
  1856. foreach ($forms as $form) {
  1857. // We try to set the fields of this form as specified in $edit.
  1858. $edit = $edit_save;
  1859. $post = array();
  1860. $upload = array();
  1861. $submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
  1862. $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
  1863. if ($ajax) {
  1864. $action = $this->getAbsoluteUrl(!empty($submit['path']) ? $submit['path'] : 'system/ajax');
  1865. // Ajax callbacks verify the triggering element if necessary, so while
  1866. // we may eventually want extra code that verifies it in the
  1867. // handleForm() function, it's not currently a requirement.
  1868. $submit_matches = TRUE;
  1869. }
  1870. // We post only if we managed to handle every field in edit and the
  1871. // submit button matches.
  1872. if (!$edit && ($submit_matches || !isset($submit))) {
  1873. $post_array = $post;
  1874. if ($upload) {
  1875. // TODO: cURL handles file uploads for us, but the implementation
  1876. // is broken. This is a less than elegant workaround. Alternatives
  1877. // are being explored at #253506.
  1878. foreach ($upload as $key => $file) {
  1879. $file = drupal_realpath($file);
  1880. if ($file && is_file($file)) {
  1881. // Use the new CurlFile class for file uploads when using PHP
  1882. // 5.5 or higher.
  1883. if (class_exists('CurlFile')) {
  1884. $post[$key] = curl_file_create($file);
  1885. }
  1886. else {
  1887. $post[$key] = '@' . $file;
  1888. }
  1889. }
  1890. }
  1891. }
  1892. else {
  1893. foreach ($post as $key => $value) {
  1894. // Encode according to application/x-www-form-urlencoded
  1895. // Both names and values needs to be urlencoded, according to
  1896. // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
  1897. $post[$key] = urlencode($key) . '=' . urlencode($value);
  1898. }
  1899. $post = implode('&', $post) . $extra_post;
  1900. }
  1901. $out = $this->curlExec(array(CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers));
  1902. // Ensure that any changes to variables in the other thread are picked up.
  1903. $this->refreshVariables();
  1904. // Replace original page output with new output from redirected page(s).
  1905. if ($new = $this->checkForMetaRefresh()) {
  1906. $out = $new;
  1907. }
  1908. $this->verbose('POST request to: ' . $path .
  1909. '<hr />Ending URL: ' . $this->getUrl() .
  1910. '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE) .
  1911. '<hr />' . $out);
  1912. return $out;
  1913. }
  1914. }
  1915. // We have not found a form which contained all fields of $edit.
  1916. foreach ($edit as $name => $value) {
  1917. $this->fail(t('Failed to set field @name to @value', array('@name' => $name, '@value' => $value)));
  1918. }
  1919. if (!$ajax && isset($submit)) {
  1920. $this->assertTrue($submit_matches, t('Found the @submit button', array('@submit' => $submit)));
  1921. }
  1922. $this->fail(t('Found the requested form fields at @path', array('@path' => $path)));
  1923. }
  1924. }
  1925. /**
  1926. * Execute an Ajax submission.
  1927. *
  1928. * This executes a POST as ajax.js does. It uses the returned JSON data, an
  1929. * array of commands, to update $this->content using equivalent DOM
  1930. * manipulation as is used by ajax.js. It also returns the array of commands.
  1931. *
  1932. * @param $path
  1933. * Location of the form containing the Ajax enabled element to test. Can be
  1934. * either a Drupal path or an absolute path or NULL to use the current page.
  1935. * @param $edit
  1936. * Field data in an associative array. Changes the current input fields
  1937. * (where possible) to the values indicated.
  1938. * @param $triggering_element
  1939. * The name of the form element that is responsible for triggering the Ajax
  1940. * functionality to test. May be a string or, if the triggering element is
  1941. * a button, an associative array where the key is the name of the button
  1942. * and the value is the button label. i.e.) array('op' => t('Refresh')).
  1943. * @param $ajax_path
  1944. * (optional) Override the path set by the Ajax settings of the triggering
  1945. * element. In the absence of both the triggering element's Ajax path and
  1946. * $ajax_path 'system/ajax' will be used.
  1947. * @param $options
  1948. * (optional) Options to be forwarded to url().
  1949. * @param $headers
  1950. * (optional) An array containing additional HTTP request headers, each
  1951. * formatted as "name: value". Forwarded to drupalPost().
  1952. * @param $form_html_id
  1953. * (optional) HTML ID of the form to be submitted, use when there is more
  1954. * than one identical form on the same page and the value of the triggering
  1955. * element is not enough to identify the form. Note this is not the Drupal
  1956. * ID of the form but rather the HTML ID of the form.
  1957. * @param $ajax_settings
  1958. * (optional) An array of Ajax settings which if specified will be used in
  1959. * place of the Ajax settings of the triggering element.
  1960. *
  1961. * @return
  1962. * An array of Ajax commands.
  1963. *
  1964. * @see drupalPost()
  1965. * @see ajax.js
  1966. */
  1967. protected function drupalPostAJAX($path, $edit, $triggering_element, $ajax_path = NULL, array $options = array(), array $headers = array(), $form_html_id = NULL, $ajax_settings = NULL) {
  1968. // Get the content of the initial page prior to calling drupalPost(), since
  1969. // drupalPost() replaces $this->content.
  1970. if (isset($path)) {
  1971. $this->drupalGet($path, $options);
  1972. }
  1973. $content = $this->content;
  1974. $drupal_settings = $this->drupalSettings;
  1975. // Get the Ajax settings bound to the triggering element.
  1976. if (!isset($ajax_settings)) {
  1977. if (is_array($triggering_element)) {
  1978. $xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
  1979. }
  1980. else {
  1981. $xpath = '//*[@name="' . $triggering_element . '"]';
  1982. }
  1983. if (isset($form_html_id)) {
  1984. $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
  1985. }
  1986. $element = $this->xpath($xpath);
  1987. $element_id = (string) $element[0]['id'];
  1988. $ajax_settings = $drupal_settings['ajax'][$element_id];
  1989. }
  1990. // Add extra information to the POST data as ajax.js does.
  1991. $extra_post = '';
  1992. if (isset($ajax_settings['submit'])) {
  1993. foreach ($ajax_settings['submit'] as $key => $value) {
  1994. $extra_post .= '&' . urlencode($key) . '=' . urlencode($value);
  1995. }
  1996. }
  1997. foreach ($this->xpath('//*[@id]') as $element) {
  1998. $id = (string) $element['id'];
  1999. $extra_post .= '&' . urlencode('ajax_html_ids[]') . '=' . urlencode($id);
  2000. }
  2001. if (isset($drupal_settings['ajaxPageState'])) {
  2002. $extra_post .= '&' . urlencode('ajax_page_state[theme]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme']);
  2003. $extra_post .= '&' . urlencode('ajax_page_state[theme_token]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme_token']);
  2004. foreach ($drupal_settings['ajaxPageState']['css'] as $key => $value) {
  2005. $extra_post .= '&' . urlencode("ajax_page_state[css][$key]") . '=1';
  2006. }
  2007. foreach ($drupal_settings['ajaxPageState']['js'] as $key => $value) {
  2008. $extra_post .= '&' . urlencode("ajax_page_state[js][$key]") . '=1';
  2009. }
  2010. }
  2011. // Unless a particular path is specified, use the one specified by the
  2012. // Ajax settings, or else 'system/ajax'.
  2013. if (!isset($ajax_path)) {
  2014. $ajax_path = isset($ajax_settings['url']) ? $ajax_settings['url'] : 'system/ajax';
  2015. }
  2016. // Submit the POST request.
  2017. $return = drupal_json_decode($this->drupalPost(NULL, $edit, array('path' => $ajax_path, 'triggering_element' => $triggering_element), $options, $headers, $form_html_id, $extra_post));
  2018. $this->assertIdentical($this->drupalGetHeader('X-Drupal-Ajax-Token'), '1', 'Ajax response header found.');
  2019. // Change the page content by applying the returned commands.
  2020. if (!empty($ajax_settings) && !empty($return)) {
  2021. // ajax.js applies some defaults to the settings object, so do the same
  2022. // for what's used by this function.
  2023. $ajax_settings += array(
  2024. 'method' => 'replaceWith',
  2025. );
  2026. // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
  2027. // them.
  2028. $dom = new DOMDocument();
  2029. @$dom->loadHTML($content);
  2030. // XPath allows for finding wrapper nodes better than DOM does.
  2031. $xpath = new DOMXPath($dom);
  2032. foreach ($return as $command) {
  2033. switch ($command['command']) {
  2034. case 'settings':
  2035. $drupal_settings = drupal_array_merge_deep($drupal_settings, $command['settings']);
  2036. break;
  2037. case 'insert':
  2038. $wrapperNode = NULL;
  2039. // When a command doesn't specify a selector, use the
  2040. // #ajax['wrapper'] which is always an HTML ID.
  2041. if (!isset($command['selector'])) {
  2042. $wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0);
  2043. }
  2044. // @todo Ajax commands can target any jQuery selector, but these are
  2045. // hard to fully emulate with XPath. For now, just handle 'head'
  2046. // and 'body', since these are used by ajax_render().
  2047. elseif (in_array($command['selector'], array('head', 'body'))) {
  2048. $wrapperNode = $xpath->query('//' . $command['selector'])->item(0);
  2049. }
  2050. if ($wrapperNode) {
  2051. // ajax.js adds an enclosing DIV to work around a Safari bug.
  2052. $newDom = new DOMDocument();
  2053. // DOM can load HTML soup. But, HTML soup can throw warnings,
  2054. // suppress them.
  2055. $newDom->loadHTML('<div>' . $command['data'] . '</div>');
  2056. // Suppress warnings thrown when duplicate HTML IDs are
  2057. // encountered. This probably means we are replacing an element
  2058. // with the same ID.
  2059. $newNode = @$dom->importNode($newDom->documentElement->firstChild->firstChild, TRUE);
  2060. $method = isset($command['method']) ? $command['method'] : $ajax_settings['method'];
  2061. // The "method" is a jQuery DOM manipulation function. Emulate
  2062. // each one using PHP's DOMNode API.
  2063. switch ($method) {
  2064. case 'replaceWith':
  2065. $wrapperNode->parentNode->replaceChild($newNode, $wrapperNode);
  2066. break;
  2067. case 'append':
  2068. $wrapperNode->appendChild($newNode);
  2069. break;
  2070. case 'prepend':
  2071. // If no firstChild, insertBefore() falls back to
  2072. // appendChild().
  2073. $wrapperNode->insertBefore($newNode, $wrapperNode->firstChild);
  2074. break;
  2075. case 'before':
  2076. $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode);
  2077. break;
  2078. case 'after':
  2079. // If no nextSibling, insertBefore() falls back to
  2080. // appendChild().
  2081. $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling);
  2082. break;
  2083. case 'html':
  2084. foreach ($wrapperNode->childNodes as $childNode) {
  2085. $wrapperNode->removeChild($childNode);
  2086. }
  2087. $wrapperNode->appendChild($newNode);
  2088. break;
  2089. }
  2090. }
  2091. break;
  2092. case 'updateBuildId':
  2093. $buildId = $xpath->query('//input[@name="form_build_id" and @value="' . $command['old'] . '"]')->item(0);
  2094. if ($buildId) {
  2095. $buildId->setAttribute('value', $command['new']);
  2096. }
  2097. break;
  2098. // @todo Add suitable implementations for these commands in order to
  2099. // have full test coverage of what ajax.js can do.
  2100. case 'remove':
  2101. break;
  2102. case 'changed':
  2103. break;
  2104. case 'css':
  2105. break;
  2106. case 'data':
  2107. break;
  2108. case 'restripe':
  2109. break;
  2110. case 'add_css':
  2111. break;
  2112. }
  2113. }
  2114. $content = $dom->saveHTML();
  2115. }
  2116. $this->drupalSetContent($content);
  2117. $this->drupalSetSettings($drupal_settings);
  2118. $verbose = 'AJAX POST request to: ' . $path;
  2119. $verbose .= '<br />AJAX callback path: ' . $ajax_path;
  2120. $verbose .= '<hr />Ending URL: ' . $this->getUrl();
  2121. $verbose .= '<hr />' . $this->content;
  2122. $this->verbose($verbose);
  2123. return $return;
  2124. }
  2125. /**
  2126. * Runs cron in the Drupal installed by Simpletest.
  2127. */
  2128. protected function cronRun() {
  2129. $this->drupalGet($GLOBALS['base_url'] . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => variable_get('cron_key', 'drupal'))));
  2130. }
  2131. /**
  2132. * Check for meta refresh tag and if found call drupalGet() recursively. This
  2133. * function looks for the http-equiv attribute to be set to "Refresh"
  2134. * and is case-sensitive.
  2135. *
  2136. * @return
  2137. * Either the new page content or FALSE.
  2138. */
  2139. protected function checkForMetaRefresh() {
  2140. if (strpos($this->drupalGetContent(), '<meta ') && $this->parse()) {
  2141. $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
  2142. if (!empty($refresh)) {
  2143. // Parse the content attribute of the meta tag for the format:
  2144. // "[delay]: URL=[page_to_redirect_to]".
  2145. if (preg_match('/\d+;\s*URL=(?P<url>.*)/i', $refresh[0]['content'], $match)) {
  2146. return $this->drupalGet($this->getAbsoluteUrl(decode_entities($match['url'])));
  2147. }
  2148. }
  2149. }
  2150. return FALSE;
  2151. }
  2152. /**
  2153. * Retrieves only the headers for a Drupal path or an absolute path.
  2154. *
  2155. * @param $path
  2156. * Drupal path or URL to load into internal browser
  2157. * @param $options
  2158. * Options to be forwarded to url().
  2159. * @param $headers
  2160. * An array containing additional HTTP request headers, each formatted as
  2161. * "name: value".
  2162. * @return
  2163. * The retrieved headers, also available as $this->drupalGetContent()
  2164. */
  2165. protected function drupalHead($path, array $options = array(), array $headers = array()) {
  2166. $options['absolute'] = TRUE;
  2167. $out = $this->curlExec(array(CURLOPT_NOBODY => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_HTTPHEADER => $headers));
  2168. $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
  2169. return $out;
  2170. }
  2171. /**
  2172. * Handle form input related to drupalPost(). Ensure that the specified fields
  2173. * exist and attempt to create POST data in the correct manner for the particular
  2174. * field type.
  2175. *
  2176. * @param $post
  2177. * Reference to array of post values.
  2178. * @param $edit
  2179. * Reference to array of edit values to be checked against the form.
  2180. * @param $submit
  2181. * Form submit button value.
  2182. * @param $form
  2183. * Array of form elements.
  2184. * @return
  2185. * Submit value matches a valid submit input in the form.
  2186. */
  2187. protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
  2188. // Retrieve the form elements.
  2189. $elements = $form->xpath('.//input[not(@disabled)]|.//textarea[not(@disabled)]|.//select[not(@disabled)]');
  2190. $submit_matches = FALSE;
  2191. foreach ($elements as $element) {
  2192. // SimpleXML objects need string casting all the time.
  2193. $name = (string) $element['name'];
  2194. // This can either be the type of <input> or the name of the tag itself
  2195. // for <select> or <textarea>.
  2196. $type = isset($element['type']) ? (string) $element['type'] : $element->getName();
  2197. $value = isset($element['value']) ? (string) $element['value'] : '';
  2198. $done = FALSE;
  2199. if (isset($edit[$name])) {
  2200. switch ($type) {
  2201. case 'text':
  2202. case 'tel':
  2203. case 'textarea':
  2204. case 'url':
  2205. case 'number':
  2206. case 'range':
  2207. case 'color':
  2208. case 'hidden':
  2209. case 'password':
  2210. case 'email':
  2211. case 'search':
  2212. $post[$name] = $edit[$name];
  2213. unset($edit[$name]);
  2214. break;
  2215. case 'radio':
  2216. if ($edit[$name] == $value) {
  2217. $post[$name] = $edit[$name];
  2218. unset($edit[$name]);
  2219. }
  2220. break;
  2221. case 'checkbox':
  2222. // To prevent checkbox from being checked.pass in a FALSE,
  2223. // otherwise the checkbox will be set to its value regardless
  2224. // of $edit.
  2225. if ($edit[$name] === FALSE) {
  2226. unset($edit[$name]);
  2227. continue 2;
  2228. }
  2229. else {
  2230. unset($edit[$name]);
  2231. $post[$name] = $value;
  2232. }
  2233. break;
  2234. case 'select':
  2235. $new_value = $edit[$name];
  2236. $options = $this->getAllOptions($element);
  2237. if (is_array($new_value)) {
  2238. // Multiple select box.
  2239. if (!empty($new_value)) {
  2240. $index = 0;
  2241. $key = preg_replace('/\[\]$/', '', $name);
  2242. foreach ($options as $option) {
  2243. $option_value = (string) $option['value'];
  2244. if (in_array($option_value, $new_value)) {
  2245. $post[$key . '[' . $index++ . ']'] = $option_value;
  2246. $done = TRUE;
  2247. unset($edit[$name]);
  2248. }
  2249. }
  2250. }
  2251. else {
  2252. // No options selected: do not include any POST data for the
  2253. // element.
  2254. $done = TRUE;
  2255. unset($edit[$name]);
  2256. }
  2257. }
  2258. else {
  2259. // Single select box.
  2260. foreach ($options as $option) {
  2261. if ($new_value == $option['value']) {
  2262. $post[$name] = $new_value;
  2263. unset($edit[$name]);
  2264. $done = TRUE;
  2265. break;
  2266. }
  2267. }
  2268. }
  2269. break;
  2270. case 'file':
  2271. $upload[$name] = $edit[$name];
  2272. unset($edit[$name]);
  2273. break;
  2274. }
  2275. }
  2276. if (!isset($post[$name]) && !$done) {
  2277. switch ($type) {
  2278. case 'textarea':
  2279. $post[$name] = (string) $element;
  2280. break;
  2281. case 'select':
  2282. $single = empty($element['multiple']);
  2283. $first = TRUE;
  2284. $index = 0;
  2285. $key = preg_replace('/\[\]$/', '', $name);
  2286. $options = $this->getAllOptions($element);
  2287. foreach ($options as $option) {
  2288. // For single select, we load the first option, if there is a
  2289. // selected option that will overwrite it later.
  2290. if ($option['selected'] || ($first && $single)) {
  2291. $first = FALSE;
  2292. if ($single) {
  2293. $post[$name] = (string) $option['value'];
  2294. }
  2295. else {
  2296. $post[$key . '[' . $index++ . ']'] = (string) $option['value'];
  2297. }
  2298. }
  2299. }
  2300. break;
  2301. case 'file':
  2302. break;
  2303. case 'submit':
  2304. case 'image':
  2305. if (isset($submit) && $submit == $value) {
  2306. $post[$name] = $value;
  2307. $submit_matches = TRUE;
  2308. }
  2309. break;
  2310. case 'radio':
  2311. case 'checkbox':
  2312. if (!isset($element['checked'])) {
  2313. break;
  2314. }
  2315. // Deliberate no break.
  2316. default:
  2317. $post[$name] = $value;
  2318. }
  2319. }
  2320. }
  2321. return $submit_matches;
  2322. }
  2323. /**
  2324. * Builds an XPath query.
  2325. *
  2326. * Builds an XPath query by replacing placeholders in the query by the value
  2327. * of the arguments.
  2328. *
  2329. * XPath 1.0 (the version supported by libxml2, the underlying XML library
  2330. * used by PHP) doesn't support any form of quotation. This function
  2331. * simplifies the building of XPath expression.
  2332. *
  2333. * @param $xpath
  2334. * An XPath query, possibly with placeholders in the form ':name'.
  2335. * @param $args
  2336. * An array of arguments with keys in the form ':name' matching the
  2337. * placeholders in the query. The values may be either strings or numeric
  2338. * values.
  2339. * @return
  2340. * An XPath query with arguments replaced.
  2341. */
  2342. protected function buildXPathQuery($xpath, array $args = array()) {
  2343. // Replace placeholders.
  2344. foreach ($args as $placeholder => $value) {
  2345. // XPath 1.0 doesn't support a way to escape single or double quotes in a
  2346. // string literal. We split double quotes out of the string, and encode
  2347. // them separately.
  2348. if (is_string($value)) {
  2349. // Explode the text at the quote characters.
  2350. $parts = explode('"', $value);
  2351. // Quote the parts.
  2352. foreach ($parts as &$part) {
  2353. $part = '"' . $part . '"';
  2354. }
  2355. // Return the string.
  2356. $value = count($parts) > 1 ? 'concat(' . implode(', \'"\', ', $parts) . ')' : $parts[0];
  2357. }
  2358. $xpath = preg_replace('/' . preg_quote($placeholder) . '\b/', $value, $xpath);
  2359. }
  2360. return $xpath;
  2361. }
  2362. /**
  2363. * Perform an xpath search on the contents of the internal browser. The search
  2364. * is relative to the root element (HTML tag normally) of the page.
  2365. *
  2366. * @param $xpath
  2367. * The xpath string to use in the search.
  2368. * @param array $arguments
  2369. * An array of arguments with keys in the form ':name' matching the
  2370. * placeholders in the query. The values may be either strings or numeric
  2371. * values.
  2372. *
  2373. * @return
  2374. * The return value of the xpath search. For details on the xpath string
  2375. * format and return values see the SimpleXML documentation,
  2376. * http://us.php.net/manual/function.simplexml-element-xpath.php.
  2377. */
  2378. protected function xpath($xpath, array $arguments = array()) {
  2379. if ($this->parse()) {
  2380. $xpath = $this->buildXPathQuery($xpath, $arguments);
  2381. $result = $this->elements->xpath($xpath);
  2382. // Some combinations of PHP / libxml versions return an empty array
  2383. // instead of the documented FALSE. Forcefully convert any falsish values
  2384. // to an empty array to allow foreach(...) constructions.
  2385. return $result ? $result : array();
  2386. }
  2387. else {
  2388. return FALSE;
  2389. }
  2390. }
  2391. /**
  2392. * Get all option elements, including nested options, in a select.
  2393. *
  2394. * @param $element
  2395. * The element for which to get the options.
  2396. * @return
  2397. * Option elements in select.
  2398. */
  2399. protected function getAllOptions(SimpleXMLElement $element) {
  2400. $options = array();
  2401. // Add all options items.
  2402. foreach ($element->option as $option) {
  2403. $options[] = $option;
  2404. }
  2405. // Search option group children.
  2406. if (isset($element->optgroup)) {
  2407. foreach ($element->optgroup as $group) {
  2408. $options = array_merge($options, $this->getAllOptions($group));
  2409. }
  2410. }
  2411. return $options;
  2412. }
  2413. /**
  2414. * Pass if a link with the specified label is found, and optional with the
  2415. * specified index.
  2416. *
  2417. * @param $label
  2418. * Text between the anchor tags.
  2419. * @param $index
  2420. * Link position counting from zero.
  2421. * @param $message
  2422. * Message to display.
  2423. * @param $group
  2424. * The group this message belongs to, defaults to 'Other'.
  2425. * @return
  2426. * TRUE if the assertion succeeded, FALSE otherwise.
  2427. */
  2428. protected function assertLink($label, $index = 0, $message = '', $group = 'Other') {
  2429. $links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
  2430. $message = ($message ? $message : t('Link with label %label found.', array('%label' => $label)));
  2431. return $this->assert(isset($links[$index]), $message, $group);
  2432. }
  2433. /**
  2434. * Pass if a link with the specified label is not found.
  2435. *
  2436. * @param $label
  2437. * Text between the anchor tags.
  2438. * @param $message
  2439. * Message to display.
  2440. * @param $group
  2441. * The group this message belongs to, defaults to 'Other'.
  2442. * @return
  2443. * TRUE if the assertion succeeded, FALSE otherwise.
  2444. */
  2445. protected function assertNoLink($label, $message = '', $group = 'Other') {
  2446. $links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
  2447. $message = ($message ? $message : t('Link with label %label not found.', array('%label' => $label)));
  2448. return $this->assert(empty($links), $message, $group);
  2449. }
  2450. /**
  2451. * Pass if a link containing a given href (part) is found.
  2452. *
  2453. * @param $href
  2454. * The full or partial value of the 'href' attribute of the anchor tag.
  2455. * @param $index
  2456. * Link position counting from zero.
  2457. * @param $message
  2458. * Message to display.
  2459. * @param $group
  2460. * The group this message belongs to, defaults to 'Other'.
  2461. *
  2462. * @return
  2463. * TRUE if the assertion succeeded, FALSE otherwise.
  2464. */
  2465. protected function assertLinkByHref($href, $index = 0, $message = '', $group = 'Other') {
  2466. $links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
  2467. $message = ($message ? $message : t('Link containing href %href found.', array('%href' => $href)));
  2468. return $this->assert(isset($links[$index]), $message, $group);
  2469. }
  2470. /**
  2471. * Pass if a link containing a given href (part) is not found.
  2472. *
  2473. * @param $href
  2474. * The full or partial value of the 'href' attribute of the anchor tag.
  2475. * @param $message
  2476. * Message to display.
  2477. * @param $group
  2478. * The group this message belongs to, defaults to 'Other'.
  2479. *
  2480. * @return
  2481. * TRUE if the assertion succeeded, FALSE otherwise.
  2482. */
  2483. protected function assertNoLinkByHref($href, $message = '', $group = 'Other') {
  2484. $links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
  2485. $message = ($message ? $message : t('No link containing href %href found.', array('%href' => $href)));
  2486. return $this->assert(empty($links), $message, $group);
  2487. }
  2488. /**
  2489. * Follows a link by name.
  2490. *
  2491. * Will click the first link found with this link text by default, or a later
  2492. * one if an index is given. Match is case sensitive with normalized space.
  2493. * The label is translated label.
  2494. *
  2495. * If the link is discovered and clicked, the test passes. Fail otherwise.
  2496. *
  2497. * @param $label
  2498. * Text between the anchor tags.
  2499. * @param $index
  2500. * Link position counting from zero.
  2501. * @return
  2502. * Page contents on success, or FALSE on failure.
  2503. */
  2504. protected function clickLink($label, $index = 0) {
  2505. $url_before = $this->getUrl();
  2506. $urls = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
  2507. if (isset($urls[$index])) {
  2508. $url_target = $this->getAbsoluteUrl($urls[$index]['href']);
  2509. $this->pass(t('Clicked link %label (@url_target) from @url_before', array('%label' => $label, '@url_target' => $url_target, '@url_before' => $url_before)), 'Browser');
  2510. return $this->drupalGet($url_target);
  2511. }
  2512. $this->fail(t('Link %label does not exist on @url_before', array('%label' => $label, '@url_before' => $url_before)), 'Browser');
  2513. return FALSE;
  2514. }
  2515. /**
  2516. * Takes a path and returns an absolute path.
  2517. *
  2518. * @param $path
  2519. * A path from the internal browser content.
  2520. * @return
  2521. * The $path with $base_url prepended, if necessary.
  2522. */
  2523. protected function getAbsoluteUrl($path) {
  2524. global $base_url, $base_path;
  2525. $parts = parse_url($path);
  2526. if (empty($parts['host'])) {
  2527. // Ensure that we have a string (and no xpath object).
  2528. $path = (string) $path;
  2529. // Strip $base_path, if existent.
  2530. $length = strlen($base_path);
  2531. if (substr($path, 0, $length) === $base_path) {
  2532. $path = substr($path, $length);
  2533. }
  2534. // Ensure that we have an absolute path.
  2535. if (empty($path) || $path[0] !== '/') {
  2536. $path = '/' . $path;
  2537. }
  2538. // Finally, prepend the $base_url.
  2539. $path = $base_url . $path;
  2540. }
  2541. return $path;
  2542. }
  2543. /**
  2544. * Get the current URL from the cURL handler.
  2545. *
  2546. * @return
  2547. * The current URL.
  2548. */
  2549. protected function getUrl() {
  2550. return $this->url;
  2551. }
  2552. /**
  2553. * Gets the HTTP response headers of the requested page. Normally we are only
  2554. * interested in the headers returned by the last request. However, if a page
  2555. * is redirected or HTTP authentication is in use, multiple requests will be
  2556. * required to retrieve the page. Headers from all requests may be requested
  2557. * by passing TRUE to this function.
  2558. *
  2559. * @param $all_requests
  2560. * Boolean value specifying whether to return headers from all requests
  2561. * instead of just the last request. Defaults to FALSE.
  2562. * @return
  2563. * A name/value array if headers from only the last request are requested.
  2564. * If headers from all requests are requested, an array of name/value
  2565. * arrays, one for each request.
  2566. *
  2567. * The pseudonym ":status" is used for the HTTP status line.
  2568. *
  2569. * Values for duplicate headers are stored as a single comma-separated list.
  2570. */
  2571. protected function drupalGetHeaders($all_requests = FALSE) {
  2572. $request = 0;
  2573. $headers = array($request => array());
  2574. foreach ($this->headers as $header) {
  2575. $header = trim($header);
  2576. if ($header === '') {
  2577. $request++;
  2578. }
  2579. else {
  2580. if (strpos($header, 'HTTP/') === 0) {
  2581. $name = ':status';
  2582. $value = $header;
  2583. }
  2584. else {
  2585. list($name, $value) = explode(':', $header, 2);
  2586. $name = strtolower($name);
  2587. }
  2588. if (isset($headers[$request][$name])) {
  2589. $headers[$request][$name] .= ',' . trim($value);
  2590. }
  2591. else {
  2592. $headers[$request][$name] = trim($value);
  2593. }
  2594. }
  2595. }
  2596. if (!$all_requests) {
  2597. $headers = array_pop($headers);
  2598. }
  2599. return $headers;
  2600. }
  2601. /**
  2602. * Gets the value of an HTTP response header. If multiple requests were
  2603. * required to retrieve the page, only the headers from the last request will
  2604. * be checked by default. However, if TRUE is passed as the second argument,
  2605. * all requests will be processed from last to first until the header is
  2606. * found.
  2607. *
  2608. * @param $name
  2609. * The name of the header to retrieve. Names are case-insensitive (see RFC
  2610. * 2616 section 4.2).
  2611. * @param $all_requests
  2612. * Boolean value specifying whether to check all requests if the header is
  2613. * not found in the last request. Defaults to FALSE.
  2614. * @return
  2615. * The HTTP header value or FALSE if not found.
  2616. */
  2617. protected function drupalGetHeader($name, $all_requests = FALSE) {
  2618. $name = strtolower($name);
  2619. $header = FALSE;
  2620. if ($all_requests) {
  2621. foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
  2622. if (isset($headers[$name])) {
  2623. $header = $headers[$name];
  2624. break;
  2625. }
  2626. }
  2627. }
  2628. else {
  2629. $headers = $this->drupalGetHeaders();
  2630. if (isset($headers[$name])) {
  2631. $header = $headers[$name];
  2632. }
  2633. }
  2634. return $header;
  2635. }
  2636. /**
  2637. * Gets the current raw HTML of requested page.
  2638. */
  2639. protected function drupalGetContent() {
  2640. return $this->content;
  2641. }
  2642. /**
  2643. * Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
  2644. */
  2645. protected function drupalGetSettings() {
  2646. return $this->drupalSettings;
  2647. }
  2648. /**
  2649. * Gets an array containing all e-mails sent during this test case.
  2650. *
  2651. * @param $filter
  2652. * An array containing key/value pairs used to filter the e-mails that are returned.
  2653. * @return
  2654. * An array containing e-mail messages captured during the current test.
  2655. */
  2656. protected function drupalGetMails($filter = array()) {
  2657. $captured_emails = variable_get('drupal_test_email_collector', array());
  2658. $filtered_emails = array();
  2659. foreach ($captured_emails as $message) {
  2660. foreach ($filter as $key => $value) {
  2661. if (!isset($message[$key]) || $message[$key] != $value) {
  2662. continue 2;
  2663. }
  2664. }
  2665. $filtered_emails[] = $message;
  2666. }
  2667. return $filtered_emails;
  2668. }
  2669. /**
  2670. * Sets the raw HTML content. This can be useful when a page has been fetched
  2671. * outside of the internal browser and assertions need to be made on the
  2672. * returned page.
  2673. *
  2674. * A good example would be when testing drupal_http_request(). After fetching
  2675. * the page the content can be set and page elements can be checked to ensure
  2676. * that the function worked properly.
  2677. */
  2678. protected function drupalSetContent($content, $url = 'internal:') {
  2679. $this->content = $content;
  2680. $this->url = $url;
  2681. $this->plainTextContent = FALSE;
  2682. $this->elements = FALSE;
  2683. $this->drupalSettings = array();
  2684. if (preg_match('/jQuery\.extend\(Drupal\.settings, (.*?)\);/', $content, $matches)) {
  2685. $this->drupalSettings = drupal_json_decode($matches[1]);
  2686. }
  2687. }
  2688. /**
  2689. * Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
  2690. */
  2691. protected function drupalSetSettings($settings) {
  2692. $this->drupalSettings = $settings;
  2693. }
  2694. /**
  2695. * Pass if the internal browser's URL matches the given path.
  2696. *
  2697. * @param $path
  2698. * The expected system path.
  2699. * @param $options
  2700. * (optional) Any additional options to pass for $path to url().
  2701. * @param $message
  2702. * Message to display.
  2703. * @param $group
  2704. * The group this message belongs to, defaults to 'Other'.
  2705. *
  2706. * @return
  2707. * TRUE on pass, FALSE on fail.
  2708. */
  2709. protected function assertUrl($path, array $options = array(), $message = '', $group = 'Other') {
  2710. if (!$message) {
  2711. $message = t('Current URL is @url.', array(
  2712. '@url' => var_export(url($path, $options), TRUE),
  2713. ));
  2714. }
  2715. $options['absolute'] = TRUE;
  2716. return $this->assertEqual($this->getUrl(), url($path, $options), $message, $group);
  2717. }
  2718. /**
  2719. * Pass if the raw text IS found on the loaded page, fail otherwise. Raw text
  2720. * refers to the raw HTML that the page generated.
  2721. *
  2722. * @param $raw
  2723. * Raw (HTML) string to look for.
  2724. * @param $message
  2725. * Message to display.
  2726. * @param $group
  2727. * The group this message belongs to, defaults to 'Other'.
  2728. * @return
  2729. * TRUE on pass, FALSE on fail.
  2730. */
  2731. protected function assertRaw($raw, $message = '', $group = 'Other') {
  2732. if (!$message) {
  2733. $message = t('Raw "@raw" found', array('@raw' => $raw));
  2734. }
  2735. return $this->assert(strpos($this->drupalGetContent(), $raw) !== FALSE, $message, $group);
  2736. }
  2737. /**
  2738. * Pass if the raw text is NOT found on the loaded page, fail otherwise. Raw text
  2739. * refers to the raw HTML that the page generated.
  2740. *
  2741. * @param $raw
  2742. * Raw (HTML) string to look for.
  2743. * @param $message
  2744. * Message to display.
  2745. * @param $group
  2746. * The group this message belongs to, defaults to 'Other'.
  2747. * @return
  2748. * TRUE on pass, FALSE on fail.
  2749. */
  2750. protected function assertNoRaw($raw, $message = '', $group = 'Other') {
  2751. if (!$message) {
  2752. $message = t('Raw "@raw" not found', array('@raw' => $raw));
  2753. }
  2754. return $this->assert(strpos($this->drupalGetContent(), $raw) === FALSE, $message, $group);
  2755. }
  2756. /**
  2757. * Pass if the text IS found on the text version of the page. The text version
  2758. * is the equivalent of what a user would see when viewing through a web browser.
  2759. * In other words the HTML has been filtered out of the contents.
  2760. *
  2761. * @param $text
  2762. * Plain text to look for.
  2763. * @param $message
  2764. * Message to display.
  2765. * @param $group
  2766. * The group this message belongs to, defaults to 'Other'.
  2767. * @return
  2768. * TRUE on pass, FALSE on fail.
  2769. */
  2770. protected function assertText($text, $message = '', $group = 'Other') {
  2771. return $this->assertTextHelper($text, $message, $group, FALSE);
  2772. }
  2773. /**
  2774. * Pass if the text is NOT found on the text version of the page. The text version
  2775. * is the equivalent of what a user would see when viewing through a web browser.
  2776. * In other words the HTML has been filtered out of the contents.
  2777. *
  2778. * @param $text
  2779. * Plain text to look for.
  2780. * @param $message
  2781. * Message to display.
  2782. * @param $group
  2783. * The group this message belongs to, defaults to 'Other'.
  2784. * @return
  2785. * TRUE on pass, FALSE on fail.
  2786. */
  2787. protected function assertNoText($text, $message = '', $group = 'Other') {
  2788. return $this->assertTextHelper($text, $message, $group, TRUE);
  2789. }
  2790. /**
  2791. * Helper for assertText and assertNoText.
  2792. *
  2793. * It is not recommended to call this function directly.
  2794. *
  2795. * @param $text
  2796. * Plain text to look for.
  2797. * @param $message
  2798. * Message to display.
  2799. * @param $group
  2800. * The group this message belongs to.
  2801. * @param $not_exists
  2802. * TRUE if this text should not exist, FALSE if it should.
  2803. * @return
  2804. * TRUE on pass, FALSE on fail.
  2805. */
  2806. protected function assertTextHelper($text, $message = '', $group, $not_exists) {
  2807. if ($this->plainTextContent === FALSE) {
  2808. $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
  2809. }
  2810. if (!$message) {
  2811. $message = !$not_exists ? t('"@text" found', array('@text' => $text)) : t('"@text" not found', array('@text' => $text));
  2812. }
  2813. return $this->assert($not_exists == (strpos($this->plainTextContent, $text) === FALSE), $message, $group);
  2814. }
  2815. /**
  2816. * Pass if the text is found ONLY ONCE on the text version of the page.
  2817. *
  2818. * The text version is the equivalent of what a user would see when viewing
  2819. * through a web browser. In other words the HTML has been filtered out of
  2820. * the contents.
  2821. *
  2822. * @param $text
  2823. * Plain text to look for.
  2824. * @param $message
  2825. * Message to display.
  2826. * @param $group
  2827. * The group this message belongs to, defaults to 'Other'.
  2828. * @return
  2829. * TRUE on pass, FALSE on fail.
  2830. */
  2831. protected function assertUniqueText($text, $message = '', $group = 'Other') {
  2832. return $this->assertUniqueTextHelper($text, $message, $group, TRUE);
  2833. }
  2834. /**
  2835. * Pass if the text is found MORE THAN ONCE on the text version of the page.
  2836. *
  2837. * The text version is the equivalent of what a user would see when viewing
  2838. * through a web browser. In other words the HTML has been filtered out of
  2839. * the contents.
  2840. *
  2841. * @param $text
  2842. * Plain text to look for.
  2843. * @param $message
  2844. * Message to display.
  2845. * @param $group
  2846. * The group this message belongs to, defaults to 'Other'.
  2847. * @return
  2848. * TRUE on pass, FALSE on fail.
  2849. */
  2850. protected function assertNoUniqueText($text, $message = '', $group = 'Other') {
  2851. return $this->assertUniqueTextHelper($text, $message, $group, FALSE);
  2852. }
  2853. /**
  2854. * Helper for assertUniqueText and assertNoUniqueText.
  2855. *
  2856. * It is not recommended to call this function directly.
  2857. *
  2858. * @param $text
  2859. * Plain text to look for.
  2860. * @param $message
  2861. * Message to display.
  2862. * @param $group
  2863. * The group this message belongs to.
  2864. * @param $be_unique
  2865. * TRUE if this text should be found only once, FALSE if it should be found more than once.
  2866. * @return
  2867. * TRUE on pass, FALSE on fail.
  2868. */
  2869. protected function assertUniqueTextHelper($text, $message = '', $group, $be_unique) {
  2870. if ($this->plainTextContent === FALSE) {
  2871. $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
  2872. }
  2873. if (!$message) {
  2874. $message = '"' . $text . '"' . ($be_unique ? ' found only once' : ' found more than once');
  2875. }
  2876. $first_occurance = strpos($this->plainTextContent, $text);
  2877. if ($first_occurance === FALSE) {
  2878. return $this->assert(FALSE, $message, $group);
  2879. }
  2880. $offset = $first_occurance + strlen($text);
  2881. $second_occurance = strpos($this->plainTextContent, $text, $offset);
  2882. return $this->assert($be_unique == ($second_occurance === FALSE), $message, $group);
  2883. }
  2884. /**
  2885. * Will trigger a pass if the Perl regex pattern is found in the raw content.
  2886. *
  2887. * @param $pattern
  2888. * Perl regex to look for including the regex delimiters.
  2889. * @param $message
  2890. * Message to display.
  2891. * @param $group
  2892. * The group this message belongs to.
  2893. * @return
  2894. * TRUE on pass, FALSE on fail.
  2895. */
  2896. protected function assertPattern($pattern, $message = '', $group = 'Other') {
  2897. if (!$message) {
  2898. $message = t('Pattern "@pattern" found', array('@pattern' => $pattern));
  2899. }
  2900. return $this->assert((bool) preg_match($pattern, $this->drupalGetContent()), $message, $group);
  2901. }
  2902. /**
  2903. * Will trigger a pass if the perl regex pattern is not present in raw content.
  2904. *
  2905. * @param $pattern
  2906. * Perl regex to look for including the regex delimiters.
  2907. * @param $message
  2908. * Message to display.
  2909. * @param $group
  2910. * The group this message belongs to.
  2911. * @return
  2912. * TRUE on pass, FALSE on fail.
  2913. */
  2914. protected function assertNoPattern($pattern, $message = '', $group = 'Other') {
  2915. if (!$message) {
  2916. $message = t('Pattern "@pattern" not found', array('@pattern' => $pattern));
  2917. }
  2918. return $this->assert(!preg_match($pattern, $this->drupalGetContent()), $message, $group);
  2919. }
  2920. /**
  2921. * Pass if the page title is the given string.
  2922. *
  2923. * @param $title
  2924. * The string the title should be.
  2925. * @param $message
  2926. * Message to display.
  2927. * @param $group
  2928. * The group this message belongs to.
  2929. * @return
  2930. * TRUE on pass, FALSE on fail.
  2931. */
  2932. protected function assertTitle($title, $message = '', $group = 'Other') {
  2933. $actual = (string) current($this->xpath('//title'));
  2934. if (!$message) {
  2935. $message = t('Page title @actual is equal to @expected.', array(
  2936. '@actual' => var_export($actual, TRUE),
  2937. '@expected' => var_export($title, TRUE),
  2938. ));
  2939. }
  2940. return $this->assertEqual($actual, $title, $message, $group);
  2941. }
  2942. /**
  2943. * Pass if the page title is not the given string.
  2944. *
  2945. * @param $title
  2946. * The string the title should not be.
  2947. * @param $message
  2948. * Message to display.
  2949. * @param $group
  2950. * The group this message belongs to.
  2951. * @return
  2952. * TRUE on pass, FALSE on fail.
  2953. */
  2954. protected function assertNoTitle($title, $message = '', $group = 'Other') {
  2955. $actual = (string) current($this->xpath('//title'));
  2956. if (!$message) {
  2957. $message = t('Page title @actual is not equal to @unexpected.', array(
  2958. '@actual' => var_export($actual, TRUE),
  2959. '@unexpected' => var_export($title, TRUE),
  2960. ));
  2961. }
  2962. return $this->assertNotEqual($actual, $title, $message, $group);
  2963. }
  2964. /**
  2965. * Asserts themed output.
  2966. *
  2967. * @param $callback
  2968. * The name of the theme function to invoke; e.g. 'links' for theme_links().
  2969. * @param $variables
  2970. * (optional) An array of variables to pass to the theme function.
  2971. * @param $expected
  2972. * The expected themed output string.
  2973. * @param $message
  2974. * (optional) A message to display with the assertion. Do not translate
  2975. * messages: use format_string() to embed variables in the message text, not
  2976. * t(). If left blank, a default message will be displayed.
  2977. * @param $group
  2978. * (optional) The group this message is in, which is displayed in a column
  2979. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  2980. * translate this string. Defaults to 'Other'; most tests do not override
  2981. * this default.
  2982. *
  2983. * @return
  2984. * TRUE on pass, FALSE on fail.
  2985. */
  2986. protected function assertThemeOutput($callback, array $variables = array(), $expected, $message = '', $group = 'Other') {
  2987. $output = theme($callback, $variables);
  2988. $this->verbose('Variables:' . '<pre>' . check_plain(var_export($variables, TRUE)) . '</pre>'
  2989. . '<hr />' . 'Result:' . '<pre>' . check_plain(var_export($output, TRUE)) . '</pre>'
  2990. . '<hr />' . 'Expected:' . '<pre>' . check_plain(var_export($expected, TRUE)) . '</pre>'
  2991. . '<hr />' . $output
  2992. );
  2993. if (!$message) {
  2994. $message = '%callback rendered correctly.';
  2995. }
  2996. $message = format_string($message, array('%callback' => 'theme_' . $callback . '()'));
  2997. return $this->assertIdentical($output, $expected, $message, $group);
  2998. }
  2999. /**
  3000. * Asserts that a field exists in the current page by the given XPath.
  3001. *
  3002. * @param $xpath
  3003. * XPath used to find the field.
  3004. * @param $value
  3005. * (optional) Value of the field to assert. You may pass in NULL (default)
  3006. * to skip checking the actual value, while still checking that the field
  3007. * exists.
  3008. * @param $message
  3009. * (optional) Message to display.
  3010. * @param $group
  3011. * (optional) The group this message belongs to.
  3012. *
  3013. * @return
  3014. * TRUE on pass, FALSE on fail.
  3015. */
  3016. protected function assertFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
  3017. $fields = $this->xpath($xpath);
  3018. // If value specified then check array for match.
  3019. $found = TRUE;
  3020. if (isset($value)) {
  3021. $found = FALSE;
  3022. if ($fields) {
  3023. foreach ($fields as $field) {
  3024. if (isset($field['value']) && $field['value'] == $value) {
  3025. // Input element with correct value.
  3026. $found = TRUE;
  3027. }
  3028. elseif (isset($field->option)) {
  3029. // Select element found.
  3030. if ($this->getSelectedItem($field) == $value) {
  3031. $found = TRUE;
  3032. }
  3033. else {
  3034. // No item selected so use first item.
  3035. $items = $this->getAllOptions($field);
  3036. if (!empty($items) && $items[0]['value'] == $value) {
  3037. $found = TRUE;
  3038. }
  3039. }
  3040. }
  3041. elseif ((string) $field == $value) {
  3042. // Text area with correct text.
  3043. $found = TRUE;
  3044. }
  3045. }
  3046. }
  3047. }
  3048. return $this->assertTrue($fields && $found, $message, $group);
  3049. }
  3050. /**
  3051. * Get the selected value from a select field.
  3052. *
  3053. * @param $element
  3054. * SimpleXMLElement select element.
  3055. * @return
  3056. * The selected value or FALSE.
  3057. */
  3058. protected function getSelectedItem(SimpleXMLElement $element) {
  3059. foreach ($element->children() as $item) {
  3060. if (isset($item['selected'])) {
  3061. return $item['value'];
  3062. }
  3063. elseif ($item->getName() == 'optgroup') {
  3064. if ($value = $this->getSelectedItem($item)) {
  3065. return $value;
  3066. }
  3067. }
  3068. }
  3069. return FALSE;
  3070. }
  3071. /**
  3072. * Asserts that a field doesn't exist or its value doesn't match, by XPath.
  3073. *
  3074. * @param $xpath
  3075. * XPath used to find the field.
  3076. * @param $value
  3077. * (optional) Value for the field, to assert that the field's value on the
  3078. * page doesn't match it. You may pass in NULL to skip checking the
  3079. * value, while still checking that the field doesn't exist.
  3080. * @param $message
  3081. * (optional) Message to display.
  3082. * @param $group
  3083. * (optional) The group this message belongs to.
  3084. *
  3085. * @return
  3086. * TRUE on pass, FALSE on fail.
  3087. */
  3088. protected function assertNoFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
  3089. $fields = $this->xpath($xpath);
  3090. // If value specified then check array for match.
  3091. $found = TRUE;
  3092. if (isset($value)) {
  3093. $found = FALSE;
  3094. if ($fields) {
  3095. foreach ($fields as $field) {
  3096. if ($field['value'] == $value) {
  3097. $found = TRUE;
  3098. }
  3099. }
  3100. }
  3101. }
  3102. return $this->assertFalse($fields && $found, $message, $group);
  3103. }
  3104. /**
  3105. * Asserts that a field exists in the current page with the given name and value.
  3106. *
  3107. * @param $name
  3108. * Name of field to assert.
  3109. * @param $value
  3110. * (optional) Value of the field to assert. You may pass in NULL (default)
  3111. * to skip checking the actual value, while still checking that the field
  3112. * exists.
  3113. * @param $message
  3114. * Message to display.
  3115. * @param $group
  3116. * The group this message belongs to.
  3117. * @return
  3118. * TRUE on pass, FALSE on fail.
  3119. */
  3120. protected function assertFieldByName($name, $value = NULL, $message = NULL) {
  3121. if (!isset($message)) {
  3122. if (!isset($value)) {
  3123. $message = t('Found field with name @name', array(
  3124. '@name' => var_export($name, TRUE),
  3125. ));
  3126. }
  3127. else {
  3128. $message = t('Found field with name @name and value @value', array(
  3129. '@name' => var_export($name, TRUE),
  3130. '@value' => var_export($value, TRUE),
  3131. ));
  3132. }
  3133. }
  3134. return $this->assertFieldByXPath($this->constructFieldXpath('name', $name), $value, $message, t('Browser'));
  3135. }
  3136. /**
  3137. * Asserts that a field does not exist with the given name and value.
  3138. *
  3139. * @param $name
  3140. * Name of field to assert.
  3141. * @param $value
  3142. * (optional) Value for the field, to assert that the field's value on the
  3143. * page doesn't match it. You may pass in NULL to skip checking the
  3144. * value, while still checking that the field doesn't exist. However, the
  3145. * default value ('') asserts that the field value is not an empty string.
  3146. * @param $message
  3147. * (optional) Message to display.
  3148. * @param $group
  3149. * The group this message belongs to.
  3150. * @return
  3151. * TRUE on pass, FALSE on fail.
  3152. */
  3153. protected function assertNoFieldByName($name, $value = '', $message = '') {
  3154. return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $name), $value, $message ? $message : t('Did not find field by name @name', array('@name' => $name)), t('Browser'));
  3155. }
  3156. /**
  3157. * Asserts that a field exists in the current page with the given ID and value.
  3158. *
  3159. * @param $id
  3160. * ID of field to assert.
  3161. * @param $value
  3162. * (optional) Value for the field to assert. You may pass in NULL to skip
  3163. * checking the value, while still checking that the field exists.
  3164. * However, the default value ('') asserts that the field value is an empty
  3165. * string.
  3166. * @param $message
  3167. * (optional) Message to display.
  3168. * @param $group
  3169. * The group this message belongs to.
  3170. * @return
  3171. * TRUE on pass, FALSE on fail.
  3172. */
  3173. protected function assertFieldById($id, $value = '', $message = '') {
  3174. return $this->assertFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Found field by id @id', array('@id' => $id)), t('Browser'));
  3175. }
  3176. /**
  3177. * Asserts that a field does not exist with the given ID and value.
  3178. *
  3179. * @param $id
  3180. * ID of field to assert.
  3181. * @param $value
  3182. * (optional) Value for the field, to assert that the field's value on the
  3183. * page doesn't match it. You may pass in NULL to skip checking the value,
  3184. * while still checking that the field doesn't exist. However, the default
  3185. * value ('') asserts that the field value is not an empty string.
  3186. * @param $message
  3187. * (optional) Message to display.
  3188. * @param $group
  3189. * The group this message belongs to.
  3190. * @return
  3191. * TRUE on pass, FALSE on fail.
  3192. */
  3193. protected function assertNoFieldById($id, $value = '', $message = '') {
  3194. return $this->assertNoFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Did not find field by id @id', array('@id' => $id)), t('Browser'));
  3195. }
  3196. /**
  3197. * Asserts that a checkbox field in the current page is checked.
  3198. *
  3199. * @param $id
  3200. * ID of field to assert.
  3201. * @param $message
  3202. * (optional) Message to display.
  3203. * @return
  3204. * TRUE on pass, FALSE on fail.
  3205. */
  3206. protected function assertFieldChecked($id, $message = '') {
  3207. $elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
  3208. return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is checked.', array('@id' => $id)), t('Browser'));
  3209. }
  3210. /**
  3211. * Asserts that a checkbox field in the current page is not checked.
  3212. *
  3213. * @param $id
  3214. * ID of field to assert.
  3215. * @param $message
  3216. * (optional) Message to display.
  3217. * @return
  3218. * TRUE on pass, FALSE on fail.
  3219. */
  3220. protected function assertNoFieldChecked($id, $message = '') {
  3221. $elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
  3222. return $this->assertTrue(isset($elements[0]) && empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is not checked.', array('@id' => $id)), t('Browser'));
  3223. }
  3224. /**
  3225. * Asserts that a select option in the current page is checked.
  3226. *
  3227. * @param $id
  3228. * ID of select field to assert.
  3229. * @param $option
  3230. * Option to assert.
  3231. * @param $message
  3232. * (optional) Message to display.
  3233. * @return
  3234. * TRUE on pass, FALSE on fail.
  3235. *
  3236. * @todo $id is unusable. Replace with $name.
  3237. */
  3238. protected function assertOptionSelected($id, $option, $message = '') {
  3239. $elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
  3240. return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['selected']), $message ? $message : t('Option @option for field @id is selected.', array('@option' => $option, '@id' => $id)), t('Browser'));
  3241. }
  3242. /**
  3243. * Asserts that a select option in the current page is not checked.
  3244. *
  3245. * @param $id
  3246. * ID of select field to assert.
  3247. * @param $option
  3248. * Option to assert.
  3249. * @param $message
  3250. * (optional) Message to display.
  3251. * @return
  3252. * TRUE on pass, FALSE on fail.
  3253. */
  3254. protected function assertNoOptionSelected($id, $option, $message = '') {
  3255. $elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
  3256. return $this->assertTrue(isset($elements[0]) && empty($elements[0]['selected']), $message ? $message : t('Option @option for field @id is not selected.', array('@option' => $option, '@id' => $id)), t('Browser'));
  3257. }
  3258. /**
  3259. * Asserts that a field exists with the given name or ID.
  3260. *
  3261. * @param $field
  3262. * Name or ID of field to assert.
  3263. * @param $message
  3264. * (optional) Message to display.
  3265. * @param $group
  3266. * The group this message belongs to.
  3267. * @return
  3268. * TRUE on pass, FALSE on fail.
  3269. */
  3270. protected function assertField($field, $message = '', $group = 'Other') {
  3271. return $this->assertFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
  3272. }
  3273. /**
  3274. * Asserts that a field does not exist with the given name or ID.
  3275. *
  3276. * @param $field
  3277. * Name or ID of field to assert.
  3278. * @param $message
  3279. * (optional) Message to display.
  3280. * @param $group
  3281. * The group this message belongs to.
  3282. * @return
  3283. * TRUE on pass, FALSE on fail.
  3284. */
  3285. protected function assertNoField($field, $message = '', $group = 'Other') {
  3286. return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
  3287. }
  3288. /**
  3289. * Asserts that each HTML ID is used for just a single element.
  3290. *
  3291. * @param $message
  3292. * Message to display.
  3293. * @param $group
  3294. * The group this message belongs to.
  3295. * @param $ids_to_skip
  3296. * An optional array of ids to skip when checking for duplicates. It is
  3297. * always a bug to have duplicate HTML IDs, so this parameter is to enable
  3298. * incremental fixing of core code. Whenever a test passes this parameter,
  3299. * it should add a "todo" comment above the call to this function explaining
  3300. * the legacy bug that the test wishes to ignore and including a link to an
  3301. * issue that is working to fix that legacy bug.
  3302. * @return
  3303. * TRUE on pass, FALSE on fail.
  3304. */
  3305. protected function assertNoDuplicateIds($message = '', $group = 'Other', $ids_to_skip = array()) {
  3306. $status = TRUE;
  3307. foreach ($this->xpath('//*[@id]') as $element) {
  3308. $id = (string) $element['id'];
  3309. if (isset($seen_ids[$id]) && !in_array($id, $ids_to_skip)) {
  3310. $this->fail(t('The HTML ID %id is unique.', array('%id' => $id)), $group);
  3311. $status = FALSE;
  3312. }
  3313. $seen_ids[$id] = TRUE;
  3314. }
  3315. return $this->assert($status, $message, $group);
  3316. }
  3317. /**
  3318. * Helper function: construct an XPath for the given set of attributes and value.
  3319. *
  3320. * @param $attribute
  3321. * Field attributes.
  3322. * @param $value
  3323. * Value of field.
  3324. * @return
  3325. * XPath for specified values.
  3326. */
  3327. protected function constructFieldXpath($attribute, $value) {
  3328. $xpath = '//textarea[@' . $attribute . '=:value]|//input[@' . $attribute . '=:value]|//select[@' . $attribute . '=:value]';
  3329. return $this->buildXPathQuery($xpath, array(':value' => $value));
  3330. }
  3331. /**
  3332. * Asserts the page responds with the specified response code.
  3333. *
  3334. * @param $code
  3335. * Response code. For example 200 is a successful page request. For a list
  3336. * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
  3337. * @param $message
  3338. * Message to display.
  3339. * @return
  3340. * Assertion result.
  3341. */
  3342. protected function assertResponse($code, $message = '') {
  3343. $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  3344. $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
  3345. return $this->assertTrue($match, $message ? $message : t('HTTP response expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
  3346. }
  3347. /**
  3348. * Asserts the page did not return the specified response code.
  3349. *
  3350. * @param $code
  3351. * Response code. For example 200 is a successful page request. For a list
  3352. * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
  3353. * @param $message
  3354. * Message to display.
  3355. *
  3356. * @return
  3357. * Assertion result.
  3358. */
  3359. protected function assertNoResponse($code, $message = '') {
  3360. $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  3361. $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
  3362. return $this->assertFalse($match, $message ? $message : t('HTTP response not expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
  3363. }
  3364. /**
  3365. * Asserts that the most recently sent e-mail message has the given value.
  3366. *
  3367. * The field in $name must have the content described in $value.
  3368. *
  3369. * @param $name
  3370. * Name of field or message property to assert. Examples: subject, body, id, ...
  3371. * @param $value
  3372. * Value of the field to assert.
  3373. * @param $message
  3374. * Message to display.
  3375. *
  3376. * @return
  3377. * TRUE on pass, FALSE on fail.
  3378. */
  3379. protected function assertMail($name, $value = '', $message = '') {
  3380. $captured_emails = variable_get('drupal_test_email_collector', array());
  3381. $email = end($captured_emails);
  3382. return $this->assertTrue($email && isset($email[$name]) && $email[$name] == $value, $message, t('E-mail'));
  3383. }
  3384. /**
  3385. * Asserts that the most recently sent e-mail message has the string in it.
  3386. *
  3387. * @param $field_name
  3388. * Name of field or message property to assert: subject, body, id, ...
  3389. * @param $string
  3390. * String to search for.
  3391. * @param $email_depth
  3392. * Number of emails to search for string, starting with most recent.
  3393. *
  3394. * @return
  3395. * TRUE on pass, FALSE on fail.
  3396. */
  3397. protected function assertMailString($field_name, $string, $email_depth) {
  3398. $mails = $this->drupalGetMails();
  3399. $string_found = FALSE;
  3400. for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $email_depth && $i >= 0; $i--) {
  3401. $mail = $mails[$i];
  3402. // Normalize whitespace, as we don't know what the mail system might have
  3403. // done. Any run of whitespace becomes a single space.
  3404. $normalized_mail = preg_replace('/\s+/', ' ', $mail[$field_name]);
  3405. $normalized_string = preg_replace('/\s+/', ' ', $string);
  3406. $string_found = (FALSE !== strpos($normalized_mail, $normalized_string));
  3407. if ($string_found) {
  3408. break;
  3409. }
  3410. }
  3411. return $this->assertTrue($string_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $string)));
  3412. }
  3413. /**
  3414. * Asserts that the most recently sent e-mail message has the pattern in it.
  3415. *
  3416. * @param $field_name
  3417. * Name of field or message property to assert: subject, body, id, ...
  3418. * @param $regex
  3419. * Pattern to search for.
  3420. *
  3421. * @return
  3422. * TRUE on pass, FALSE on fail.
  3423. */
  3424. protected function assertMailPattern($field_name, $regex, $message) {
  3425. $mails = $this->drupalGetMails();
  3426. $mail = end($mails);
  3427. $regex_found = preg_match("/$regex/", $mail[$field_name]);
  3428. return $this->assertTrue($regex_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $regex)));
  3429. }
  3430. /**
  3431. * Outputs to verbose the most recent $count emails sent.
  3432. *
  3433. * @param $count
  3434. * Optional number of emails to output.
  3435. */
  3436. protected function verboseEmail($count = 1) {
  3437. $mails = $this->drupalGetMails();
  3438. for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $count && $i >= 0; $i--) {
  3439. $mail = $mails[$i];
  3440. $this->verbose(t('Email:') . '<pre>' . print_r($mail, TRUE) . '</pre>');
  3441. }
  3442. }
  3443. }
  3444. /**
  3445. * Logs verbose message in a text file.
  3446. *
  3447. * If verbose mode is enabled then page requests will be dumped to a file and
  3448. * presented on the test result screen. The messages will be placed in a file
  3449. * located in the simpletest directory in the original file system.
  3450. *
  3451. * @param $message
  3452. * The verbose message to be stored.
  3453. * @param $original_file_directory
  3454. * The original file directory, before it was changed for testing purposes.
  3455. * @param $test_class
  3456. * The active test case class.
  3457. *
  3458. * @return
  3459. * The ID of the message to be placed in related assertion messages.
  3460. *
  3461. * @see DrupalTestCase->originalFileDirectory
  3462. * @see DrupalWebTestCase->verbose()
  3463. */
  3464. function simpletest_verbose($message, $original_file_directory = NULL, $test_class = NULL) {
  3465. static $file_directory = NULL, $class = NULL, $id = 1, $verbose = NULL;
  3466. // Will pass first time during setup phase, and when verbose is TRUE.
  3467. if (!isset($original_file_directory) && !$verbose) {
  3468. return FALSE;
  3469. }
  3470. if ($message && $file_directory) {
  3471. $message = '<hr />ID #' . $id . ' (<a href="' . $class . '-' . ($id - 1) . '.html">Previous</a> | <a href="' . $class . '-' . ($id + 1) . '.html">Next</a>)<hr />' . $message;
  3472. file_put_contents($file_directory . "/simpletest/verbose/$class-$id.html", $message, FILE_APPEND);
  3473. return $id++;
  3474. }
  3475. if ($original_file_directory) {
  3476. $file_directory = $original_file_directory;
  3477. $class = $test_class;
  3478. $verbose = variable_get('simpletest_verbose', TRUE);
  3479. $directory = $file_directory . '/simpletest/verbose';
  3480. $writable = file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
  3481. if ($writable && !file_exists($directory . '/.htaccess')) {
  3482. file_put_contents($directory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
  3483. }
  3484. return $writable;
  3485. }
  3486. return FALSE;
  3487. }