drupal_web_test_case.php 132 KB

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