drupal_web_test_case.php 133 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806
  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($this->databasePrefix . '%');
  1503. $connection_info = Database::getConnectionInfo('default');
  1504. $tables = db_find_tables($connection_info['default']['prefix']['default'] . '%');
  1505. if (empty($tables)) {
  1506. $this->fail('Failed to find test tables to drop.');
  1507. }
  1508. $prefix_length = strlen($connection_info['default']['prefix']['default']);
  1509. foreach ($tables as $table) {
  1510. if (db_drop_table(substr($table, $prefix_length))) {
  1511. unset($tables[$table]);
  1512. }
  1513. }
  1514. if (!empty($tables)) {
  1515. $this->fail('Failed to drop all prefixed tables.');
  1516. }
  1517. // Get back to the original connection.
  1518. Database::removeConnection('default');
  1519. Database::renameConnection('simpletest_original_default', 'default');
  1520. // Restore original shutdown callbacks array to prevent original
  1521. // environment of calling handlers from test run.
  1522. $callbacks = &drupal_register_shutdown_function();
  1523. $callbacks = $this->originalShutdownCallbacks;
  1524. // Return the user to the original one.
  1525. $user = $this->originalUser;
  1526. drupal_save_session(TRUE);
  1527. // Ensure that internal logged in variable and cURL options are reset.
  1528. $this->loggedInUser = FALSE;
  1529. $this->additionalCurlOptions = array();
  1530. // Reload module list and implementations to ensure that test module hooks
  1531. // aren't called after tests.
  1532. module_list(TRUE);
  1533. module_implements('', FALSE, TRUE);
  1534. // Reset the Field API.
  1535. field_cache_clear();
  1536. // Rebuild caches.
  1537. $this->refreshVariables();
  1538. // Reset public files directory.
  1539. $GLOBALS['conf']['file_public_path'] = $this->originalFileDirectory;
  1540. // Reset language.
  1541. $language = $this->originalLanguage;
  1542. $language_url = $this->originalLanguageUrl;
  1543. if ($this->originalLanguageDefault) {
  1544. $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault;
  1545. }
  1546. // Close the CURL handler and reset the cookies array so test classes
  1547. // containing multiple tests are not polluted.
  1548. $this->curlClose();
  1549. $this->cookies = array();
  1550. }
  1551. /**
  1552. * Initializes the cURL connection.
  1553. *
  1554. * If the simpletest_httpauth_credentials variable is set, this function will
  1555. * add HTTP authentication headers. This is necessary for testing sites that
  1556. * are protected by login credentials from public access.
  1557. * See the description of $curl_options for other options.
  1558. */
  1559. protected function curlInitialize() {
  1560. global $base_url;
  1561. if (!isset($this->curlHandle)) {
  1562. $this->curlHandle = curl_init();
  1563. // Some versions/configurations of cURL break on a NULL cookie jar, so
  1564. // supply a real file.
  1565. if (empty($this->cookieFile)) {
  1566. $this->cookieFile = $this->public_files_directory . '/cookie.jar';
  1567. }
  1568. $curl_options = array(
  1569. CURLOPT_COOKIEJAR => $this->cookieFile,
  1570. CURLOPT_URL => $base_url,
  1571. CURLOPT_FOLLOWLOCATION => FALSE,
  1572. CURLOPT_RETURNTRANSFER => TRUE,
  1573. CURLOPT_SSL_VERIFYPEER => FALSE, // Required to make the tests run on HTTPS.
  1574. CURLOPT_SSL_VERIFYHOST => FALSE, // Required to make the tests run on HTTPS.
  1575. CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'),
  1576. CURLOPT_USERAGENT => $this->databasePrefix,
  1577. );
  1578. if (isset($this->httpauth_credentials)) {
  1579. $curl_options[CURLOPT_HTTPAUTH] = $this->httpauth_method;
  1580. $curl_options[CURLOPT_USERPWD] = $this->httpauth_credentials;
  1581. }
  1582. // curl_setopt_array() returns FALSE if any of the specified options
  1583. // cannot be set, and stops processing any further options.
  1584. $result = curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
  1585. if (!$result) {
  1586. throw new Exception('One or more cURL options could not be set.');
  1587. }
  1588. // By default, the child session name should be the same as the parent.
  1589. $this->session_name = session_name();
  1590. }
  1591. // We set the user agent header on each request so as to use the current
  1592. // time and a new uniqid.
  1593. if (preg_match('/simpletest\d+/', $this->databasePrefix, $matches)) {
  1594. curl_setopt($this->curlHandle, CURLOPT_USERAGENT, drupal_generate_test_ua($matches[0]));
  1595. }
  1596. }
  1597. /**
  1598. * Initializes and executes a cURL request.
  1599. *
  1600. * @param $curl_options
  1601. * An associative array of cURL options to set, where the keys are constants
  1602. * defined by the cURL library. For a list of valid options, see
  1603. * http://www.php.net/manual/function.curl-setopt.php
  1604. * @param $redirect
  1605. * FALSE if this is an initial request, TRUE if this request is the result
  1606. * of a redirect.
  1607. *
  1608. * @return
  1609. * The content returned from the call to curl_exec().
  1610. *
  1611. * @see curlInitialize()
  1612. */
  1613. protected function curlExec($curl_options, $redirect = FALSE) {
  1614. $this->curlInitialize();
  1615. if (!empty($curl_options[CURLOPT_URL])) {
  1616. // Forward XDebug activation if present.
  1617. if (isset($_COOKIE['XDEBUG_SESSION'])) {
  1618. $options = drupal_parse_url($curl_options[CURLOPT_URL]);
  1619. $options += array('query' => array());
  1620. $options['query'] += array('XDEBUG_SESSION_START' => $_COOKIE['XDEBUG_SESSION']);
  1621. $curl_options[CURLOPT_URL] = url($options['path'], $options);
  1622. }
  1623. // cURL incorrectly handles URLs with a fragment by including the
  1624. // fragment in the request to the server, causing some web servers
  1625. // to reject the request citing "400 - Bad Request". To prevent
  1626. // this, we strip the fragment from the request.
  1627. // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
  1628. if (strpos($curl_options[CURLOPT_URL], '#')) {
  1629. $original_url = $curl_options[CURLOPT_URL];
  1630. $curl_options[CURLOPT_URL] = strtok($curl_options[CURLOPT_URL], '#');
  1631. }
  1632. }
  1633. $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
  1634. if (!empty($curl_options[CURLOPT_POST])) {
  1635. // This is a fix for the Curl library to prevent Expect: 100-continue
  1636. // headers in POST requests, that may cause unexpected HTTP response
  1637. // codes from some webservers (like lighttpd that returns a 417 error
  1638. // code). It is done by setting an empty "Expect" header field that is
  1639. // not overwritten by Curl.
  1640. $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
  1641. }
  1642. curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
  1643. if (!$redirect) {
  1644. // Reset headers, the session ID and the redirect counter.
  1645. $this->session_id = NULL;
  1646. $this->headers = array();
  1647. $this->redirect_count = 0;
  1648. }
  1649. $content = curl_exec($this->curlHandle);
  1650. $status = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  1651. // cURL incorrectly handles URLs with fragments, so instead of
  1652. // letting cURL handle redirects we take of them ourselves to
  1653. // to prevent fragments being sent to the web server as part
  1654. // of the request.
  1655. // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
  1656. if (in_array($status, array(300, 301, 302, 303, 305, 307)) && $this->redirect_count < variable_get('simpletest_maximum_redirects', 5)) {
  1657. if ($this->drupalGetHeader('location')) {
  1658. $this->redirect_count++;
  1659. $curl_options = array();
  1660. $curl_options[CURLOPT_URL] = $this->drupalGetHeader('location');
  1661. $curl_options[CURLOPT_HTTPGET] = TRUE;
  1662. return $this->curlExec($curl_options, TRUE);
  1663. }
  1664. }
  1665. $this->drupalSetContent($content, isset($original_url) ? $original_url : curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL));
  1666. $message_vars = array(
  1667. '!method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
  1668. '@url' => isset($original_url) ? $original_url : $url,
  1669. '@status' => $status,
  1670. '!length' => format_size(strlen($this->drupalGetContent()))
  1671. );
  1672. $message = t('!method @url returned @status (!length).', $message_vars);
  1673. $this->assertTrue($this->drupalGetContent() !== FALSE, $message, t('Browser'));
  1674. return $this->drupalGetContent();
  1675. }
  1676. /**
  1677. * Reads headers and registers errors received from the tested site.
  1678. *
  1679. * @see _drupal_log_error().
  1680. *
  1681. * @param $curlHandler
  1682. * The cURL handler.
  1683. * @param $header
  1684. * An header.
  1685. */
  1686. protected function curlHeaderCallback($curlHandler, $header) {
  1687. // Header fields can be extended over multiple lines by preceding each
  1688. // extra line with at least one SP or HT. They should be joined on receive.
  1689. // Details are in RFC2616 section 4.
  1690. if ($header[0] == ' ' || $header[0] == "\t") {
  1691. // Normalize whitespace between chucks.
  1692. $this->headers[] = array_pop($this->headers) . ' ' . trim($header);
  1693. }
  1694. else {
  1695. $this->headers[] = $header;
  1696. }
  1697. // Errors are being sent via X-Drupal-Assertion-* headers,
  1698. // generated by _drupal_log_error() in the exact form required
  1699. // by DrupalWebTestCase::error().
  1700. if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
  1701. // Call DrupalWebTestCase::error() with the parameters from the header.
  1702. call_user_func_array(array(&$this, 'error'), unserialize(urldecode($matches[1])));
  1703. }
  1704. // Save cookies.
  1705. if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
  1706. $name = $matches[1];
  1707. $parts = array_map('trim', explode(';', $matches[2]));
  1708. $value = array_shift($parts);
  1709. $this->cookies[$name] = array('value' => $value, 'secure' => in_array('secure', $parts));
  1710. if ($name == $this->session_name) {
  1711. if ($value != 'deleted') {
  1712. $this->session_id = $value;
  1713. }
  1714. else {
  1715. $this->session_id = NULL;
  1716. }
  1717. }
  1718. }
  1719. // This is required by cURL.
  1720. return strlen($header);
  1721. }
  1722. /**
  1723. * Close the cURL handler and unset the handler.
  1724. */
  1725. protected function curlClose() {
  1726. if (isset($this->curlHandle)) {
  1727. curl_close($this->curlHandle);
  1728. unset($this->curlHandle);
  1729. }
  1730. }
  1731. /**
  1732. * Parse content returned from curlExec using DOM and SimpleXML.
  1733. *
  1734. * @return
  1735. * A SimpleXMLElement or FALSE on failure.
  1736. */
  1737. protected function parse() {
  1738. if (!$this->elements) {
  1739. // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
  1740. // them.
  1741. $htmlDom = new DOMDocument();
  1742. @$htmlDom->loadHTML($this->drupalGetContent());
  1743. if ($htmlDom) {
  1744. $this->pass(t('Valid HTML found on "@path"', array('@path' => $this->getUrl())), t('Browser'));
  1745. // It's much easier to work with simplexml than DOM, luckily enough
  1746. // we can just simply import our DOM tree.
  1747. $this->elements = simplexml_import_dom($htmlDom);
  1748. }
  1749. }
  1750. if (!$this->elements) {
  1751. $this->fail(t('Parsed page successfully.'), t('Browser'));
  1752. }
  1753. return $this->elements;
  1754. }
  1755. /**
  1756. * Retrieves a Drupal path or an absolute path.
  1757. *
  1758. * @param $path
  1759. * Drupal path or URL to load into internal browser
  1760. * @param $options
  1761. * Options to be forwarded to url().
  1762. * @param $headers
  1763. * An array containing additional HTTP request headers, each formatted as
  1764. * "name: value".
  1765. * @return
  1766. * The retrieved HTML string, also available as $this->drupalGetContent()
  1767. */
  1768. protected function drupalGet($path, array $options = array(), array $headers = array()) {
  1769. $options['absolute'] = TRUE;
  1770. // We re-using a CURL connection here. If that connection still has certain
  1771. // options set, it might change the GET into a POST. Make sure we clear out
  1772. // previous options.
  1773. $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers));
  1774. $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
  1775. // Replace original page output with new output from redirected page(s).
  1776. if ($new = $this->checkForMetaRefresh()) {
  1777. $out = $new;
  1778. }
  1779. $this->verbose('GET request to: ' . $path .
  1780. '<hr />Ending URL: ' . $this->getUrl() .
  1781. '<hr />' . $out);
  1782. return $out;
  1783. }
  1784. /**
  1785. * Retrieve a Drupal path or an absolute path and JSON decode the result.
  1786. */
  1787. protected function drupalGetAJAX($path, array $options = array(), array $headers = array()) {
  1788. return drupal_json_decode($this->drupalGet($path, $options, $headers));
  1789. }
  1790. /**
  1791. * Execute a POST request on a Drupal page.
  1792. * It will be done as usual POST request with SimpleBrowser.
  1793. *
  1794. * @param $path
  1795. * Location of the post form. Either a Drupal path or an absolute path or
  1796. * NULL to post to the current page. For multi-stage forms you can set the
  1797. * path to NULL and have it post to the last received page. Example:
  1798. *
  1799. * @code
  1800. * // First step in form.
  1801. * $edit = array(...);
  1802. * $this->drupalPost('some_url', $edit, t('Save'));
  1803. *
  1804. * // Second step in form.
  1805. * $edit = array(...);
  1806. * $this->drupalPost(NULL, $edit, t('Save'));
  1807. * @endcode
  1808. * @param $edit
  1809. * Field data in an associative array. Changes the current input fields
  1810. * (where possible) to the values indicated. A checkbox can be set to
  1811. * TRUE to be checked and FALSE to be unchecked. Note that when a form
  1812. * contains file upload fields, other fields cannot start with the '@'
  1813. * character.
  1814. *
  1815. * Multiple select fields can be set using name[] and setting each of the
  1816. * possible values. Example:
  1817. * @code
  1818. * $edit = array();
  1819. * $edit['name[]'] = array('value1', 'value2');
  1820. * @endcode
  1821. * @param $submit
  1822. * Value of the submit button whose click is to be emulated. For example,
  1823. * t('Save'). The processing of the request depends on this value. For
  1824. * example, a form may have one button with the value t('Save') and another
  1825. * button with the value t('Delete'), and execute different code depending
  1826. * on which one is clicked.
  1827. *
  1828. * This function can also be called to emulate an Ajax submission. In this
  1829. * case, this value needs to be an array with the following keys:
  1830. * - path: A path to submit the form values to for Ajax-specific processing,
  1831. * which is likely different than the $path parameter used for retrieving
  1832. * the initial form. Defaults to 'system/ajax'.
  1833. * - triggering_element: If the value for the 'path' key is 'system/ajax' or
  1834. * another generic Ajax processing path, this needs to be set to the name
  1835. * of the element. If the name doesn't identify the element uniquely, then
  1836. * this should instead be an array with a single key/value pair,
  1837. * corresponding to the element name and value. The callback for the
  1838. * generic Ajax processing path uses this to find the #ajax information
  1839. * for the element, including which specific callback to use for
  1840. * processing the request.
  1841. *
  1842. * This can also be set to NULL in order to emulate an Internet Explorer
  1843. * submission of a form with a single text field, and pressing ENTER in that
  1844. * textfield: under these conditions, no button information is added to the
  1845. * POST data.
  1846. * @param $options
  1847. * Options to be forwarded to url().
  1848. * @param $headers
  1849. * An array containing additional HTTP request headers, each formatted as
  1850. * "name: value".
  1851. * @param $form_html_id
  1852. * (optional) HTML ID of the form to be submitted. On some pages
  1853. * there are many identical forms, so just using the value of the submit
  1854. * button is not enough. For example: 'trigger-node-presave-assign-form'.
  1855. * Note that this is not the Drupal $form_id, but rather the HTML ID of the
  1856. * form, which is typically the same thing but with hyphens replacing the
  1857. * underscores.
  1858. * @param $extra_post
  1859. * (optional) A string of additional data to append to the POST submission.
  1860. * This can be used to add POST data for which there are no HTML fields, as
  1861. * is done by drupalPostAJAX(). This string is literally appended to the
  1862. * POST data, so it must already be urlencoded and contain a leading "&"
  1863. * (e.g., "&extra_var1=hello+world&extra_var2=you%26me").
  1864. */
  1865. protected function drupalPost($path, $edit, $submit, array $options = array(), array $headers = array(), $form_html_id = NULL, $extra_post = NULL) {
  1866. $submit_matches = FALSE;
  1867. $ajax = is_array($submit);
  1868. if (isset($path)) {
  1869. $this->drupalGet($path, $options);
  1870. }
  1871. if ($this->parse()) {
  1872. $edit_save = $edit;
  1873. // Let's iterate over all the forms.
  1874. $xpath = "//form";
  1875. if (!empty($form_html_id)) {
  1876. $xpath .= "[@id='" . $form_html_id . "']";
  1877. }
  1878. $forms = $this->xpath($xpath);
  1879. foreach ($forms as $form) {
  1880. // We try to set the fields of this form as specified in $edit.
  1881. $edit = $edit_save;
  1882. $post = array();
  1883. $upload = array();
  1884. $submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
  1885. $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
  1886. if ($ajax) {
  1887. $action = $this->getAbsoluteUrl(!empty($submit['path']) ? $submit['path'] : 'system/ajax');
  1888. // Ajax callbacks verify the triggering element if necessary, so while
  1889. // we may eventually want extra code that verifies it in the
  1890. // handleForm() function, it's not currently a requirement.
  1891. $submit_matches = TRUE;
  1892. }
  1893. // We post only if we managed to handle every field in edit and the
  1894. // submit button matches.
  1895. if (!$edit && ($submit_matches || !isset($submit))) {
  1896. $post_array = $post;
  1897. if ($upload) {
  1898. // TODO: cURL handles file uploads for us, but the implementation
  1899. // is broken. This is a less than elegant workaround. Alternatives
  1900. // are being explored at #253506.
  1901. foreach ($upload as $key => $file) {
  1902. $file = drupal_realpath($file);
  1903. if ($file && is_file($file)) {
  1904. // Use the new CurlFile class for file uploads when using PHP
  1905. // 5.5 or higher.
  1906. if (class_exists('CurlFile')) {
  1907. $post[$key] = curl_file_create($file);
  1908. }
  1909. else {
  1910. $post[$key] = '@' . $file;
  1911. }
  1912. }
  1913. }
  1914. }
  1915. else {
  1916. foreach ($post as $key => $value) {
  1917. // Encode according to application/x-www-form-urlencoded
  1918. // Both names and values needs to be urlencoded, according to
  1919. // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
  1920. $post[$key] = urlencode($key) . '=' . urlencode($value);
  1921. }
  1922. $post = implode('&', $post) . $extra_post;
  1923. }
  1924. $out = $this->curlExec(array(CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers));
  1925. // Ensure that any changes to variables in the other thread are picked up.
  1926. $this->refreshVariables();
  1927. // Replace original page output with new output from redirected page(s).
  1928. if ($new = $this->checkForMetaRefresh()) {
  1929. $out = $new;
  1930. }
  1931. $this->verbose('POST request to: ' . $path .
  1932. '<hr />Ending URL: ' . $this->getUrl() .
  1933. '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE) .
  1934. '<hr />' . $out);
  1935. return $out;
  1936. }
  1937. }
  1938. // We have not found a form which contained all fields of $edit.
  1939. foreach ($edit as $name => $value) {
  1940. $this->fail(t('Failed to set field @name to @value', array('@name' => $name, '@value' => $value)));
  1941. }
  1942. if (!$ajax && isset($submit)) {
  1943. $this->assertTrue($submit_matches, t('Found the @submit button', array('@submit' => $submit)));
  1944. }
  1945. $this->fail(t('Found the requested form fields at @path', array('@path' => $path)));
  1946. }
  1947. }
  1948. /**
  1949. * Execute an Ajax submission.
  1950. *
  1951. * This executes a POST as ajax.js does. It uses the returned JSON data, an
  1952. * array of commands, to update $this->content using equivalent DOM
  1953. * manipulation as is used by ajax.js. It also returns the array of commands.
  1954. *
  1955. * @param $path
  1956. * Location of the form containing the Ajax enabled element to test. Can be
  1957. * either a Drupal path or an absolute path or NULL to use the current page.
  1958. * @param $edit
  1959. * Field data in an associative array. Changes the current input fields
  1960. * (where possible) to the values indicated.
  1961. * @param $triggering_element
  1962. * The name of the form element that is responsible for triggering the Ajax
  1963. * functionality to test. May be a string or, if the triggering element is
  1964. * a button, an associative array where the key is the name of the button
  1965. * and the value is the button label. i.e.) array('op' => t('Refresh')).
  1966. * @param $ajax_path
  1967. * (optional) Override the path set by the Ajax settings of the triggering
  1968. * element. In the absence of both the triggering element's Ajax path and
  1969. * $ajax_path 'system/ajax' will be used.
  1970. * @param $options
  1971. * (optional) Options to be forwarded to url().
  1972. * @param $headers
  1973. * (optional) An array containing additional HTTP request headers, each
  1974. * formatted as "name: value". Forwarded to drupalPost().
  1975. * @param $form_html_id
  1976. * (optional) HTML ID of the form to be submitted, use when there is more
  1977. * than one identical form on the same page and the value of the triggering
  1978. * element is not enough to identify the form. Note this is not the Drupal
  1979. * ID of the form but rather the HTML ID of the form.
  1980. * @param $ajax_settings
  1981. * (optional) An array of Ajax settings which if specified will be used in
  1982. * place of the Ajax settings of the triggering element.
  1983. *
  1984. * @return
  1985. * An array of Ajax commands.
  1986. *
  1987. * @see drupalPost()
  1988. * @see ajax.js
  1989. */
  1990. protected function drupalPostAJAX($path, $edit, $triggering_element, $ajax_path = NULL, array $options = array(), array $headers = array(), $form_html_id = NULL, $ajax_settings = NULL) {
  1991. // Get the content of the initial page prior to calling drupalPost(), since
  1992. // drupalPost() replaces $this->content.
  1993. if (isset($path)) {
  1994. $this->drupalGet($path, $options);
  1995. }
  1996. $content = $this->content;
  1997. $drupal_settings = $this->drupalSettings;
  1998. // Get the Ajax settings bound to the triggering element.
  1999. if (!isset($ajax_settings)) {
  2000. if (is_array($triggering_element)) {
  2001. $xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
  2002. }
  2003. else {
  2004. $xpath = '//*[@name="' . $triggering_element . '"]';
  2005. }
  2006. if (isset($form_html_id)) {
  2007. $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
  2008. }
  2009. $element = $this->xpath($xpath);
  2010. $element_id = (string) $element[0]['id'];
  2011. $ajax_settings = $drupal_settings['ajax'][$element_id];
  2012. }
  2013. // Add extra information to the POST data as ajax.js does.
  2014. $extra_post = '';
  2015. if (isset($ajax_settings['submit'])) {
  2016. foreach ($ajax_settings['submit'] as $key => $value) {
  2017. $extra_post .= '&' . urlencode($key) . '=' . urlencode($value);
  2018. }
  2019. }
  2020. foreach ($this->xpath('//*[@id]') as $element) {
  2021. $id = (string) $element['id'];
  2022. $extra_post .= '&' . urlencode('ajax_html_ids[]') . '=' . urlencode($id);
  2023. }
  2024. if (isset($drupal_settings['ajaxPageState'])) {
  2025. $extra_post .= '&' . urlencode('ajax_page_state[theme]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme']);
  2026. $extra_post .= '&' . urlencode('ajax_page_state[theme_token]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme_token']);
  2027. foreach ($drupal_settings['ajaxPageState']['css'] as $key => $value) {
  2028. $extra_post .= '&' . urlencode("ajax_page_state[css][$key]") . '=1';
  2029. }
  2030. foreach ($drupal_settings['ajaxPageState']['js'] as $key => $value) {
  2031. $extra_post .= '&' . urlencode("ajax_page_state[js][$key]") . '=1';
  2032. }
  2033. }
  2034. // Unless a particular path is specified, use the one specified by the
  2035. // Ajax settings, or else 'system/ajax'.
  2036. if (!isset($ajax_path)) {
  2037. $ajax_path = isset($ajax_settings['url']) ? $ajax_settings['url'] : 'system/ajax';
  2038. }
  2039. // Submit the POST request.
  2040. $return = drupal_json_decode($this->drupalPost(NULL, $edit, array('path' => $ajax_path, 'triggering_element' => $triggering_element), $options, $headers, $form_html_id, $extra_post));
  2041. $this->assertIdentical($this->drupalGetHeader('X-Drupal-Ajax-Token'), '1', 'Ajax response header found.');
  2042. // Change the page content by applying the returned commands.
  2043. if (!empty($ajax_settings) && !empty($return)) {
  2044. // ajax.js applies some defaults to the settings object, so do the same
  2045. // for what's used by this function.
  2046. $ajax_settings += array(
  2047. 'method' => 'replaceWith',
  2048. );
  2049. // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
  2050. // them.
  2051. $dom = new DOMDocument();
  2052. @$dom->loadHTML($content);
  2053. // XPath allows for finding wrapper nodes better than DOM does.
  2054. $xpath = new DOMXPath($dom);
  2055. foreach ($return as $command) {
  2056. switch ($command['command']) {
  2057. case 'settings':
  2058. $drupal_settings = drupal_array_merge_deep($drupal_settings, $command['settings']);
  2059. break;
  2060. case 'insert':
  2061. $wrapperNode = NULL;
  2062. // When a command doesn't specify a selector, use the
  2063. // #ajax['wrapper'] which is always an HTML ID.
  2064. if (!isset($command['selector'])) {
  2065. $wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0);
  2066. }
  2067. // @todo Ajax commands can target any jQuery selector, but these are
  2068. // hard to fully emulate with XPath. For now, just handle 'head'
  2069. // and 'body', since these are used by ajax_render().
  2070. elseif (in_array($command['selector'], array('head', 'body'))) {
  2071. $wrapperNode = $xpath->query('//' . $command['selector'])->item(0);
  2072. }
  2073. if ($wrapperNode) {
  2074. // ajax.js adds an enclosing DIV to work around a Safari bug.
  2075. $newDom = new DOMDocument();
  2076. // DOM can load HTML soup. But, HTML soup can throw warnings,
  2077. // suppress them.
  2078. $newDom->loadHTML('<div>' . $command['data'] . '</div>');
  2079. // Suppress warnings thrown when duplicate HTML IDs are
  2080. // encountered. This probably means we are replacing an element
  2081. // with the same ID.
  2082. $newNode = @$dom->importNode($newDom->documentElement->firstChild->firstChild, TRUE);
  2083. $method = isset($command['method']) ? $command['method'] : $ajax_settings['method'];
  2084. // The "method" is a jQuery DOM manipulation function. Emulate
  2085. // each one using PHP's DOMNode API.
  2086. switch ($method) {
  2087. case 'replaceWith':
  2088. $wrapperNode->parentNode->replaceChild($newNode, $wrapperNode);
  2089. break;
  2090. case 'append':
  2091. $wrapperNode->appendChild($newNode);
  2092. break;
  2093. case 'prepend':
  2094. // If no firstChild, insertBefore() falls back to
  2095. // appendChild().
  2096. $wrapperNode->insertBefore($newNode, $wrapperNode->firstChild);
  2097. break;
  2098. case 'before':
  2099. $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode);
  2100. break;
  2101. case 'after':
  2102. // If no nextSibling, insertBefore() falls back to
  2103. // appendChild().
  2104. $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling);
  2105. break;
  2106. case 'html':
  2107. foreach ($wrapperNode->childNodes as $childNode) {
  2108. $wrapperNode->removeChild($childNode);
  2109. }
  2110. $wrapperNode->appendChild($newNode);
  2111. break;
  2112. }
  2113. }
  2114. break;
  2115. case 'updateBuildId':
  2116. $buildId = $xpath->query('//input[@name="form_build_id" and @value="' . $command['old'] . '"]')->item(0);
  2117. if ($buildId) {
  2118. $buildId->setAttribute('value', $command['new']);
  2119. }
  2120. break;
  2121. // @todo Add suitable implementations for these commands in order to
  2122. // have full test coverage of what ajax.js can do.
  2123. case 'remove':
  2124. break;
  2125. case 'changed':
  2126. break;
  2127. case 'css':
  2128. break;
  2129. case 'data':
  2130. break;
  2131. case 'restripe':
  2132. break;
  2133. case 'add_css':
  2134. break;
  2135. }
  2136. }
  2137. $content = $dom->saveHTML();
  2138. }
  2139. $this->drupalSetContent($content);
  2140. $this->drupalSetSettings($drupal_settings);
  2141. $verbose = 'AJAX POST request to: ' . $path;
  2142. $verbose .= '<br />AJAX callback path: ' . $ajax_path;
  2143. $verbose .= '<hr />Ending URL: ' . $this->getUrl();
  2144. $verbose .= '<hr />' . $this->content;
  2145. $this->verbose($verbose);
  2146. return $return;
  2147. }
  2148. /**
  2149. * Runs cron in the Drupal installed by Simpletest.
  2150. */
  2151. protected function cronRun() {
  2152. $this->drupalGet($GLOBALS['base_url'] . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => variable_get('cron_key', 'drupal'))));
  2153. }
  2154. /**
  2155. * Check for meta refresh tag and if found call drupalGet() recursively. This
  2156. * function looks for the http-equiv attribute to be set to "Refresh"
  2157. * and is case-sensitive.
  2158. *
  2159. * @return
  2160. * Either the new page content or FALSE.
  2161. */
  2162. protected function checkForMetaRefresh() {
  2163. if (strpos($this->drupalGetContent(), '<meta ') && $this->parse()) {
  2164. $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
  2165. if (!empty($refresh)) {
  2166. // Parse the content attribute of the meta tag for the format:
  2167. // "[delay]: URL=[page_to_redirect_to]".
  2168. if (preg_match('/\d+;\s*URL=(?P<url>.*)/i', $refresh[0]['content'], $match)) {
  2169. return $this->drupalGet($this->getAbsoluteUrl(decode_entities($match['url'])));
  2170. }
  2171. }
  2172. }
  2173. return FALSE;
  2174. }
  2175. /**
  2176. * Retrieves only the headers for a Drupal path or an absolute path.
  2177. *
  2178. * @param $path
  2179. * Drupal path or URL to load into internal browser
  2180. * @param $options
  2181. * Options to be forwarded to url().
  2182. * @param $headers
  2183. * An array containing additional HTTP request headers, each formatted as
  2184. * "name: value".
  2185. * @return
  2186. * The retrieved headers, also available as $this->drupalGetContent()
  2187. */
  2188. protected function drupalHead($path, array $options = array(), array $headers = array()) {
  2189. $options['absolute'] = TRUE;
  2190. $out = $this->curlExec(array(CURLOPT_NOBODY => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_HTTPHEADER => $headers));
  2191. $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
  2192. return $out;
  2193. }
  2194. /**
  2195. * Handle form input related to drupalPost(). Ensure that the specified fields
  2196. * exist and attempt to create POST data in the correct manner for the particular
  2197. * field type.
  2198. *
  2199. * @param $post
  2200. * Reference to array of post values.
  2201. * @param $edit
  2202. * Reference to array of edit values to be checked against the form.
  2203. * @param $submit
  2204. * Form submit button value.
  2205. * @param $form
  2206. * Array of form elements.
  2207. * @return
  2208. * Submit value matches a valid submit input in the form.
  2209. */
  2210. protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
  2211. // Retrieve the form elements.
  2212. $elements = $form->xpath('.//input[not(@disabled)]|.//textarea[not(@disabled)]|.//select[not(@disabled)]');
  2213. $submit_matches = FALSE;
  2214. foreach ($elements as $element) {
  2215. // SimpleXML objects need string casting all the time.
  2216. $name = (string) $element['name'];
  2217. // This can either be the type of <input> or the name of the tag itself
  2218. // for <select> or <textarea>.
  2219. $type = isset($element['type']) ? (string) $element['type'] : $element->getName();
  2220. $value = isset($element['value']) ? (string) $element['value'] : '';
  2221. $done = FALSE;
  2222. if (isset($edit[$name])) {
  2223. switch ($type) {
  2224. case 'text':
  2225. case 'tel':
  2226. case 'textarea':
  2227. case 'url':
  2228. case 'number':
  2229. case 'range':
  2230. case 'color':
  2231. case 'hidden':
  2232. case 'password':
  2233. case 'email':
  2234. case 'search':
  2235. $post[$name] = $edit[$name];
  2236. unset($edit[$name]);
  2237. break;
  2238. case 'radio':
  2239. if ($edit[$name] == $value) {
  2240. $post[$name] = $edit[$name];
  2241. unset($edit[$name]);
  2242. }
  2243. break;
  2244. case 'checkbox':
  2245. // To prevent checkbox from being checked.pass in a FALSE,
  2246. // otherwise the checkbox will be set to its value regardless
  2247. // of $edit.
  2248. if ($edit[$name] === FALSE) {
  2249. unset($edit[$name]);
  2250. continue 2;
  2251. }
  2252. else {
  2253. unset($edit[$name]);
  2254. $post[$name] = $value;
  2255. }
  2256. break;
  2257. case 'select':
  2258. $new_value = $edit[$name];
  2259. $options = $this->getAllOptions($element);
  2260. if (is_array($new_value)) {
  2261. // Multiple select box.
  2262. if (!empty($new_value)) {
  2263. $index = 0;
  2264. $key = preg_replace('/\[\]$/', '', $name);
  2265. foreach ($options as $option) {
  2266. $option_value = (string) $option['value'];
  2267. if (in_array($option_value, $new_value)) {
  2268. $post[$key . '[' . $index++ . ']'] = $option_value;
  2269. $done = TRUE;
  2270. unset($edit[$name]);
  2271. }
  2272. }
  2273. }
  2274. else {
  2275. // No options selected: do not include any POST data for the
  2276. // element.
  2277. $done = TRUE;
  2278. unset($edit[$name]);
  2279. }
  2280. }
  2281. else {
  2282. // Single select box.
  2283. foreach ($options as $option) {
  2284. if ($new_value == $option['value']) {
  2285. $post[$name] = $new_value;
  2286. unset($edit[$name]);
  2287. $done = TRUE;
  2288. break;
  2289. }
  2290. }
  2291. }
  2292. break;
  2293. case 'file':
  2294. $upload[$name] = $edit[$name];
  2295. unset($edit[$name]);
  2296. break;
  2297. }
  2298. }
  2299. if (!isset($post[$name]) && !$done) {
  2300. switch ($type) {
  2301. case 'textarea':
  2302. $post[$name] = (string) $element;
  2303. break;
  2304. case 'select':
  2305. $single = empty($element['multiple']);
  2306. $first = TRUE;
  2307. $index = 0;
  2308. $key = preg_replace('/\[\]$/', '', $name);
  2309. $options = $this->getAllOptions($element);
  2310. foreach ($options as $option) {
  2311. // For single select, we load the first option, if there is a
  2312. // selected option that will overwrite it later.
  2313. if ($option['selected'] || ($first && $single)) {
  2314. $first = FALSE;
  2315. if ($single) {
  2316. $post[$name] = (string) $option['value'];
  2317. }
  2318. else {
  2319. $post[$key . '[' . $index++ . ']'] = (string) $option['value'];
  2320. }
  2321. }
  2322. }
  2323. break;
  2324. case 'file':
  2325. break;
  2326. case 'submit':
  2327. case 'image':
  2328. if (isset($submit) && $submit == $value) {
  2329. $post[$name] = $value;
  2330. $submit_matches = TRUE;
  2331. }
  2332. break;
  2333. case 'radio':
  2334. case 'checkbox':
  2335. if (!isset($element['checked'])) {
  2336. break;
  2337. }
  2338. // Deliberate no break.
  2339. default:
  2340. $post[$name] = $value;
  2341. }
  2342. }
  2343. }
  2344. return $submit_matches;
  2345. }
  2346. /**
  2347. * Builds an XPath query.
  2348. *
  2349. * Builds an XPath query by replacing placeholders in the query by the value
  2350. * of the arguments.
  2351. *
  2352. * XPath 1.0 (the version supported by libxml2, the underlying XML library
  2353. * used by PHP) doesn't support any form of quotation. This function
  2354. * simplifies the building of XPath expression.
  2355. *
  2356. * @param $xpath
  2357. * An XPath query, possibly with placeholders in the form ':name'.
  2358. * @param $args
  2359. * An array of arguments with keys in the form ':name' matching the
  2360. * placeholders in the query. The values may be either strings or numeric
  2361. * values.
  2362. * @return
  2363. * An XPath query with arguments replaced.
  2364. */
  2365. protected function buildXPathQuery($xpath, array $args = array()) {
  2366. // Replace placeholders.
  2367. foreach ($args as $placeholder => $value) {
  2368. // XPath 1.0 doesn't support a way to escape single or double quotes in a
  2369. // string literal. We split double quotes out of the string, and encode
  2370. // them separately.
  2371. if (is_string($value)) {
  2372. // Explode the text at the quote characters.
  2373. $parts = explode('"', $value);
  2374. // Quote the parts.
  2375. foreach ($parts as &$part) {
  2376. $part = '"' . $part . '"';
  2377. }
  2378. // Return the string.
  2379. $value = count($parts) > 1 ? 'concat(' . implode(', \'"\', ', $parts) . ')' : $parts[0];
  2380. }
  2381. $xpath = preg_replace('/' . preg_quote($placeholder) . '\b/', $value, $xpath);
  2382. }
  2383. return $xpath;
  2384. }
  2385. /**
  2386. * Perform an xpath search on the contents of the internal browser. The search
  2387. * is relative to the root element (HTML tag normally) of the page.
  2388. *
  2389. * @param $xpath
  2390. * The xpath string to use in the search.
  2391. * @param array $arguments
  2392. * An array of arguments with keys in the form ':name' matching the
  2393. * placeholders in the query. The values may be either strings or numeric
  2394. * values.
  2395. *
  2396. * @return
  2397. * The return value of the xpath search. For details on the xpath string
  2398. * format and return values see the SimpleXML documentation,
  2399. * http://us.php.net/manual/function.simplexml-element-xpath.php.
  2400. */
  2401. protected function xpath($xpath, array $arguments = array()) {
  2402. if ($this->parse()) {
  2403. $xpath = $this->buildXPathQuery($xpath, $arguments);
  2404. $result = $this->elements->xpath($xpath);
  2405. // Some combinations of PHP / libxml versions return an empty array
  2406. // instead of the documented FALSE. Forcefully convert any falsish values
  2407. // to an empty array to allow foreach(...) constructions.
  2408. return $result ? $result : array();
  2409. }
  2410. else {
  2411. return FALSE;
  2412. }
  2413. }
  2414. /**
  2415. * Get all option elements, including nested options, in a select.
  2416. *
  2417. * @param $element
  2418. * The element for which to get the options.
  2419. * @return
  2420. * Option elements in select.
  2421. */
  2422. protected function getAllOptions(SimpleXMLElement $element) {
  2423. $options = array();
  2424. // Add all options items.
  2425. foreach ($element->option as $option) {
  2426. $options[] = $option;
  2427. }
  2428. // Search option group children.
  2429. if (isset($element->optgroup)) {
  2430. foreach ($element->optgroup as $group) {
  2431. $options = array_merge($options, $this->getAllOptions($group));
  2432. }
  2433. }
  2434. return $options;
  2435. }
  2436. /**
  2437. * Pass if a link with the specified label is found, and optional with the
  2438. * specified index.
  2439. *
  2440. * @param $label
  2441. * Text between the anchor tags.
  2442. * @param $index
  2443. * Link position counting from zero.
  2444. * @param $message
  2445. * Message to display.
  2446. * @param $group
  2447. * The group this message belongs to, defaults to 'Other'.
  2448. * @return
  2449. * TRUE if the assertion succeeded, FALSE otherwise.
  2450. */
  2451. protected function assertLink($label, $index = 0, $message = '', $group = 'Other') {
  2452. $links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
  2453. $message = ($message ? $message : t('Link with label %label found.', array('%label' => $label)));
  2454. return $this->assert(isset($links[$index]), $message, $group);
  2455. }
  2456. /**
  2457. * Pass if a link with the specified label is not found.
  2458. *
  2459. * @param $label
  2460. * Text between the anchor tags.
  2461. * @param $message
  2462. * Message to display.
  2463. * @param $group
  2464. * The group this message belongs to, defaults to 'Other'.
  2465. * @return
  2466. * TRUE if the assertion succeeded, FALSE otherwise.
  2467. */
  2468. protected function assertNoLink($label, $message = '', $group = 'Other') {
  2469. $links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
  2470. $message = ($message ? $message : t('Link with label %label not found.', array('%label' => $label)));
  2471. return $this->assert(empty($links), $message, $group);
  2472. }
  2473. /**
  2474. * Pass if a link containing a given href (part) is found.
  2475. *
  2476. * @param $href
  2477. * The full or partial value of the 'href' attribute of the anchor tag.
  2478. * @param $index
  2479. * Link position counting from zero.
  2480. * @param $message
  2481. * Message to display.
  2482. * @param $group
  2483. * The group this message belongs to, defaults to 'Other'.
  2484. *
  2485. * @return
  2486. * TRUE if the assertion succeeded, FALSE otherwise.
  2487. */
  2488. protected function assertLinkByHref($href, $index = 0, $message = '', $group = 'Other') {
  2489. $links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
  2490. $message = ($message ? $message : t('Link containing href %href found.', array('%href' => $href)));
  2491. return $this->assert(isset($links[$index]), $message, $group);
  2492. }
  2493. /**
  2494. * Pass if a link containing a given href (part) is not found.
  2495. *
  2496. * @param $href
  2497. * The full or partial value of the 'href' attribute of the anchor tag.
  2498. * @param $message
  2499. * Message to display.
  2500. * @param $group
  2501. * The group this message belongs to, defaults to 'Other'.
  2502. *
  2503. * @return
  2504. * TRUE if the assertion succeeded, FALSE otherwise.
  2505. */
  2506. protected function assertNoLinkByHref($href, $message = '', $group = 'Other') {
  2507. $links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
  2508. $message = ($message ? $message : t('No link containing href %href found.', array('%href' => $href)));
  2509. return $this->assert(empty($links), $message, $group);
  2510. }
  2511. /**
  2512. * Follows a link by name.
  2513. *
  2514. * Will click the first link found with this link text by default, or a later
  2515. * one if an index is given. Match is case sensitive with normalized space.
  2516. * The label is translated label.
  2517. *
  2518. * If the link is discovered and clicked, the test passes. Fail otherwise.
  2519. *
  2520. * @param $label
  2521. * Text between the anchor tags.
  2522. * @param $index
  2523. * Link position counting from zero.
  2524. * @return
  2525. * Page contents on success, or FALSE on failure.
  2526. */
  2527. protected function clickLink($label, $index = 0) {
  2528. $url_before = $this->getUrl();
  2529. $urls = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
  2530. if (isset($urls[$index])) {
  2531. $url_target = $this->getAbsoluteUrl($urls[$index]['href']);
  2532. $this->pass(t('Clicked link %label (@url_target) from @url_before', array('%label' => $label, '@url_target' => $url_target, '@url_before' => $url_before)), 'Browser');
  2533. return $this->drupalGet($url_target);
  2534. }
  2535. $this->fail(t('Link %label does not exist on @url_before', array('%label' => $label, '@url_before' => $url_before)), 'Browser');
  2536. return FALSE;
  2537. }
  2538. /**
  2539. * Takes a path and returns an absolute path.
  2540. *
  2541. * @param $path
  2542. * A path from the internal browser content.
  2543. * @return
  2544. * The $path with $base_url prepended, if necessary.
  2545. */
  2546. protected function getAbsoluteUrl($path) {
  2547. global $base_url, $base_path;
  2548. $parts = parse_url($path);
  2549. if (empty($parts['host'])) {
  2550. // Ensure that we have a string (and no xpath object).
  2551. $path = (string) $path;
  2552. // Strip $base_path, if existent.
  2553. $length = strlen($base_path);
  2554. if (substr($path, 0, $length) === $base_path) {
  2555. $path = substr($path, $length);
  2556. }
  2557. // Ensure that we have an absolute path.
  2558. if (empty($path) || $path[0] !== '/') {
  2559. $path = '/' . $path;
  2560. }
  2561. // Finally, prepend the $base_url.
  2562. $path = $base_url . $path;
  2563. }
  2564. return $path;
  2565. }
  2566. /**
  2567. * Get the current URL from the cURL handler.
  2568. *
  2569. * @return
  2570. * The current URL.
  2571. */
  2572. protected function getUrl() {
  2573. return $this->url;
  2574. }
  2575. /**
  2576. * Gets the HTTP response headers of the requested page. Normally we are only
  2577. * interested in the headers returned by the last request. However, if a page
  2578. * is redirected or HTTP authentication is in use, multiple requests will be
  2579. * required to retrieve the page. Headers from all requests may be requested
  2580. * by passing TRUE to this function.
  2581. *
  2582. * @param $all_requests
  2583. * Boolean value specifying whether to return headers from all requests
  2584. * instead of just the last request. Defaults to FALSE.
  2585. * @return
  2586. * A name/value array if headers from only the last request are requested.
  2587. * If headers from all requests are requested, an array of name/value
  2588. * arrays, one for each request.
  2589. *
  2590. * The pseudonym ":status" is used for the HTTP status line.
  2591. *
  2592. * Values for duplicate headers are stored as a single comma-separated list.
  2593. */
  2594. protected function drupalGetHeaders($all_requests = FALSE) {
  2595. $request = 0;
  2596. $headers = array($request => array());
  2597. foreach ($this->headers as $header) {
  2598. $header = trim($header);
  2599. if ($header === '') {
  2600. $request++;
  2601. }
  2602. else {
  2603. if (strpos($header, 'HTTP/') === 0) {
  2604. $name = ':status';
  2605. $value = $header;
  2606. }
  2607. else {
  2608. list($name, $value) = explode(':', $header, 2);
  2609. $name = strtolower($name);
  2610. }
  2611. if (isset($headers[$request][$name])) {
  2612. $headers[$request][$name] .= ',' . trim($value);
  2613. }
  2614. else {
  2615. $headers[$request][$name] = trim($value);
  2616. }
  2617. }
  2618. }
  2619. if (!$all_requests) {
  2620. $headers = array_pop($headers);
  2621. }
  2622. return $headers;
  2623. }
  2624. /**
  2625. * Gets the value of an HTTP response header. If multiple requests were
  2626. * required to retrieve the page, only the headers from the last request will
  2627. * be checked by default. However, if TRUE is passed as the second argument,
  2628. * all requests will be processed from last to first until the header is
  2629. * found.
  2630. *
  2631. * @param $name
  2632. * The name of the header to retrieve. Names are case-insensitive (see RFC
  2633. * 2616 section 4.2).
  2634. * @param $all_requests
  2635. * Boolean value specifying whether to check all requests if the header is
  2636. * not found in the last request. Defaults to FALSE.
  2637. * @return
  2638. * The HTTP header value or FALSE if not found.
  2639. */
  2640. protected function drupalGetHeader($name, $all_requests = FALSE) {
  2641. $name = strtolower($name);
  2642. $header = FALSE;
  2643. if ($all_requests) {
  2644. foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
  2645. if (isset($headers[$name])) {
  2646. $header = $headers[$name];
  2647. break;
  2648. }
  2649. }
  2650. }
  2651. else {
  2652. $headers = $this->drupalGetHeaders();
  2653. if (isset($headers[$name])) {
  2654. $header = $headers[$name];
  2655. }
  2656. }
  2657. return $header;
  2658. }
  2659. /**
  2660. * Gets the current raw HTML of requested page.
  2661. */
  2662. protected function drupalGetContent() {
  2663. return $this->content;
  2664. }
  2665. /**
  2666. * Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
  2667. */
  2668. protected function drupalGetSettings() {
  2669. return $this->drupalSettings;
  2670. }
  2671. /**
  2672. * Gets an array containing all e-mails sent during this test case.
  2673. *
  2674. * @param $filter
  2675. * An array containing key/value pairs used to filter the e-mails that are returned.
  2676. * @return
  2677. * An array containing e-mail messages captured during the current test.
  2678. */
  2679. protected function drupalGetMails($filter = array()) {
  2680. $captured_emails = variable_get('drupal_test_email_collector', array());
  2681. $filtered_emails = array();
  2682. foreach ($captured_emails as $message) {
  2683. foreach ($filter as $key => $value) {
  2684. if (!isset($message[$key]) || $message[$key] != $value) {
  2685. continue 2;
  2686. }
  2687. }
  2688. $filtered_emails[] = $message;
  2689. }
  2690. return $filtered_emails;
  2691. }
  2692. /**
  2693. * Sets the raw HTML content. This can be useful when a page has been fetched
  2694. * outside of the internal browser and assertions need to be made on the
  2695. * returned page.
  2696. *
  2697. * A good example would be when testing drupal_http_request(). After fetching
  2698. * the page the content can be set and page elements can be checked to ensure
  2699. * that the function worked properly.
  2700. */
  2701. protected function drupalSetContent($content, $url = 'internal:') {
  2702. $this->content = $content;
  2703. $this->url = $url;
  2704. $this->plainTextContent = FALSE;
  2705. $this->elements = FALSE;
  2706. $this->drupalSettings = array();
  2707. if (preg_match('/jQuery\.extend\(Drupal\.settings, (.*?)\);/', $content, $matches)) {
  2708. $this->drupalSettings = drupal_json_decode($matches[1]);
  2709. }
  2710. }
  2711. /**
  2712. * Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
  2713. */
  2714. protected function drupalSetSettings($settings) {
  2715. $this->drupalSettings = $settings;
  2716. }
  2717. /**
  2718. * Pass if the internal browser's URL matches the given path.
  2719. *
  2720. * @param $path
  2721. * The expected system path.
  2722. * @param $options
  2723. * (optional) Any additional options to pass for $path to url().
  2724. * @param $message
  2725. * Message to display.
  2726. * @param $group
  2727. * The group this message belongs to, defaults to 'Other'.
  2728. *
  2729. * @return
  2730. * TRUE on pass, FALSE on fail.
  2731. */
  2732. protected function assertUrl($path, array $options = array(), $message = '', $group = 'Other') {
  2733. if (!$message) {
  2734. $message = t('Current URL is @url.', array(
  2735. '@url' => var_export(url($path, $options), TRUE),
  2736. ));
  2737. }
  2738. $options['absolute'] = TRUE;
  2739. return $this->assertEqual($this->getUrl(), url($path, $options), $message, $group);
  2740. }
  2741. /**
  2742. * Pass if the raw text IS found on the loaded page, fail otherwise. Raw text
  2743. * refers to the raw HTML that the page generated.
  2744. *
  2745. * @param $raw
  2746. * Raw (HTML) string to look for.
  2747. * @param $message
  2748. * Message to display.
  2749. * @param $group
  2750. * The group this message belongs to, defaults to 'Other'.
  2751. * @return
  2752. * TRUE on pass, FALSE on fail.
  2753. */
  2754. protected function assertRaw($raw, $message = '', $group = 'Other') {
  2755. if (!$message) {
  2756. $message = t('Raw "@raw" found', array('@raw' => $raw));
  2757. }
  2758. return $this->assert(strpos($this->drupalGetContent(), (string) $raw) !== FALSE, $message, $group);
  2759. }
  2760. /**
  2761. * Pass if the raw text is NOT found on the loaded page, fail otherwise. Raw text
  2762. * refers to the raw HTML that the page generated.
  2763. *
  2764. * @param $raw
  2765. * Raw (HTML) string to look for.
  2766. * @param $message
  2767. * Message to display.
  2768. * @param $group
  2769. * The group this message belongs to, defaults to 'Other'.
  2770. * @return
  2771. * TRUE on pass, FALSE on fail.
  2772. */
  2773. protected function assertNoRaw($raw, $message = '', $group = 'Other') {
  2774. if (!$message) {
  2775. $message = t('Raw "@raw" not found', array('@raw' => $raw));
  2776. }
  2777. return $this->assert(strpos($this->drupalGetContent(), (string) $raw) === FALSE, $message, $group);
  2778. }
  2779. /**
  2780. * Pass if the text IS found on the text version of the page. The text version
  2781. * is the equivalent of what a user would see when viewing through a web browser.
  2782. * In other words the HTML has been filtered out of the contents.
  2783. *
  2784. * @param $text
  2785. * Plain text to look for.
  2786. * @param $message
  2787. * Message to display.
  2788. * @param $group
  2789. * The group this message belongs to, defaults to 'Other'.
  2790. * @return
  2791. * TRUE on pass, FALSE on fail.
  2792. */
  2793. protected function assertText($text, $message = '', $group = 'Other') {
  2794. return $this->assertTextHelper($text, $message, $group, FALSE);
  2795. }
  2796. /**
  2797. * Pass if the text is NOT found on the text version of the page. The text version
  2798. * is the equivalent of what a user would see when viewing through a web browser.
  2799. * In other words the HTML has been filtered out of the contents.
  2800. *
  2801. * @param $text
  2802. * Plain text to look for.
  2803. * @param $message
  2804. * Message to display.
  2805. * @param $group
  2806. * The group this message belongs to, defaults to 'Other'.
  2807. * @return
  2808. * TRUE on pass, FALSE on fail.
  2809. */
  2810. protected function assertNoText($text, $message = '', $group = 'Other') {
  2811. return $this->assertTextHelper($text, $message, $group, TRUE);
  2812. }
  2813. /**
  2814. * Helper for assertText and assertNoText.
  2815. *
  2816. * It is not recommended to call this function directly.
  2817. *
  2818. * @param $text
  2819. * Plain text to look for.
  2820. * @param $message
  2821. * Message to display.
  2822. * @param $group
  2823. * The group this message belongs to.
  2824. * @param $not_exists
  2825. * TRUE if this text should not exist, FALSE if it should.
  2826. * @return
  2827. * TRUE on pass, FALSE on fail.
  2828. */
  2829. protected function assertTextHelper($text, $message = '', $group, $not_exists) {
  2830. if ($this->plainTextContent === FALSE) {
  2831. $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
  2832. }
  2833. if (!$message) {
  2834. $message = !$not_exists ? t('"@text" found', array('@text' => $text)) : t('"@text" not found', array('@text' => $text));
  2835. }
  2836. return $this->assert($not_exists == (strpos($this->plainTextContent, $text) === FALSE), $message, $group);
  2837. }
  2838. /**
  2839. * Pass if the text is found ONLY ONCE on the text version of the page.
  2840. *
  2841. * The text version is the equivalent of what a user would see when viewing
  2842. * through a web browser. In other words the HTML has been filtered out of
  2843. * the contents.
  2844. *
  2845. * @param $text
  2846. * Plain text to look for.
  2847. * @param $message
  2848. * Message to display.
  2849. * @param $group
  2850. * The group this message belongs to, defaults to 'Other'.
  2851. * @return
  2852. * TRUE on pass, FALSE on fail.
  2853. */
  2854. protected function assertUniqueText($text, $message = '', $group = 'Other') {
  2855. return $this->assertUniqueTextHelper($text, $message, $group, TRUE);
  2856. }
  2857. /**
  2858. * Pass if the text is found MORE THAN ONCE on the text version of the page.
  2859. *
  2860. * The text version is the equivalent of what a user would see when viewing
  2861. * through a web browser. In other words the HTML has been filtered out of
  2862. * the contents.
  2863. *
  2864. * @param $text
  2865. * Plain text to look for.
  2866. * @param $message
  2867. * Message to display.
  2868. * @param $group
  2869. * The group this message belongs to, defaults to 'Other'.
  2870. * @return
  2871. * TRUE on pass, FALSE on fail.
  2872. */
  2873. protected function assertNoUniqueText($text, $message = '', $group = 'Other') {
  2874. return $this->assertUniqueTextHelper($text, $message, $group, FALSE);
  2875. }
  2876. /**
  2877. * Helper for assertUniqueText and assertNoUniqueText.
  2878. *
  2879. * It is not recommended to call this function directly.
  2880. *
  2881. * @param $text
  2882. * Plain text to look for.
  2883. * @param $message
  2884. * Message to display.
  2885. * @param $group
  2886. * The group this message belongs to.
  2887. * @param $be_unique
  2888. * TRUE if this text should be found only once, FALSE if it should be found more than once.
  2889. * @return
  2890. * TRUE on pass, FALSE on fail.
  2891. */
  2892. protected function assertUniqueTextHelper($text, $message = '', $group, $be_unique) {
  2893. if ($this->plainTextContent === FALSE) {
  2894. $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
  2895. }
  2896. if (!$message) {
  2897. $message = '"' . $text . '"' . ($be_unique ? ' found only once' : ' found more than once');
  2898. }
  2899. $first_occurance = strpos($this->plainTextContent, $text);
  2900. if ($first_occurance === FALSE) {
  2901. return $this->assert(FALSE, $message, $group);
  2902. }
  2903. $offset = $first_occurance + strlen($text);
  2904. $second_occurance = strpos($this->plainTextContent, $text, $offset);
  2905. return $this->assert($be_unique == ($second_occurance === FALSE), $message, $group);
  2906. }
  2907. /**
  2908. * Will trigger a pass if the Perl regex pattern is found in the raw content.
  2909. *
  2910. * @param $pattern
  2911. * Perl regex to look for including the regex delimiters.
  2912. * @param $message
  2913. * Message to display.
  2914. * @param $group
  2915. * The group this message belongs to.
  2916. * @return
  2917. * TRUE on pass, FALSE on fail.
  2918. */
  2919. protected function assertPattern($pattern, $message = '', $group = 'Other') {
  2920. if (!$message) {
  2921. $message = t('Pattern "@pattern" found', array('@pattern' => $pattern));
  2922. }
  2923. return $this->assert((bool) preg_match($pattern, $this->drupalGetContent()), $message, $group);
  2924. }
  2925. /**
  2926. * Will trigger a pass if the perl regex pattern is not present in raw content.
  2927. *
  2928. * @param $pattern
  2929. * Perl regex to look for including the regex delimiters.
  2930. * @param $message
  2931. * Message to display.
  2932. * @param $group
  2933. * The group this message belongs to.
  2934. * @return
  2935. * TRUE on pass, FALSE on fail.
  2936. */
  2937. protected function assertNoPattern($pattern, $message = '', $group = 'Other') {
  2938. if (!$message) {
  2939. $message = t('Pattern "@pattern" not found', array('@pattern' => $pattern));
  2940. }
  2941. return $this->assert(!preg_match($pattern, $this->drupalGetContent()), $message, $group);
  2942. }
  2943. /**
  2944. * Pass if the page title is the given string.
  2945. *
  2946. * @param $title
  2947. * The string the title should be.
  2948. * @param $message
  2949. * Message to display.
  2950. * @param $group
  2951. * The group this message belongs to.
  2952. * @return
  2953. * TRUE on pass, FALSE on fail.
  2954. */
  2955. protected function assertTitle($title, $message = '', $group = 'Other') {
  2956. $actual = (string) current($this->xpath('//title'));
  2957. if (!$message) {
  2958. $message = t('Page title @actual is equal to @expected.', array(
  2959. '@actual' => var_export($actual, TRUE),
  2960. '@expected' => var_export($title, TRUE),
  2961. ));
  2962. }
  2963. return $this->assertEqual($actual, $title, $message, $group);
  2964. }
  2965. /**
  2966. * Pass if the page title is not the given string.
  2967. *
  2968. * @param $title
  2969. * The string the title should not be.
  2970. * @param $message
  2971. * Message to display.
  2972. * @param $group
  2973. * The group this message belongs to.
  2974. * @return
  2975. * TRUE on pass, FALSE on fail.
  2976. */
  2977. protected function assertNoTitle($title, $message = '', $group = 'Other') {
  2978. $actual = (string) current($this->xpath('//title'));
  2979. if (!$message) {
  2980. $message = t('Page title @actual is not equal to @unexpected.', array(
  2981. '@actual' => var_export($actual, TRUE),
  2982. '@unexpected' => var_export($title, TRUE),
  2983. ));
  2984. }
  2985. return $this->assertNotEqual($actual, $title, $message, $group);
  2986. }
  2987. /**
  2988. * Asserts themed output.
  2989. *
  2990. * @param $callback
  2991. * The name of the theme function to invoke; e.g. 'links' for theme_links().
  2992. * @param $variables
  2993. * (optional) An array of variables to pass to the theme function.
  2994. * @param $expected
  2995. * The expected themed output string.
  2996. * @param $message
  2997. * (optional) A message to display with the assertion. Do not translate
  2998. * messages: use format_string() to embed variables in the message text, not
  2999. * t(). If left blank, a default message will be displayed.
  3000. * @param $group
  3001. * (optional) The group this message is in, which is displayed in a column
  3002. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  3003. * translate this string. Defaults to 'Other'; most tests do not override
  3004. * this default.
  3005. *
  3006. * @return
  3007. * TRUE on pass, FALSE on fail.
  3008. */
  3009. protected function assertThemeOutput($callback, array $variables = array(), $expected, $message = '', $group = 'Other') {
  3010. $output = theme($callback, $variables);
  3011. $this->verbose('Variables:' . '<pre>' . check_plain(var_export($variables, TRUE)) . '</pre>'
  3012. . '<hr />' . 'Result:' . '<pre>' . check_plain(var_export($output, TRUE)) . '</pre>'
  3013. . '<hr />' . 'Expected:' . '<pre>' . check_plain(var_export($expected, TRUE)) . '</pre>'
  3014. . '<hr />' . $output
  3015. );
  3016. if (!$message) {
  3017. $message = '%callback rendered correctly.';
  3018. }
  3019. $message = format_string($message, array('%callback' => 'theme_' . $callback . '()'));
  3020. return $this->assertIdentical($output, $expected, $message, $group);
  3021. }
  3022. /**
  3023. * Asserts that a field exists in the current page by the given XPath.
  3024. *
  3025. * @param $xpath
  3026. * XPath used to find the field.
  3027. * @param $value
  3028. * (optional) Value of the field to assert. You may pass in NULL (default)
  3029. * to skip checking the actual value, while still checking that the field
  3030. * exists.
  3031. * @param $message
  3032. * (optional) Message to display.
  3033. * @param $group
  3034. * (optional) The group this message belongs to.
  3035. *
  3036. * @return
  3037. * TRUE on pass, FALSE on fail.
  3038. */
  3039. protected function assertFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
  3040. $fields = $this->xpath($xpath);
  3041. // If value specified then check array for match.
  3042. $found = TRUE;
  3043. if (isset($value)) {
  3044. $found = FALSE;
  3045. if ($fields) {
  3046. foreach ($fields as $field) {
  3047. if (isset($field['value']) && $field['value'] == $value) {
  3048. // Input element with correct value.
  3049. $found = TRUE;
  3050. }
  3051. elseif (isset($field->option)) {
  3052. // Select element found.
  3053. if ($this->getSelectedItem($field) == $value) {
  3054. $found = TRUE;
  3055. }
  3056. else {
  3057. // No item selected so use first item.
  3058. $items = $this->getAllOptions($field);
  3059. if (!empty($items) && $items[0]['value'] == $value) {
  3060. $found = TRUE;
  3061. }
  3062. }
  3063. }
  3064. elseif ((string) $field == $value) {
  3065. // Text area with correct text.
  3066. $found = TRUE;
  3067. }
  3068. }
  3069. }
  3070. }
  3071. return $this->assertTrue($fields && $found, $message, $group);
  3072. }
  3073. /**
  3074. * Get the selected value from a select field.
  3075. *
  3076. * @param $element
  3077. * SimpleXMLElement select element.
  3078. * @return
  3079. * The selected value or FALSE.
  3080. */
  3081. protected function getSelectedItem(SimpleXMLElement $element) {
  3082. foreach ($element->children() as $item) {
  3083. if (isset($item['selected'])) {
  3084. return $item['value'];
  3085. }
  3086. elseif ($item->getName() == 'optgroup') {
  3087. if ($value = $this->getSelectedItem($item)) {
  3088. return $value;
  3089. }
  3090. }
  3091. }
  3092. return FALSE;
  3093. }
  3094. /**
  3095. * Asserts that a field doesn't exist or its value doesn't match, by XPath.
  3096. *
  3097. * @param $xpath
  3098. * XPath used to find the field.
  3099. * @param $value
  3100. * (optional) Value for the field, to assert that the field's value on the
  3101. * page doesn't match it. You may pass in NULL to skip checking the
  3102. * value, while still checking that the field doesn't exist.
  3103. * @param $message
  3104. * (optional) Message to display.
  3105. * @param $group
  3106. * (optional) The group this message belongs to.
  3107. *
  3108. * @return
  3109. * TRUE on pass, FALSE on fail.
  3110. */
  3111. protected function assertNoFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
  3112. $fields = $this->xpath($xpath);
  3113. // If value specified then check array for match.
  3114. $found = TRUE;
  3115. if (isset($value)) {
  3116. $found = FALSE;
  3117. if ($fields) {
  3118. foreach ($fields as $field) {
  3119. if ($field['value'] == $value) {
  3120. $found = TRUE;
  3121. }
  3122. }
  3123. }
  3124. }
  3125. return $this->assertFalse($fields && $found, $message, $group);
  3126. }
  3127. /**
  3128. * Asserts that a field exists in the current page with the given name and value.
  3129. *
  3130. * @param $name
  3131. * Name of field to assert.
  3132. * @param $value
  3133. * (optional) Value of the field to assert. You may pass in NULL (default)
  3134. * to skip checking the actual value, while still checking that the field
  3135. * exists.
  3136. * @param $message
  3137. * Message to display.
  3138. * @param $group
  3139. * The group this message belongs to.
  3140. * @return
  3141. * TRUE on pass, FALSE on fail.
  3142. */
  3143. protected function assertFieldByName($name, $value = NULL, $message = NULL) {
  3144. if (!isset($message)) {
  3145. if (!isset($value)) {
  3146. $message = t('Found field with name @name', array(
  3147. '@name' => var_export($name, TRUE),
  3148. ));
  3149. }
  3150. else {
  3151. $message = t('Found field with name @name and value @value', array(
  3152. '@name' => var_export($name, TRUE),
  3153. '@value' => var_export($value, TRUE),
  3154. ));
  3155. }
  3156. }
  3157. return $this->assertFieldByXPath($this->constructFieldXpath('name', $name), $value, $message, t('Browser'));
  3158. }
  3159. /**
  3160. * Asserts that a field does not exist with the given name and value.
  3161. *
  3162. * @param $name
  3163. * Name of field to assert.
  3164. * @param $value
  3165. * (optional) Value for the field, to assert that the field's value on the
  3166. * page doesn't match it. You may pass in NULL to skip checking the
  3167. * value, while still checking that the field doesn't exist. However, the
  3168. * default value ('') asserts that the field value is not an empty string.
  3169. * @param $message
  3170. * (optional) Message to display.
  3171. * @param $group
  3172. * The group this message belongs to.
  3173. * @return
  3174. * TRUE on pass, FALSE on fail.
  3175. */
  3176. protected function assertNoFieldByName($name, $value = '', $message = '') {
  3177. return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $name), $value, $message ? $message : t('Did not find field by name @name', array('@name' => $name)), t('Browser'));
  3178. }
  3179. /**
  3180. * Asserts that a field exists in the current page with the given ID and value.
  3181. *
  3182. * @param $id
  3183. * ID of field to assert.
  3184. * @param $value
  3185. * (optional) Value for the field to assert. You may pass in NULL to skip
  3186. * checking the value, while still checking that the field exists.
  3187. * However, the default value ('') asserts that the field value is an empty
  3188. * string.
  3189. * @param $message
  3190. * (optional) Message to display.
  3191. * @param $group
  3192. * The group this message belongs to.
  3193. * @return
  3194. * TRUE on pass, FALSE on fail.
  3195. */
  3196. protected function assertFieldById($id, $value = '', $message = '') {
  3197. return $this->assertFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Found field by id @id', array('@id' => $id)), t('Browser'));
  3198. }
  3199. /**
  3200. * Asserts that a field does not exist with the given ID and value.
  3201. *
  3202. * @param $id
  3203. * ID of field to assert.
  3204. * @param $value
  3205. * (optional) Value for the field, to assert that the field's value on the
  3206. * page doesn't match it. You may pass in NULL to skip checking the value,
  3207. * while still checking that the field doesn't exist. However, the default
  3208. * value ('') asserts that the field value is not an empty string.
  3209. * @param $message
  3210. * (optional) Message to display.
  3211. * @param $group
  3212. * The group this message belongs to.
  3213. * @return
  3214. * TRUE on pass, FALSE on fail.
  3215. */
  3216. protected function assertNoFieldById($id, $value = '', $message = '') {
  3217. return $this->assertNoFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Did not find field by id @id', array('@id' => $id)), t('Browser'));
  3218. }
  3219. /**
  3220. * Asserts that a checkbox field in the current page is checked.
  3221. *
  3222. * @param $id
  3223. * ID of field to assert.
  3224. * @param $message
  3225. * (optional) Message to display.
  3226. * @return
  3227. * TRUE on pass, FALSE on fail.
  3228. */
  3229. protected function assertFieldChecked($id, $message = '') {
  3230. $elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
  3231. return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is checked.', array('@id' => $id)), t('Browser'));
  3232. }
  3233. /**
  3234. * Asserts that a checkbox field in the current page is not checked.
  3235. *
  3236. * @param $id
  3237. * ID of field to assert.
  3238. * @param $message
  3239. * (optional) Message to display.
  3240. * @return
  3241. * TRUE on pass, FALSE on fail.
  3242. */
  3243. protected function assertNoFieldChecked($id, $message = '') {
  3244. $elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
  3245. return $this->assertTrue(isset($elements[0]) && empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is not checked.', array('@id' => $id)), t('Browser'));
  3246. }
  3247. /**
  3248. * Asserts that a select option in the current page is checked.
  3249. *
  3250. * @param $id
  3251. * ID of select field to assert.
  3252. * @param $option
  3253. * Option to assert.
  3254. * @param $message
  3255. * (optional) Message to display.
  3256. * @return
  3257. * TRUE on pass, FALSE on fail.
  3258. *
  3259. * @todo $id is unusable. Replace with $name.
  3260. */
  3261. protected function assertOptionSelected($id, $option, $message = '') {
  3262. $elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
  3263. 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'));
  3264. }
  3265. /**
  3266. * Asserts that a select option in the current page is not checked.
  3267. *
  3268. * @param $id
  3269. * ID of select field to assert.
  3270. * @param $option
  3271. * Option to assert.
  3272. * @param $message
  3273. * (optional) Message to display.
  3274. * @return
  3275. * TRUE on pass, FALSE on fail.
  3276. */
  3277. protected function assertNoOptionSelected($id, $option, $message = '') {
  3278. $elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
  3279. 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'));
  3280. }
  3281. /**
  3282. * Asserts that a field exists with the given name or ID.
  3283. *
  3284. * @param $field
  3285. * Name or ID of field to assert.
  3286. * @param $message
  3287. * (optional) Message to display.
  3288. * @param $group
  3289. * The group this message belongs to.
  3290. * @return
  3291. * TRUE on pass, FALSE on fail.
  3292. */
  3293. protected function assertField($field, $message = '', $group = 'Other') {
  3294. return $this->assertFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
  3295. }
  3296. /**
  3297. * Asserts that a field does not exist with the given name or ID.
  3298. *
  3299. * @param $field
  3300. * Name or ID of field to assert.
  3301. * @param $message
  3302. * (optional) Message to display.
  3303. * @param $group
  3304. * The group this message belongs to.
  3305. * @return
  3306. * TRUE on pass, FALSE on fail.
  3307. */
  3308. protected function assertNoField($field, $message = '', $group = 'Other') {
  3309. return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
  3310. }
  3311. /**
  3312. * Asserts that each HTML ID is used for just a single element.
  3313. *
  3314. * @param $message
  3315. * Message to display.
  3316. * @param $group
  3317. * The group this message belongs to.
  3318. * @param $ids_to_skip
  3319. * An optional array of ids to skip when checking for duplicates. It is
  3320. * always a bug to have duplicate HTML IDs, so this parameter is to enable
  3321. * incremental fixing of core code. Whenever a test passes this parameter,
  3322. * it should add a "todo" comment above the call to this function explaining
  3323. * the legacy bug that the test wishes to ignore and including a link to an
  3324. * issue that is working to fix that legacy bug.
  3325. * @return
  3326. * TRUE on pass, FALSE on fail.
  3327. */
  3328. protected function assertNoDuplicateIds($message = '', $group = 'Other', $ids_to_skip = array()) {
  3329. $status = TRUE;
  3330. foreach ($this->xpath('//*[@id]') as $element) {
  3331. $id = (string) $element['id'];
  3332. if (isset($seen_ids[$id]) && !in_array($id, $ids_to_skip)) {
  3333. $this->fail(t('The HTML ID %id is unique.', array('%id' => $id)), $group);
  3334. $status = FALSE;
  3335. }
  3336. $seen_ids[$id] = TRUE;
  3337. }
  3338. return $this->assert($status, $message, $group);
  3339. }
  3340. /**
  3341. * Helper function: construct an XPath for the given set of attributes and value.
  3342. *
  3343. * @param $attribute
  3344. * Field attributes.
  3345. * @param $value
  3346. * Value of field.
  3347. * @return
  3348. * XPath for specified values.
  3349. */
  3350. protected function constructFieldXpath($attribute, $value) {
  3351. $xpath = '//textarea[@' . $attribute . '=:value]|//input[@' . $attribute . '=:value]|//select[@' . $attribute . '=:value]';
  3352. return $this->buildXPathQuery($xpath, array(':value' => $value));
  3353. }
  3354. /**
  3355. * Asserts the page responds with the specified response code.
  3356. *
  3357. * @param $code
  3358. * Response code. For example 200 is a successful page request. For a list
  3359. * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
  3360. * @param $message
  3361. * Message to display.
  3362. * @return
  3363. * Assertion result.
  3364. */
  3365. protected function assertResponse($code, $message = '') {
  3366. $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  3367. $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
  3368. return $this->assertTrue($match, $message ? $message : t('HTTP response expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
  3369. }
  3370. /**
  3371. * Asserts the page did not return the specified response code.
  3372. *
  3373. * @param $code
  3374. * Response code. For example 200 is a successful page request. For a list
  3375. * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
  3376. * @param $message
  3377. * Message to display.
  3378. *
  3379. * @return
  3380. * Assertion result.
  3381. */
  3382. protected function assertNoResponse($code, $message = '') {
  3383. $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  3384. $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
  3385. return $this->assertFalse($match, $message ? $message : t('HTTP response not expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
  3386. }
  3387. /**
  3388. * Asserts that the most recently sent e-mail message has the given value.
  3389. *
  3390. * The field in $name must have the content described in $value.
  3391. *
  3392. * @param $name
  3393. * Name of field or message property to assert. Examples: subject, body, id, ...
  3394. * @param $value
  3395. * Value of the field to assert.
  3396. * @param $message
  3397. * Message to display.
  3398. *
  3399. * @return
  3400. * TRUE on pass, FALSE on fail.
  3401. */
  3402. protected function assertMail($name, $value = '', $message = '') {
  3403. $captured_emails = variable_get('drupal_test_email_collector', array());
  3404. $email = end($captured_emails);
  3405. return $this->assertTrue($email && isset($email[$name]) && $email[$name] == $value, $message, t('E-mail'));
  3406. }
  3407. /**
  3408. * Asserts that the most recently sent e-mail message has the string in it.
  3409. *
  3410. * @param $field_name
  3411. * Name of field or message property to assert: subject, body, id, ...
  3412. * @param $string
  3413. * String to search for.
  3414. * @param $email_depth
  3415. * Number of emails to search for string, starting with most recent.
  3416. *
  3417. * @return
  3418. * TRUE on pass, FALSE on fail.
  3419. */
  3420. protected function assertMailString($field_name, $string, $email_depth) {
  3421. $mails = $this->drupalGetMails();
  3422. $string_found = FALSE;
  3423. for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $email_depth && $i >= 0; $i--) {
  3424. $mail = $mails[$i];
  3425. // Normalize whitespace, as we don't know what the mail system might have
  3426. // done. Any run of whitespace becomes a single space.
  3427. $normalized_mail = preg_replace('/\s+/', ' ', $mail[$field_name]);
  3428. $normalized_string = preg_replace('/\s+/', ' ', $string);
  3429. $string_found = (FALSE !== strpos($normalized_mail, $normalized_string));
  3430. if ($string_found) {
  3431. break;
  3432. }
  3433. }
  3434. return $this->assertTrue($string_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $string)));
  3435. }
  3436. /**
  3437. * Asserts that the most recently sent e-mail message has the pattern in it.
  3438. *
  3439. * @param $field_name
  3440. * Name of field or message property to assert: subject, body, id, ...
  3441. * @param $regex
  3442. * Pattern to search for.
  3443. *
  3444. * @return
  3445. * TRUE on pass, FALSE on fail.
  3446. */
  3447. protected function assertMailPattern($field_name, $regex, $message) {
  3448. $mails = $this->drupalGetMails();
  3449. $mail = end($mails);
  3450. $regex_found = preg_match("/$regex/", $mail[$field_name]);
  3451. return $this->assertTrue($regex_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $regex)));
  3452. }
  3453. /**
  3454. * Outputs to verbose the most recent $count emails sent.
  3455. *
  3456. * @param $count
  3457. * Optional number of emails to output.
  3458. */
  3459. protected function verboseEmail($count = 1) {
  3460. $mails = $this->drupalGetMails();
  3461. for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $count && $i >= 0; $i--) {
  3462. $mail = $mails[$i];
  3463. $this->verbose(t('Email:') . '<pre>' . print_r($mail, TRUE) . '</pre>');
  3464. }
  3465. }
  3466. }
  3467. /**
  3468. * Logs verbose message in a text file.
  3469. *
  3470. * If verbose mode is enabled then page requests will be dumped to a file and
  3471. * presented on the test result screen. The messages will be placed in a file
  3472. * located in the simpletest directory in the original file system.
  3473. *
  3474. * @param $message
  3475. * The verbose message to be stored.
  3476. * @param $original_file_directory
  3477. * The original file directory, before it was changed for testing purposes.
  3478. * @param $test_class
  3479. * The active test case class.
  3480. *
  3481. * @return
  3482. * The ID of the message to be placed in related assertion messages.
  3483. *
  3484. * @see DrupalTestCase->originalFileDirectory
  3485. * @see DrupalWebTestCase->verbose()
  3486. */
  3487. function simpletest_verbose($message, $original_file_directory = NULL, $test_class = NULL) {
  3488. static $file_directory = NULL, $class = NULL, $id = 1, $verbose = NULL;
  3489. // Will pass first time during setup phase, and when verbose is TRUE.
  3490. if (!isset($original_file_directory) && !$verbose) {
  3491. return FALSE;
  3492. }
  3493. if ($message && $file_directory) {
  3494. $message = '<hr />ID #' . $id . ' (<a href="' . $class . '-' . ($id - 1) . '.html">Previous</a> | <a href="' . $class . '-' . ($id + 1) . '.html">Next</a>)<hr />' . $message;
  3495. file_put_contents($file_directory . "/simpletest/verbose/$class-$id.html", $message, FILE_APPEND);
  3496. return $id++;
  3497. }
  3498. if ($original_file_directory) {
  3499. $file_directory = $original_file_directory;
  3500. $class = $test_class;
  3501. $verbose = variable_get('simpletest_verbose', TRUE);
  3502. $directory = $file_directory . '/simpletest/verbose';
  3503. $writable = file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
  3504. if ($writable && !file_exists($directory . '/.htaccess')) {
  3505. file_put_contents($directory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
  3506. }
  3507. return $writable;
  3508. }
  3509. return FALSE;
  3510. }