drupal_web_test_case.php 132 KB

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