drupal_web_test_case.php 128 KB

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