drupal_web_test_case.php 133 KB

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