drupal_web_test_case.php 125 KB

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