drupal_web_test_case.php 129 KB

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