common.test 145 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431
  1. <?php
  2. /**
  3. * @file
  4. * Tests for common.inc functionality.
  5. */
  6. /**
  7. * Tests for URL generation functions.
  8. */
  9. class DrupalAlterTestCase extends DrupalWebTestCase {
  10. public static function getInfo() {
  11. return array(
  12. 'name' => 'drupal_alter() tests',
  13. 'description' => 'Confirm that alteration of arguments passed to drupal_alter() works correctly.',
  14. 'group' => 'System',
  15. );
  16. }
  17. function setUp() {
  18. parent::setUp('common_test');
  19. }
  20. function testDrupalAlter() {
  21. // This test depends on Bartik, so make sure that it is always the current
  22. // active theme.
  23. global $theme, $base_theme_info;
  24. $theme = 'bartik';
  25. $base_theme_info = array();
  26. $array = array('foo' => 'bar');
  27. $entity = new stdClass();
  28. $entity->foo = 'bar';
  29. // Verify alteration of a single argument.
  30. $array_copy = $array;
  31. $array_expected = array('foo' => 'Drupal theme');
  32. drupal_alter('drupal_alter', $array_copy);
  33. $this->assertEqual($array_copy, $array_expected, 'Single array was altered.');
  34. $entity_copy = clone $entity;
  35. $entity_expected = clone $entity;
  36. $entity_expected->foo = 'Drupal theme';
  37. drupal_alter('drupal_alter', $entity_copy);
  38. $this->assertEqual($entity_copy, $entity_expected, 'Single object was altered.');
  39. // Verify alteration of multiple arguments.
  40. $array_copy = $array;
  41. $array_expected = array('foo' => 'Drupal theme');
  42. $entity_copy = clone $entity;
  43. $entity_expected = clone $entity;
  44. $entity_expected->foo = 'Drupal theme';
  45. $array2_copy = $array;
  46. $array2_expected = array('foo' => 'Drupal theme');
  47. drupal_alter('drupal_alter', $array_copy, $entity_copy, $array2_copy);
  48. $this->assertEqual($array_copy, $array_expected, 'First argument to drupal_alter() was altered.');
  49. $this->assertEqual($entity_copy, $entity_expected, 'Second argument to drupal_alter() was altered.');
  50. $this->assertEqual($array2_copy, $array2_expected, 'Third argument to drupal_alter() was altered.');
  51. // Verify alteration order when passing an array of types to drupal_alter().
  52. // common_test_module_implements_alter() places 'block' implementation after
  53. // other modules.
  54. $array_copy = $array;
  55. $array_expected = array('foo' => 'Drupal block theme');
  56. drupal_alter(array('drupal_alter', 'drupal_alter_foo'), $array_copy);
  57. $this->assertEqual($array_copy, $array_expected, 'hook_TYPE_alter() implementations ran in correct order.');
  58. }
  59. }
  60. /**
  61. * Tests for URL generation functions.
  62. *
  63. * url() calls module_implements(), which may issue a db query, which requires
  64. * inheriting from a web test case rather than a unit test case.
  65. */
  66. class CommonURLUnitTest extends DrupalWebTestCase {
  67. public static function getInfo() {
  68. return array(
  69. 'name' => 'URL generation unit tests',
  70. 'description' => 'Confirm that url(), drupal_get_query_parameters(), drupal_http_build_query(), and l() work correctly with various input.',
  71. 'group' => 'System',
  72. );
  73. }
  74. /**
  75. * Confirm that invalid text given as $path is filtered.
  76. */
  77. function testLXSS() {
  78. $text = $this->randomName();
  79. $path = "<SCRIPT>alert('XSS')</SCRIPT>";
  80. $link = l($text, $path);
  81. $sanitized_path = check_url(url($path));
  82. $this->assertTrue(strpos($link, $sanitized_path) !== FALSE, format_string('XSS attack @path was filtered', array('@path' => $path)));
  83. // Verify that a dangerous protocol is sanitized.
  84. $text = $this->randomName();
  85. $path = "javascript:alert('XSS')";
  86. $link = l($text, $path, array('external' => TRUE));
  87. $this->assertTrue(strpos($link, 'javascript:') === FALSE, 'Dangerous protocol javascript: was sanitized.');
  88. // Verify that these harmless javascript paths are left intact for BC.
  89. $special_case_js_paths = array(
  90. 'javascript:void()',
  91. 'javascript:void();',
  92. 'javascript:void(0)',
  93. 'javascript:void(0);',
  94. 'JavaScript:Void(0)'
  95. );
  96. foreach ($special_case_js_paths as $path) {
  97. $text = $this->randomName();
  98. $link = l($text, $path, array('external' => TRUE));
  99. $this->assertTrue(strpos($link, $path) !== FALSE, format_string('Harmless @path was not sanitized.', array('@path' => $path)));
  100. }
  101. }
  102. /*
  103. * Tests for active class in l() function.
  104. */
  105. function testLActiveClass() {
  106. $link = l($this->randomName(), $_GET['q']);
  107. $this->assertTrue($this->hasClass($link, 'active'), format_string('Class @class is present on link to the current page', array('@class' => 'active')));
  108. }
  109. /**
  110. * Tests for custom class in l() function.
  111. */
  112. function testLCustomClass() {
  113. $class = $this->randomName();
  114. $link = l($this->randomName(), $_GET['q'], array('attributes' => array('class' => array($class))));
  115. $this->assertTrue($this->hasClass($link, $class), format_string('Custom class @class is present on link when requested', array('@class' => $class)));
  116. $this->assertTrue($this->hasClass($link, 'active'), format_string('Class @class is present on link to the current page', array('@class' => 'active')));
  117. }
  118. private function hasClass($link, $class) {
  119. return preg_match('|class="([^\"\s]+\s+)*' . $class . '|', $link);
  120. }
  121. /**
  122. * Test drupal_get_query_parameters().
  123. */
  124. function testDrupalGetQueryParameters() {
  125. $original = array(
  126. 'a' => 1,
  127. 'b' => array(
  128. 'd' => 4,
  129. 'e' => array(
  130. 'f' => 5,
  131. ),
  132. ),
  133. 'c' => 3,
  134. 'q' => 'foo/bar',
  135. );
  136. // Default arguments.
  137. $result = $_GET;
  138. unset($result['q']);
  139. $this->assertEqual(drupal_get_query_parameters(), $result, "\$_GET['q'] was removed.");
  140. // Default exclusion.
  141. $result = $original;
  142. unset($result['q']);
  143. $this->assertEqual(drupal_get_query_parameters($original), $result, "'q' was removed.");
  144. // First-level exclusion.
  145. $result = $original;
  146. unset($result['b']);
  147. $this->assertEqual(drupal_get_query_parameters($original, array('b')), $result, "'b' was removed.");
  148. // Second-level exclusion.
  149. $result = $original;
  150. unset($result['b']['d']);
  151. $this->assertEqual(drupal_get_query_parameters($original, array('b[d]')), $result, "'b[d]' was removed.");
  152. // Third-level exclusion.
  153. $result = $original;
  154. unset($result['b']['e']['f']);
  155. $this->assertEqual(drupal_get_query_parameters($original, array('b[e][f]')), $result, "'b[e][f]' was removed.");
  156. // Multiple exclusions.
  157. $result = $original;
  158. unset($result['a'], $result['b']['e'], $result['c']);
  159. $this->assertEqual(drupal_get_query_parameters($original, array('a', 'b[e]', 'c')), $result, "'a', 'b[e]', 'c' were removed.");
  160. }
  161. /**
  162. * Test drupal_http_build_query().
  163. */
  164. function testDrupalHttpBuildQuery() {
  165. $this->assertEqual(drupal_http_build_query(array('a' => ' &#//+%20@۞')), 'a=%20%26%23//%2B%2520%40%DB%9E', 'Value was properly encoded.');
  166. $this->assertEqual(drupal_http_build_query(array(' &#//+%20@۞' => 'a')), '%20%26%23%2F%2F%2B%2520%40%DB%9E=a', 'Key was properly encoded.');
  167. $this->assertEqual(drupal_http_build_query(array('a' => '1', 'b' => '2', 'c' => '3')), 'a=1&b=2&c=3', 'Multiple values were properly concatenated.');
  168. $this->assertEqual(drupal_http_build_query(array('a' => array('b' => '2', 'c' => '3'), 'd' => 'foo')), 'a%5Bb%5D=2&a%5Bc%5D=3&d=foo', 'Nested array was properly encoded.');
  169. }
  170. /**
  171. * Test drupal_parse_url().
  172. */
  173. function testDrupalParseUrl() {
  174. // Relative URL.
  175. $url = 'foo/bar?foo=bar&bar=baz&baz#foo';
  176. $result = array(
  177. 'path' => 'foo/bar',
  178. 'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
  179. 'fragment' => 'foo',
  180. );
  181. $this->assertEqual(drupal_parse_url($url), $result, 'Relative URL parsed correctly.');
  182. // Relative URL that is known to confuse parse_url().
  183. $url = 'foo/bar:1';
  184. $result = array(
  185. 'path' => 'foo/bar:1',
  186. 'query' => array(),
  187. 'fragment' => '',
  188. );
  189. $this->assertEqual(drupal_parse_url($url), $result, 'Relative URL parsed correctly.');
  190. // Absolute URL.
  191. $url = '/foo/bar?foo=bar&bar=baz&baz#foo';
  192. $result = array(
  193. 'path' => '/foo/bar',
  194. 'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
  195. 'fragment' => 'foo',
  196. );
  197. $this->assertEqual(drupal_parse_url($url), $result, 'Absolute URL parsed correctly.');
  198. // External URL testing.
  199. $url = 'http://drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
  200. // Test that drupal can recognize an absolute URL. Used to prevent attack vectors.
  201. $this->assertTrue(url_is_external($url), 'Correctly identified an external URL.');
  202. // External URL without an explicit protocol.
  203. $url = '//drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
  204. $this->assertTrue(url_is_external($url), 'Correctly identified an external URL without a protocol part.');
  205. // Internal URL starting with a slash.
  206. $url = '/drupal.org';
  207. $this->assertFalse(url_is_external($url), 'Correctly identified an internal URL with a leading slash.');
  208. // Test the parsing of absolute URLs.
  209. $url = 'http://drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
  210. $result = array(
  211. 'path' => 'http://drupal.org/foo/bar',
  212. 'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
  213. 'fragment' => 'foo',
  214. );
  215. $this->assertEqual(drupal_parse_url($url), $result, 'External URL parsed correctly.');
  216. // Verify proper parsing of URLs when clean URLs are disabled.
  217. $result = array(
  218. 'path' => 'foo/bar',
  219. 'query' => array('bar' => 'baz'),
  220. 'fragment' => 'foo',
  221. );
  222. // Non-clean URLs #1: Absolute URL generated by url().
  223. $url = $GLOBALS['base_url'] . '/?q=foo/bar&bar=baz#foo';
  224. $this->assertEqual(drupal_parse_url($url), $result, 'Absolute URL with clean URLs disabled parsed correctly.');
  225. // Non-clean URLs #2: Relative URL generated by url().
  226. $url = '?q=foo/bar&bar=baz#foo';
  227. $this->assertEqual(drupal_parse_url($url), $result, 'Relative URL with clean URLs disabled parsed correctly.');
  228. // Non-clean URLs #3: URL generated by url() on non-Apache webserver.
  229. $url = 'index.php?q=foo/bar&bar=baz#foo';
  230. $this->assertEqual(drupal_parse_url($url), $result, 'Relative URL on non-Apache webserver with clean URLs disabled parsed correctly.');
  231. // Test that drupal_parse_url() does not allow spoofing a URL to force a malicious redirect.
  232. $parts = drupal_parse_url('forged:http://cwe.mitre.org/data/definitions/601.html');
  233. $this->assertFalse(valid_url($parts['path'], TRUE), 'drupal_parse_url() correctly parsed a forged URL.');
  234. }
  235. /**
  236. * Test url() with/without query, with/without fragment, absolute on/off and
  237. * assert all that works when clean URLs are on and off.
  238. */
  239. function testUrl() {
  240. global $base_url;
  241. foreach (array(FALSE, TRUE) as $absolute) {
  242. // Get the expected start of the path string.
  243. $base = $absolute ? $base_url . '/' : base_path();
  244. $absolute_string = $absolute ? 'absolute' : NULL;
  245. // Disable Clean URLs.
  246. $GLOBALS['conf']['clean_url'] = 0;
  247. $url = $base . '?q=node/123';
  248. $result = url('node/123', array('absolute' => $absolute));
  249. $this->assertEqual($url, $result, "$url == $result");
  250. $url = $base . '?q=node/123#foo';
  251. $result = url('node/123', array('fragment' => 'foo', 'absolute' => $absolute));
  252. $this->assertEqual($url, $result, "$url == $result");
  253. $url = $base . '?q=node/123&foo';
  254. $result = url('node/123', array('query' => array('foo' => NULL), 'absolute' => $absolute));
  255. $this->assertEqual($url, $result, "$url == $result");
  256. $url = $base . '?q=node/123&foo=bar&bar=baz';
  257. $result = url('node/123', array('query' => array('foo' => 'bar', 'bar' => 'baz'), 'absolute' => $absolute));
  258. $this->assertEqual($url, $result, "$url == $result");
  259. $url = $base . '?q=node/123&foo#bar';
  260. $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => 'bar', 'absolute' => $absolute));
  261. $this->assertEqual($url, $result, "$url == $result");
  262. $url = $base . '?q=node/123&foo#0';
  263. $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => '0', 'absolute' => $absolute));
  264. $this->assertEqual($url, $result, "$url == $result");
  265. $url = $base . '?q=node/123&foo';
  266. $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => '', 'absolute' => $absolute));
  267. $this->assertEqual($url, $result, "$url == $result");
  268. $url = $base;
  269. $result = url('<front>', array('absolute' => $absolute));
  270. $this->assertEqual($url, $result, "$url == $result");
  271. // Enable Clean URLs.
  272. $GLOBALS['conf']['clean_url'] = 1;
  273. $url = $base . 'node/123';
  274. $result = url('node/123', array('absolute' => $absolute));
  275. $this->assertEqual($url, $result, "$url == $result");
  276. $url = $base . 'node/123#foo';
  277. $result = url('node/123', array('fragment' => 'foo', 'absolute' => $absolute));
  278. $this->assertEqual($url, $result, "$url == $result");
  279. $url = $base . 'node/123?foo';
  280. $result = url('node/123', array('query' => array('foo' => NULL), 'absolute' => $absolute));
  281. $this->assertEqual($url, $result, "$url == $result");
  282. $url = $base . 'node/123?foo=bar&bar=baz';
  283. $result = url('node/123', array('query' => array('foo' => 'bar', 'bar' => 'baz'), 'absolute' => $absolute));
  284. $this->assertEqual($url, $result, "$url == $result");
  285. $url = $base . 'node/123?foo#bar';
  286. $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => 'bar', 'absolute' => $absolute));
  287. $this->assertEqual($url, $result, "$url == $result");
  288. $url = $base;
  289. $result = url('<front>', array('absolute' => $absolute));
  290. $this->assertEqual($url, $result, "$url == $result");
  291. }
  292. }
  293. /**
  294. * Test external URL handling.
  295. */
  296. function testExternalUrls() {
  297. $test_url = 'http://drupal.org/';
  298. // Verify external URL can contain a fragment.
  299. $url = $test_url . '#drupal';
  300. $result = url($url);
  301. $this->assertEqual($url, $result, 'External URL with fragment works without a fragment in $options.');
  302. // Verify fragment can be overidden in an external URL.
  303. $url = $test_url . '#drupal';
  304. $fragment = $this->randomName(10);
  305. $result = url($url, array('fragment' => $fragment));
  306. $this->assertEqual($test_url . '#' . $fragment, $result, 'External URL fragment is overidden with a custom fragment in $options.');
  307. // Verify external URL can contain a query string.
  308. $url = $test_url . '?drupal=awesome';
  309. $result = url($url);
  310. $this->assertEqual($url, $result, 'External URL with query string works without a query string in $options.');
  311. // Verify external URL can be extended with a query string.
  312. $url = $test_url;
  313. $query = array($this->randomName(5) => $this->randomName(5));
  314. $result = url($url, array('query' => $query));
  315. $this->assertEqual($url . '?' . http_build_query($query, '', '&'), $result, 'External URL can be extended with a query string in $options.');
  316. // Verify query string can be extended in an external URL.
  317. $url = $test_url . '?drupal=awesome';
  318. $query = array($this->randomName(5) => $this->randomName(5));
  319. $result = url($url, array('query' => $query));
  320. $this->assertEqual($url . '&' . http_build_query($query, '', '&'), $result, 'External URL query string can be extended with a custom query string in $options.');
  321. // Verify that an internal URL does not result in an external URL without
  322. // protocol part.
  323. $url = '/drupal.org';
  324. $result = url($url);
  325. $this->assertTrue(strpos($result, '//') === FALSE, 'Internal URL does not turn into an external URL.');
  326. // Verify that an external URL without protocol part is recognized as such.
  327. $url = '//drupal.org';
  328. $result = url($url);
  329. $this->assertEqual($url, $result, 'External URL without protocol is not altered.');
  330. }
  331. }
  332. /**
  333. * Web tests for URL generation functions.
  334. */
  335. class CommonURLWebTest extends DrupalWebTestCase {
  336. public static function getInfo() {
  337. return array(
  338. 'name' => 'URL generation web tests',
  339. 'description' => 'Confirm that URL-generating functions work correctly on specific site paths.',
  340. 'group' => 'System',
  341. );
  342. }
  343. function setUp() {
  344. parent::setUp('common_test');
  345. }
  346. /**
  347. * Tests the url() function on internal paths which mimic external URLs.
  348. */
  349. function testInternalPathMimicsExternal() {
  350. // Ensure that calling url(current_path()) on "/http://example.com" (an
  351. // internal path which mimics an external URL) always links to the internal
  352. // path, not the external URL. This helps protect against external URL link
  353. // injection vulnerabilities.
  354. variable_set('common_test_link_to_current_path', TRUE);
  355. $this->drupalGet('/http://example.com');
  356. $this->clickLink('link which should point to the current path');
  357. $this->assertUrl('/http://example.com');
  358. $this->assertText('link which should point to the current path');
  359. }
  360. }
  361. /**
  362. * Tests url_is_external().
  363. */
  364. class UrlIsExternalUnitTest extends DrupalUnitTestCase {
  365. public static function getInfo() {
  366. return array(
  367. 'name' => 'External URL checking',
  368. 'description' => 'Performs tests on url_is_external().',
  369. 'group' => 'System',
  370. );
  371. }
  372. /**
  373. * Tests if each URL is external or not.
  374. */
  375. function testUrlIsExternal() {
  376. foreach ($this->examples() as $path => $expected) {
  377. $this->assertIdentical(url_is_external($path), $expected, $path);
  378. }
  379. }
  380. /**
  381. * Provides data for testUrlIsExternal().
  382. *
  383. * @return array
  384. * An array of test data, keyed by a path, with the expected value where
  385. * TRUE is external, and FALSE is not external.
  386. */
  387. protected function examples() {
  388. return array(
  389. // Simple external URLs.
  390. 'http://example.com' => TRUE,
  391. 'https://example.com' => TRUE,
  392. 'http://drupal.org/foo/bar?foo=bar&bar=baz&baz#foo' => TRUE,
  393. '//drupal.org' => TRUE,
  394. // Some browsers ignore or strip leading control characters.
  395. "\x00//www.example.com" => TRUE,
  396. "\x08//www.example.com" => TRUE,
  397. "\x1F//www.example.com" => TRUE,
  398. "\n//www.example.com" => TRUE,
  399. // JSON supports decoding directly from UTF-8 code points.
  400. json_decode('"\u00AD"') . "//www.example.com" => TRUE,
  401. json_decode('"\u200E"') . "//www.example.com" => TRUE,
  402. json_decode('"\uE0020"') . "//www.example.com" => TRUE,
  403. json_decode('"\uE000"') . "//www.example.com" => TRUE,
  404. // Backslashes should be normalized to forward.
  405. '\\\\example.com' => TRUE,
  406. // Local URLs.
  407. 'node' => FALSE,
  408. '/system/ajax' => FALSE,
  409. '?q=foo:bar' => FALSE,
  410. 'node/edit:me' => FALSE,
  411. '/drupal.org' => FALSE,
  412. '<front>' => FALSE,
  413. );
  414. }
  415. }
  416. /**
  417. * Tests for check_plain(), filter_xss(), format_string(), and check_url().
  418. */
  419. class CommonXssUnitTest extends DrupalUnitTestCase {
  420. public static function getInfo() {
  421. return array(
  422. 'name' => 'String filtering tests',
  423. 'description' => 'Confirm that check_plain(), filter_xss(), format_string() and check_url() work correctly, including invalid multi-byte sequences.',
  424. 'group' => 'System',
  425. );
  426. }
  427. /**
  428. * Check that invalid multi-byte sequences are rejected.
  429. */
  430. function testInvalidMultiByte() {
  431. // Ignore PHP 8.0+ null deprecations.
  432. $text = check_plain(NULL);
  433. $this->assertEqual($text, '', 'check_plain() casts null to string');
  434. $text = check_plain(FALSE);
  435. $this->assertEqual($text, '', 'check_plain() casts boolean to string');
  436. $text = filter_xss(NULL);
  437. $this->assertEqual($text, '', 'filter_xss() casts null to string');
  438. $text = filter_xss(FALSE);
  439. $this->assertEqual($text, '', 'filter_xss() casts boolean to string');
  440. // Ignore PHP 5.3+ invalid multibyte sequence warning.
  441. $text = @check_plain("Foo\xC0barbaz");
  442. $this->assertEqual($text, '', 'check_plain() rejects invalid sequence "Foo\xC0barbaz"');
  443. // Ignore PHP 5.3+ invalid multibyte sequence warning.
  444. $text = @check_plain("\xc2\"");
  445. $this->assertEqual($text, '', 'check_plain() rejects invalid sequence "\xc2\""');
  446. $text = check_plain("Fooÿñ");
  447. $this->assertEqual($text, "Fooÿñ", 'check_plain() accepts valid sequence "Fooÿñ"');
  448. $text = filter_xss("Foo\xC0barbaz");
  449. $this->assertEqual($text, '', 'filter_xss() rejects invalid sequence "Foo\xC0barbaz"');
  450. $text = filter_xss("Fooÿñ");
  451. $this->assertEqual($text, "Fooÿñ", 'filter_xss() accepts valid sequence Fooÿñ');
  452. }
  453. /**
  454. * Check that special characters are escaped.
  455. */
  456. function testEscaping() {
  457. $text = check_plain("<script>");
  458. $this->assertEqual($text, '&lt;script&gt;', 'check_plain() escapes &lt;script&gt;');
  459. $text = check_plain('<>&"\'');
  460. $this->assertEqual($text, '&lt;&gt;&amp;&quot;&#039;', 'check_plain() escapes reserved HTML characters.');
  461. }
  462. /**
  463. * Test t() and format_string() replacement functionality.
  464. */
  465. function testFormatStringAndT() {
  466. foreach (array('format_string', 't') as $function) {
  467. $text = $function('Simple text');
  468. $this->assertEqual($text, 'Simple text', $function . ' leaves simple text alone.');
  469. $text = $function('Escaped text: @value', array('@value' => '<script>'));
  470. $this->assertEqual($text, 'Escaped text: &lt;script&gt;', $function . ' replaces and escapes string.');
  471. $text = $function('Placeholder text: %value', array('%value' => '<script>'));
  472. $this->assertEqual($text, 'Placeholder text: <em class="placeholder">&lt;script&gt;</em>', $function . ' replaces, escapes and themes string.');
  473. $text = $function('Verbatim text: !value', array('!value' => '<script>'));
  474. $this->assertEqual($text, 'Verbatim text: <script>', $function . ' replaces verbatim string as-is.');
  475. }
  476. }
  477. /**
  478. * Check that harmful protocols are stripped.
  479. */
  480. function testBadProtocolStripping() {
  481. // Ensure that check_url() strips out harmful protocols, and encodes for
  482. // HTML.
  483. $url = 'javascript:http://www.example.com/?x=1&y=2';
  484. $expected_html = 'http://www.example.com/?x=1&amp;y=2';
  485. $this->assertIdentical(check_url($url), $expected_html, 'check_url() filters a URL and encodes it for HTML.');
  486. // Ensure that drupal_strip_dangerous_protocols() can be used to return a
  487. // plain-text string stripped of harmful protocols.
  488. $data = array(
  489. 'javascript:http://www.example.com/?x=1&y=2' => 'http://www.example.com/?x=1&y=2',
  490. 'foo://disallowed.com' => '//disallowed.com',
  491. 'http://example.com' => 'http://example.com',
  492. 'https://example.com' => 'https://example.com',
  493. 'www.example.com' => 'www.example.com',
  494. 'mailto:person2@example.com' => 'mailto:person2@example.com',
  495. 'person2@example.com' => 'person2@example.com',
  496. 'ftp://example.com' => 'ftp://example.com',
  497. 'sftp://secure.host' => 'sftp://secure.host',
  498. 'ssh://odd.geek' => 'ssh://odd.geek',
  499. 'news://example.net' => 'news://example.net',
  500. 'telnet://example' => 'telnet://example',
  501. 'irc://example.host' => 'irc://example.host',
  502. 'webcal://calendar' => 'webcal://calendar',
  503. 'rtsp://127.0.0.1' => 'rtsp://127.0.0.1',
  504. 'tel:111111111' => 'tel:111111111',
  505. );
  506. foreach ($data as $url => $expected_plain) {
  507. $this->assertIdentical(drupal_strip_dangerous_protocols($url), $expected_plain, 'drupal_strip_dangerous_protocols() filters a URL and returns plain text.');
  508. }
  509. }
  510. }
  511. /**
  512. * Tests file size parsing and formatting functions.
  513. */
  514. class CommonSizeTestCase extends DrupalUnitTestCase {
  515. protected $exact_test_cases;
  516. protected $rounded_test_cases;
  517. public static function getInfo() {
  518. return array(
  519. 'name' => 'Size parsing test',
  520. 'description' => 'Parse a predefined amount of bytes and compare the output with the expected value.',
  521. 'group' => 'System'
  522. );
  523. }
  524. function setUp() {
  525. $kb = DRUPAL_KILOBYTE;
  526. $this->exact_test_cases = array(
  527. '1 byte' => 1,
  528. '1 KB' => $kb,
  529. '1 MB' => $kb * $kb,
  530. '1 GB' => $kb * $kb * $kb,
  531. '1 TB' => $kb * $kb * $kb * $kb,
  532. '1 PB' => $kb * $kb * $kb * $kb * $kb,
  533. '1 EB' => $kb * $kb * $kb * $kb * $kb * $kb,
  534. '1 ZB' => $kb * $kb * $kb * $kb * $kb * $kb * $kb,
  535. '1 YB' => $kb * $kb * $kb * $kb * $kb * $kb * $kb * $kb,
  536. );
  537. $this->rounded_test_cases = array(
  538. '2 bytes' => 2,
  539. '1 MB' => ($kb * $kb) - 1, // rounded to 1 MB (not 1000 or 1024 kilobyte!)
  540. round(3623651 / ($this->exact_test_cases['1 MB']), 2) . ' MB' => 3623651, // megabytes
  541. round(67234178751368124 / ($this->exact_test_cases['1 PB']), 2) . ' PB' => 67234178751368124, // petabytes
  542. round(235346823821125814962843827 / ($this->exact_test_cases['1 YB']), 2) . ' YB' => 235346823821125814962843827, // yottabytes
  543. );
  544. parent::setUp();
  545. }
  546. /**
  547. * Check that format_size() returns the expected string.
  548. */
  549. function testCommonFormatSize() {
  550. foreach (array($this->exact_test_cases, $this->rounded_test_cases) as $test_cases) {
  551. foreach ($test_cases as $expected => $input) {
  552. $this->assertEqual(
  553. ($result = format_size($input, NULL)),
  554. $expected,
  555. $expected . ' == ' . $result . ' (' . $input . ' bytes)'
  556. );
  557. }
  558. }
  559. }
  560. /**
  561. * Check that parse_size() returns the proper byte sizes.
  562. */
  563. function testCommonParseSize() {
  564. foreach ($this->exact_test_cases as $string => $size) {
  565. $this->assertEqual(
  566. $parsed_size = parse_size($string),
  567. $size,
  568. $size . ' == ' . $parsed_size . ' (' . $string . ')'
  569. );
  570. }
  571. // Some custom parsing tests
  572. $string = '23476892 bytes';
  573. $this->assertEqual(
  574. ($parsed_size = parse_size($string)),
  575. $size = 23476892,
  576. $string . ' == ' . $parsed_size . ' bytes'
  577. );
  578. $string = '76MRandomStringThatShouldBeIgnoredByParseSize.'; // 76 MB
  579. $this->assertEqual(
  580. $parsed_size = parse_size($string),
  581. $size = 79691776,
  582. $string . ' == ' . $parsed_size . ' bytes'
  583. );
  584. $string = '76.24 Giggabyte'; // Misspeld text -> 76.24 GB
  585. $this->assertEqual(
  586. $parsed_size = parse_size($string),
  587. $size = 81862076662,
  588. $string . ' == ' . $parsed_size . ' bytes'
  589. );
  590. }
  591. /**
  592. * Cross-test parse_size() and format_size().
  593. */
  594. function testCommonParseSizeFormatSize() {
  595. foreach ($this->exact_test_cases as $size) {
  596. $this->assertEqual(
  597. $size,
  598. ($parsed_size = parse_size($string = format_size($size, NULL))),
  599. $size . ' == ' . $parsed_size . ' (' . $string . ')'
  600. );
  601. }
  602. }
  603. }
  604. /**
  605. * Test drupal_explode_tags() and drupal_implode_tags().
  606. */
  607. class DrupalTagsHandlingTestCase extends DrupalUnitTestCase {
  608. var $validTags = array(
  609. 'Drupal' => 'Drupal',
  610. 'Drupal with some spaces' => 'Drupal with some spaces',
  611. '"Legendary Drupal mascot of doom: ""Druplicon"""' => 'Legendary Drupal mascot of doom: "Druplicon"',
  612. '"Drupal, although it rhymes with sloopal, is as awesome as a troopal!"' => 'Drupal, although it rhymes with sloopal, is as awesome as a troopal!',
  613. );
  614. public static function getInfo() {
  615. return array(
  616. 'name' => 'Drupal tags handling',
  617. 'description' => "Performs tests on Drupal's handling of tags, both explosion and implosion tactics used.",
  618. 'group' => 'System'
  619. );
  620. }
  621. /**
  622. * Explode a series of tags.
  623. */
  624. function testDrupalExplodeTags() {
  625. $string = implode(', ', array_keys($this->validTags));
  626. $tags = drupal_explode_tags($string);
  627. $this->assertTags($tags);
  628. }
  629. /**
  630. * Implode a series of tags.
  631. */
  632. function testDrupalImplodeTags() {
  633. $tags = array_values($this->validTags);
  634. // Let's explode and implode to our heart's content.
  635. for ($i = 0; $i < 10; $i++) {
  636. $string = drupal_implode_tags($tags);
  637. $tags = drupal_explode_tags($string);
  638. }
  639. $this->assertTags($tags);
  640. }
  641. /**
  642. * Helper function: asserts that the ending array of tags is what we wanted.
  643. */
  644. function assertTags($tags) {
  645. $original = $this->validTags;
  646. foreach ($tags as $tag) {
  647. $key = array_search($tag, $original);
  648. $this->assertTrue($key, format_string('Make sure tag %tag shows up in the final tags array (originally %original)', array('%tag' => $tag, '%original' => $key)));
  649. unset($original[$key]);
  650. }
  651. foreach ($original as $leftover) {
  652. $this->fail(format_string('Leftover tag %leftover was left over.', array('%leftover' => $leftover)));
  653. }
  654. }
  655. }
  656. /**
  657. * Test the Drupal CSS system.
  658. */
  659. class CascadingStylesheetsTestCase extends DrupalWebTestCase {
  660. public static function getInfo() {
  661. return array(
  662. 'name' => 'Cascading stylesheets',
  663. 'description' => 'Tests adding various cascading stylesheets to the page.',
  664. 'group' => 'System',
  665. );
  666. }
  667. function setUp() {
  668. parent::setUp('php', 'locale', 'common_test');
  669. // Reset drupal_add_css() before each test.
  670. drupal_static_reset('drupal_add_css');
  671. }
  672. /**
  673. * Check default stylesheets as empty.
  674. */
  675. function testDefault() {
  676. $this->assertEqual(array(), drupal_add_css(), 'Default CSS is empty.');
  677. }
  678. /**
  679. * Test that stylesheets in module .info files are loaded.
  680. */
  681. function testModuleInfo() {
  682. $this->drupalGet('');
  683. // Verify common_test.css in a STYLE media="all" tag.
  684. $elements = $this->xpath('//style[@media=:media and contains(text(), :filename)]', array(
  685. ':media' => 'all',
  686. ':filename' => 'tests/common_test.css',
  687. ));
  688. $this->assertTrue(count($elements), "Stylesheet with media 'all' in module .info file found.");
  689. // Verify common_test.print.css in a STYLE media="print" tag.
  690. $elements = $this->xpath('//style[@media=:media and contains(text(), :filename)]', array(
  691. ':media' => 'print',
  692. ':filename' => 'tests/common_test.print.css',
  693. ));
  694. $this->assertTrue(count($elements), "Stylesheet with media 'print' in module .info file found.");
  695. }
  696. /**
  697. * Tests adding a file stylesheet.
  698. */
  699. function testAddFile() {
  700. $path = drupal_get_path('module', 'simpletest') . '/simpletest.css';
  701. $css = drupal_add_css($path);
  702. $this->assertEqual($css[$path]['data'], $path, 'Adding a CSS file caches it properly.');
  703. }
  704. /**
  705. * Tests adding an external stylesheet.
  706. */
  707. function testAddExternal() {
  708. $path = 'http://example.com/style.css';
  709. $css = drupal_add_css($path, 'external');
  710. $this->assertEqual($css[$path]['type'], 'external', 'Adding an external CSS file caches it properly.');
  711. }
  712. /**
  713. * Makes sure that reseting the CSS empties the cache.
  714. */
  715. function testReset() {
  716. drupal_static_reset('drupal_add_css');
  717. $this->assertEqual(array(), drupal_add_css(), 'Resetting the CSS empties the cache.');
  718. }
  719. /**
  720. * Tests rendering the stylesheets.
  721. */
  722. function testRenderFile() {
  723. $css = drupal_get_path('module', 'simpletest') . '/simpletest.css';
  724. drupal_add_css($css);
  725. $styles = drupal_get_css();
  726. $this->assertTrue(strpos($styles, $css) > 0, 'Rendered CSS includes the added stylesheet.');
  727. // Verify that newlines are properly added inside style tags.
  728. $query_string = variable_get('css_js_query_string', '0');
  729. $css_processed = "<style type=\"text/css\" media=\"all\">\n@import url(\"" . check_plain(file_create_url($css)) . "?" . $query_string ."\");\n</style>";
  730. $this->assertEqual(trim($styles), $css_processed, 'Rendered CSS includes newlines inside style tags for JavaScript use.');
  731. }
  732. /**
  733. * Tests rendering an external stylesheet.
  734. */
  735. function testRenderExternal() {
  736. $css = 'http://example.com/style.css';
  737. drupal_add_css($css, 'external');
  738. $styles = drupal_get_css();
  739. // Stylesheet URL may be the href of a LINK tag or in an @import statement
  740. // of a STYLE tag.
  741. $this->assertTrue(strpos($styles, 'href="' . $css) > 0 || strpos($styles, '@import url("' . $css . '")') > 0, 'Rendering an external CSS file.');
  742. }
  743. /**
  744. * Tests rendering inline stylesheets with preprocessing on.
  745. */
  746. function testRenderInlinePreprocess() {
  747. $css = 'body { padding: 0px; }';
  748. $css_preprocessed = '<style type="text/css" media="all">' . "\n<!--/*--><![CDATA[/*><!--*/\n" . drupal_load_stylesheet_content($css, TRUE) . "\n/*]]>*/-->\n" . '</style>';
  749. drupal_add_css($css, array('type' => 'inline'));
  750. $styles = drupal_get_css();
  751. $this->assertEqual(trim($styles), $css_preprocessed, 'Rendering preprocessed inline CSS adds it to the page.');
  752. }
  753. /**
  754. * Tests removing charset when rendering stylesheets with preprocessing on.
  755. */
  756. function testRenderRemoveCharsetPreprocess() {
  757. $cases = array(
  758. array(
  759. 'asset' => '@charset "UTF-8";html{font-family:"sans-serif";}',
  760. 'expected' => 'html{font-family:"sans-serif";}',
  761. ),
  762. // This asset contains extra \n character.
  763. array(
  764. 'asset' => "@charset 'UTF-8';\nhtml{font-family:'sans-serif';}",
  765. 'expected' => "\nhtml{font-family:'sans-serif';}",
  766. ),
  767. );
  768. foreach ($cases as $case) {
  769. $this->assertEqual(
  770. $case['expected'],
  771. drupal_load_stylesheet_content($case['asset']),
  772. 'CSS optimizing correctly removes the charset declaration.'
  773. );
  774. }
  775. }
  776. /**
  777. * Tests rendering inline stylesheets with preprocessing off.
  778. */
  779. function testRenderInlineNoPreprocess() {
  780. $css = 'body { padding: 0px; }';
  781. drupal_add_css($css, array('type' => 'inline', 'preprocess' => FALSE));
  782. $styles = drupal_get_css();
  783. $this->assertTrue(strpos($styles, $css) > 0, 'Rendering non-preprocessed inline CSS adds it to the page.');
  784. }
  785. /**
  786. * Tests rendering inline stylesheets through a full page request.
  787. */
  788. function testRenderInlineFullPage() {
  789. $css = 'body { font-size: 254px; }';
  790. // Inline CSS is minified unless 'preprocess' => FALSE is passed as a
  791. // drupal_add_css() option.
  792. $expected = 'body{font-size:254px;}';
  793. // Create a node, using the PHP filter that tests drupal_add_css().
  794. $php_format_id = 'php_code';
  795. $settings = array(
  796. 'type' => 'page',
  797. 'body' => array(
  798. LANGUAGE_NONE => array(
  799. array(
  800. 'value' => t('This tests the inline CSS!') . "<?php drupal_add_css('$css', 'inline'); ?>",
  801. 'format' => $php_format_id,
  802. ),
  803. ),
  804. ),
  805. 'promote' => 1,
  806. );
  807. $node = $this->drupalCreateNode($settings);
  808. // Fetch the page.
  809. $this->drupalGet('node/' . $node->nid);
  810. $this->assertRaw($expected, 'Inline stylesheets appear in the full page rendering.');
  811. }
  812. /**
  813. * Test CSS ordering.
  814. */
  815. function testRenderOrder() {
  816. // A module CSS file.
  817. drupal_add_css(drupal_get_path('module', 'simpletest') . '/simpletest.css');
  818. // A few system CSS files, ordered in a strange way.
  819. $system_path = drupal_get_path('module', 'system');
  820. drupal_add_css($system_path . '/system.menus.css', array('group' => CSS_SYSTEM));
  821. drupal_add_css($system_path . '/system.base.css', array('group' => CSS_SYSTEM, 'weight' => -10));
  822. drupal_add_css($system_path . '/system.theme.css', array('group' => CSS_SYSTEM));
  823. $expected = array(
  824. $system_path . '/system.base.css',
  825. $system_path . '/system.menus.css',
  826. $system_path . '/system.theme.css',
  827. drupal_get_path('module', 'simpletest') . '/simpletest.css',
  828. );
  829. $styles = drupal_get_css();
  830. // Stylesheet URL may be the href of a LINK tag or in an @import statement
  831. // of a STYLE tag.
  832. if (preg_match_all('/(href="|url\(")' . preg_quote($GLOBALS['base_url'] . '/', '/') . '([^?]+)\?/', $styles, $matches)) {
  833. $result = $matches[2];
  834. }
  835. else {
  836. $result = array();
  837. }
  838. $this->assertIdentical($result, $expected, 'The CSS files are in the expected order.');
  839. }
  840. /**
  841. * Test CSS override.
  842. */
  843. function testRenderOverride() {
  844. $system = drupal_get_path('module', 'system');
  845. $simpletest = drupal_get_path('module', 'simpletest');
  846. drupal_add_css($system . '/system.base.css');
  847. drupal_add_css($simpletest . '/tests/system.base.css');
  848. // The dummy stylesheet should be the only one included.
  849. $styles = drupal_get_css();
  850. $this->assert(strpos($styles, $simpletest . '/tests/system.base.css') !== FALSE, 'The overriding CSS file is output.');
  851. $this->assert(strpos($styles, $system . '/system.base.css') === FALSE, 'The overridden CSS file is not output.');
  852. drupal_add_css($simpletest . '/tests/system.base.css');
  853. drupal_add_css($system . '/system.base.css');
  854. // The standard stylesheet should be the only one included.
  855. $styles = drupal_get_css();
  856. $this->assert(strpos($styles, $system . '/system.base.css') !== FALSE, 'The overriding CSS file is output.');
  857. $this->assert(strpos($styles, $simpletest . '/tests/system.base.css') === FALSE, 'The overridden CSS file is not output.');
  858. }
  859. /**
  860. * Tests Locale module's CSS Alter to include RTL overrides.
  861. */
  862. function testAlter() {
  863. // Switch the language to a right to left language and add system.base.css.
  864. global $language;
  865. $language->direction = LANGUAGE_RTL;
  866. $path = drupal_get_path('module', 'system');
  867. drupal_add_css($path . '/system.base.css');
  868. // Check to see if system.base-rtl.css was also added.
  869. $styles = drupal_get_css();
  870. $this->assert(strpos($styles, $path . '/system.base-rtl.css') !== FALSE, 'CSS is alterable as right to left overrides are added.');
  871. // Change the language back to left to right.
  872. $language->direction = LANGUAGE_LTR;
  873. }
  874. /**
  875. * Tests that the query string remains intact when adding CSS files that have
  876. * query string parameters.
  877. */
  878. function testAddCssFileWithQueryString() {
  879. $this->drupalGet('common-test/query-string');
  880. $query_string = variable_get('css_js_query_string', '0');
  881. $this->assertRaw(drupal_get_path('module', 'node') . '/node.css?' . $query_string, 'Query string was appended correctly to css.');
  882. $this->assertRaw(drupal_get_path('module', 'node') . '/node-fake.css?arg1=value1&amp;arg2=value2', 'Query string not escaped on a URI.');
  883. }
  884. }
  885. /**
  886. * Test for cleaning HTML identifiers.
  887. */
  888. class DrupalHTMLIdentifierTestCase extends DrupalUnitTestCase {
  889. public static function getInfo() {
  890. return array(
  891. 'name' => 'HTML identifiers',
  892. 'description' => 'Test the functions drupal_html_class(), drupal_html_id() and drupal_clean_css_identifier() for expected behavior',
  893. 'group' => 'System',
  894. );
  895. }
  896. /**
  897. * Tests that drupal_clean_css_identifier() cleans the identifier properly.
  898. */
  899. function testDrupalCleanCSSIdentifier() {
  900. // Verify that no valid ASCII characters are stripped from the identifier.
  901. $identifier = 'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789';
  902. $this->assertIdentical(drupal_clean_css_identifier($identifier, array()), $identifier, 'Verify valid ASCII characters pass through.');
  903. // Verify that valid UTF-8 characters are not stripped from the identifier.
  904. $identifier = '¡¢£¤¥';
  905. $this->assertIdentical(drupal_clean_css_identifier($identifier, array()), $identifier, 'Verify valid UTF-8 characters pass through.');
  906. // Verify that invalid characters (including non-breaking space) are stripped from the identifier.
  907. $this->assertIdentical(drupal_clean_css_identifier('invalid !"#$%&\'()*+,./:;<=>?@[\\]^`{|}~ identifier', array()), 'invalididentifier', 'Strip invalid characters.');
  908. // Verify that double underscores are replaced in the identifier by default.
  909. $identifier = 'css__identifier__with__double__underscores';
  910. $expected = 'css--identifier--with--double--underscores';
  911. $this->assertIdentical(drupal_clean_css_identifier($identifier), $expected, 'Verify double underscores are replaced with double hyphens by default.');
  912. // Verify that double underscores are preserved in the identifier if the
  913. // variable allow_css_double_underscores is set to TRUE.
  914. $this->setAllowCSSDoubleUnderscores(TRUE);
  915. $this->assertIdentical(drupal_clean_css_identifier($identifier), $identifier, 'Verify double underscores are preserved if the allow_css_double_underscores set to TRUE.');
  916. // To avoid affecting other test cases, set the variable
  917. // allow_css_double_underscores to FALSE which is the default value.
  918. $this->setAllowCSSDoubleUnderscores(FALSE);
  919. }
  920. /**
  921. * Set the variable allow_css_double_underscores and reset the cache.
  922. *
  923. * @param $value bool
  924. * A new value to be set to allow_css_double_underscores.
  925. */
  926. function setAllowCSSDoubleUnderscores($value) {
  927. $GLOBALS['conf']['allow_css_double_underscores'] = $value;
  928. drupal_static_reset('drupal_clean_css_identifier:allow_css_double_underscores');
  929. }
  930. /**
  931. * Tests that drupal_html_class() cleans the class name properly.
  932. */
  933. function testDrupalHTMLClass() {
  934. // Verify Drupal coding standards are enforced.
  935. $this->assertIdentical(drupal_html_class('CLASS NAME_[Ü]'), 'class-name--ü', 'Enforce Drupal coding standards.');
  936. }
  937. /**
  938. * Tests that drupal_html_id() cleans the ID properly.
  939. */
  940. function testDrupalHTMLId() {
  941. // Verify that letters, digits, and hyphens are not stripped from the ID.
  942. $id = 'abcdefghijklmnopqrstuvwxyz-0123456789';
  943. $this->assertIdentical(drupal_html_id($id), $id, 'Verify valid characters pass through.');
  944. // Verify that invalid characters are stripped from the ID.
  945. $this->assertIdentical(drupal_html_id('invalid,./:@\\^`{Üidentifier'), 'invalididentifier', 'Strip invalid characters.');
  946. // Verify Drupal coding standards are enforced.
  947. $this->assertIdentical(drupal_html_id('ID NAME_[1]'), 'id-name-1', 'Enforce Drupal coding standards.');
  948. // Reset the static cache so we can ensure the unique id count is at zero.
  949. drupal_static_reset('drupal_html_id');
  950. // Clean up IDs with invalid starting characters.
  951. $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id', 'Test the uniqueness of IDs #1.');
  952. $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id--2', 'Test the uniqueness of IDs #2.');
  953. $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id--3', 'Test the uniqueness of IDs #3.');
  954. }
  955. }
  956. /**
  957. * CSS Unit Tests.
  958. */
  959. class CascadingStylesheetsUnitTest extends DrupalUnitTestCase {
  960. public static function getInfo() {
  961. return array(
  962. 'name' => 'CSS Unit Tests',
  963. 'description' => 'Unit tests on CSS functions like aggregation.',
  964. 'group' => 'System',
  965. );
  966. }
  967. /**
  968. * Tests basic CSS loading with and without optimization via drupal_load_stylesheet().
  969. *
  970. * Known tests:
  971. * - Retain white-space in selectors. (https://drupal.org/node/472820)
  972. * - Proper URLs in imported files. (https://drupal.org/node/265719)
  973. * - Retain pseudo-selectors. (https://drupal.org/node/460448)
  974. * - Don't adjust data URIs. (https://drupal.org/node/2142441)
  975. * - Files imported from external URLs. (https://drupal.org/node/2014851)
  976. */
  977. function testLoadCssBasic() {
  978. // Array of files to test living in 'simpletest/files/css_test_files/'.
  979. // - Original: name.css
  980. // - Unoptimized expected content: name.css.unoptimized.css
  981. // - Optimized expected content: name.css.optimized.css
  982. $testfiles = array(
  983. 'css_input_without_import.css',
  984. 'css_input_with_import.css',
  985. 'css_subfolder/css_input_with_import.css',
  986. 'comment_hacks.css',
  987. 'quotes.css',
  988. );
  989. $path = drupal_get_path('module', 'simpletest') . '/files/css_test_files';
  990. foreach ($testfiles as $file) {
  991. $file_path = $path . '/' . $file;
  992. $file_url = $GLOBALS['base_url'] . '/' . $file_path;
  993. $expected = file_get_contents($file_path . '.unoptimized.css');
  994. $unoptimized_output = drupal_load_stylesheet($file_path, FALSE);
  995. $this->assertEqual($unoptimized_output, $expected, format_string('Unoptimized CSS file has expected contents (@file)', array('@file' => $file)));
  996. $expected = file_get_contents($file_path . '.optimized.css');
  997. $optimized_output = drupal_load_stylesheet($file_path, TRUE);
  998. $this->assertEqual($optimized_output, $expected, format_string('Optimized CSS file has expected contents (@file)', array('@file' => $file)));
  999. // Repeat the tests by accessing the stylesheets by URL.
  1000. $expected = file_get_contents($file_path . '.unoptimized.css');
  1001. $unoptimized_output_url = drupal_load_stylesheet($file_url, FALSE);
  1002. $this->assertEqual($unoptimized_output_url, $expected, format_string('Unoptimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
  1003. $expected = file_get_contents($file_path . '.optimized.css');
  1004. $optimized_output_url = drupal_load_stylesheet($file_url, TRUE);
  1005. $this->assertEqual($optimized_output_url, $expected, format_string('Optimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
  1006. }
  1007. }
  1008. }
  1009. /**
  1010. * Test drupal_http_request().
  1011. */
  1012. class DrupalHTTPRequestTestCase extends DrupalWebTestCase {
  1013. public static function getInfo() {
  1014. return array(
  1015. 'name' => 'Drupal HTTP request',
  1016. 'description' => "Performs tests on Drupal's HTTP request mechanism.",
  1017. 'group' => 'System'
  1018. );
  1019. }
  1020. function setUp() {
  1021. parent::setUp('system_test', 'locale');
  1022. }
  1023. function testDrupalHTTPRequest() {
  1024. global $is_https;
  1025. // Parse URL schema.
  1026. $missing_scheme = drupal_http_request('example.com/path');
  1027. $this->assertEqual($missing_scheme->code, -1002, 'Returned with "-1002" error code.');
  1028. $this->assertEqual($missing_scheme->error, 'missing schema', 'Returned with "missing schema" error message.');
  1029. $unable_to_parse = drupal_http_request('http:///path');
  1030. $this->assertEqual($unable_to_parse->code, -1001, 'Returned with "-1001" error code.');
  1031. $this->assertEqual($unable_to_parse->error, 'unable to parse URL', 'Returned with "unable to parse URL" error message.');
  1032. // Fetch page and check that the data parameter works with both array and string.
  1033. $data_array = array($this->randomName() => $this->randomString() . ' "\'');
  1034. $data_string = drupal_http_build_query($data_array);
  1035. $result = drupal_http_request(url('node', array('absolute' => TRUE)), array('data' => $data_array));
  1036. $this->assertEqual($result->code, 200, 'Fetched page successfully.');
  1037. $this->assertTrue(substr($result->request, -strlen($data_string)) === $data_string, 'Request ends with URL-encoded data when drupal_http_request() called using array.');
  1038. $result = drupal_http_request(url('node', array('absolute' => TRUE)), array('data' => $data_string));
  1039. $this->assertTrue(substr($result->request, -strlen($data_string)) === $data_string, 'Request ends with URL-encoded data when drupal_http_request() called using string.');
  1040. $this->drupalSetContent($result->data);
  1041. $this->assertTitle(t('Welcome to @site-name | @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), 'Site title matches.');
  1042. // Test that code and status message is returned.
  1043. $result = drupal_http_request(url('pagedoesnotexist', array('absolute' => TRUE)));
  1044. $this->assertTrue(!empty($result->protocol), 'Result protocol is returned.');
  1045. $this->assertEqual($result->code, '404', 'Result code is 404');
  1046. $this->assertEqual($result->status_message, 'Not Found', 'Result status message is "Not Found"');
  1047. // Skip the timeout tests when the testing environment is HTTPS because
  1048. // stream_set_timeout() does not work for SSL connections.
  1049. // @link http://bugs.php.net/bug.php?id=47929
  1050. if (!$is_https) {
  1051. // Test that timeout is respected. The test machine is expected to be able
  1052. // to make the connection (i.e. complete the fsockopen()) in 2 seconds and
  1053. // return within a total of 5 seconds. If the test machine is extremely
  1054. // slow, the test will fail. fsockopen() has been seen to time out in
  1055. // slightly less than the specified timeout, so allow a little slack on
  1056. // the minimum expected time (i.e. 1.8 instead of 2).
  1057. timer_start(__METHOD__);
  1058. $result = drupal_http_request(url('system-test/sleep/10', array('absolute' => TRUE)), array('timeout' => 2));
  1059. $time = timer_read(__METHOD__) / 1000;
  1060. $this->assertTrue(1.8 < $time && $time < 5, format_string('Request timed out (%time seconds).', array('%time' => $time)));
  1061. $this->assertTrue($result->error, 'An error message was returned.');
  1062. $this->assertEqual($result->code, HTTP_REQUEST_TIMEOUT, 'Proper error code was returned.');
  1063. }
  1064. }
  1065. function testDrupalHTTPRequestBasicAuth() {
  1066. $username = $this->randomName();
  1067. $password = $this->randomName();
  1068. $url = url('system-test/auth', array('absolute' => TRUE));
  1069. $auth = str_replace('://', '://' . $username . ':' . $password . '@', $url);
  1070. $result = drupal_http_request($auth);
  1071. $this->drupalSetContent($result->data);
  1072. $this->assertRaw($username, 'Username is passed correctly.');
  1073. $this->assertRaw($password, 'Password is passed correctly.');
  1074. }
  1075. function testDrupalHTTPRequestRedirect() {
  1076. $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 1));
  1077. $this->assertEqual($redirect_301->redirect_code, 301, 'drupal_http_request follows the 301 redirect.');
  1078. $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 0));
  1079. $this->assertFalse(isset($redirect_301->redirect_code), 'drupal_http_request does not follow 301 redirect if max_redirects = 0.');
  1080. $redirect_invalid = drupal_http_request(url('system-test/redirect-protocol-relative', array('absolute' => TRUE)), array('max_redirects' => 1));
  1081. $this->assertEqual($redirect_invalid->code, -1002, format_string('301 redirect to protocol-relative URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
  1082. $this->assertEqual($redirect_invalid->error, 'missing schema', format_string('301 redirect to protocol-relative URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
  1083. $redirect_invalid = drupal_http_request(url('system-test/redirect-noscheme', array('absolute' => TRUE)), array('max_redirects' => 1));
  1084. $this->assertEqual($redirect_invalid->code, -1002, format_string('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
  1085. $this->assertEqual($redirect_invalid->error, 'missing schema', format_string('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
  1086. $redirect_invalid = drupal_http_request(url('system-test/redirect-noparse', array('absolute' => TRUE)), array('max_redirects' => 1));
  1087. $this->assertEqual($redirect_invalid->code, -1001, format_string('301 redirect to invalid URL returned with error message code "!error".', array('!error' => $redirect_invalid->error)));
  1088. $this->assertEqual($redirect_invalid->error, 'unable to parse URL', format_string('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
  1089. $redirect_invalid = drupal_http_request(url('system-test/redirect-invalid-scheme', array('absolute' => TRUE)), array('max_redirects' => 1));
  1090. $this->assertEqual($redirect_invalid->code, -1003, format_string('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
  1091. $this->assertEqual($redirect_invalid->error, 'invalid schema ftp', format_string('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
  1092. $redirect_302 = drupal_http_request(url('system-test/redirect/302', array('absolute' => TRUE)), array('max_redirects' => 1));
  1093. $this->assertEqual($redirect_302->redirect_code, 302, 'drupal_http_request follows the 302 redirect.');
  1094. $redirect_302 = drupal_http_request(url('system-test/redirect/302', array('absolute' => TRUE)), array('max_redirects' => 0));
  1095. $this->assertFalse(isset($redirect_302->redirect_code), 'drupal_http_request does not follow 302 redirect if $retry = 0.');
  1096. $redirect_307 = drupal_http_request(url('system-test/redirect/307', array('absolute' => TRUE)), array('max_redirects' => 1));
  1097. $this->assertEqual($redirect_307->redirect_code, 307, 'drupal_http_request follows the 307 redirect.');
  1098. $redirect_307 = drupal_http_request(url('system-test/redirect/307', array('absolute' => TRUE)), array('max_redirects' => 0));
  1099. $this->assertFalse(isset($redirect_307->redirect_code), 'drupal_http_request does not follow 307 redirect if max_redirects = 0.');
  1100. $multiple_redirect_final_url = url('system-test/multiple-redirects/0', array('absolute' => TRUE));
  1101. $multiple_redirect_1 = drupal_http_request(url('system-test/multiple-redirects/1', array('absolute' => TRUE)), array('max_redirects' => 1));
  1102. $this->assertEqual($multiple_redirect_1->redirect_url, $multiple_redirect_final_url, 'redirect_url contains the final redirection location after 1 redirect.');
  1103. $multiple_redirect_3 = drupal_http_request(url('system-test/multiple-redirects/3', array('absolute' => TRUE)), array('max_redirects' => 3));
  1104. $this->assertEqual($multiple_redirect_3->redirect_url, $multiple_redirect_final_url, 'redirect_url contains the final redirection location after 3 redirects.');
  1105. }
  1106. /**
  1107. * Tests Content-language headers generated by Drupal.
  1108. */
  1109. function testDrupalHTTPRequestHeaders() {
  1110. // Check the default header.
  1111. $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
  1112. $this->assertEqual($request->headers['content-language'], 'en', 'Content-Language HTTP header is English.');
  1113. // Add German language and set as default.
  1114. locale_add_language('de', 'German', 'Deutsch', LANGUAGE_LTR, '', '', TRUE, TRUE);
  1115. // Request front page and check for matching Content-Language.
  1116. $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
  1117. $this->assertEqual($request->headers['content-language'], 'de', 'Content-Language HTTP header is German.');
  1118. }
  1119. }
  1120. /**
  1121. * Unit tests for processing of http redirects.
  1122. */
  1123. class DrupalHTTPRedirectTest extends DrupalUnitTestCase {
  1124. public static function getInfo() {
  1125. return array(
  1126. 'name' => 'Drupal HTTP redirect processing',
  1127. 'description' => 'Perform unit tests on processing of http redirects.',
  1128. 'group' => 'System',
  1129. );
  1130. }
  1131. public function testHttpsDowngrade() {
  1132. $url = 'https://example.com/foo';
  1133. $location = 'http://example.com/bar';
  1134. $this->assertTrue(_drupal_should_strip_sensitive_headers_on_http_redirect($url, $location), 'Sensitive headers are stripped on HTTPS downgrade.');
  1135. }
  1136. public function testNoHttpsDowngrade() {
  1137. $url = 'https://example.com/foo';
  1138. $location = 'https://example.com/bar';
  1139. $this->assertFalse(_drupal_should_strip_sensitive_headers_on_http_redirect($url, $location), 'Sensitive headers are not stripped without HTTPS downgrade.');
  1140. }
  1141. public function testHostChange() {
  1142. $url = 'https://example.com/foo';
  1143. $location = 'https://www.example.com/bar';
  1144. $this->assertTrue(_drupal_should_strip_sensitive_headers_on_http_redirect($url, $location), 'Sensitive headers are stripped on change of host.');
  1145. }
  1146. public function testNoHostChange() {
  1147. $url = 'http://example.com/foo';
  1148. $location = 'http://example.com/bar';
  1149. $this->assertFalse(_drupal_should_strip_sensitive_headers_on_http_redirect($url, $location), 'Sensitive headers are not stripped without change of host.');
  1150. }
  1151. }
  1152. /**
  1153. * Tests parsing of the HTTP response status line.
  1154. */
  1155. class DrupalHTTPResponseStatusLineTest extends DrupalUnitTestCase {
  1156. public static function getInfo() {
  1157. return array(
  1158. 'name' => 'Drupal HTTP request response status parsing',
  1159. 'description' => 'Perform unit tests on _drupal_parse_response_status().',
  1160. 'group' => 'System',
  1161. );
  1162. }
  1163. /**
  1164. * Tests parsing HTTP response status line.
  1165. */
  1166. public function testStatusLine() {
  1167. // Grab the big array of test data from statusLineData().
  1168. $data = $this->statusLineData();
  1169. foreach($data as $test_case) {
  1170. $test_data = array_shift($test_case);
  1171. $expected = array_shift($test_case);
  1172. $outcome = _drupal_parse_response_status($test_data);
  1173. foreach(array_keys($expected) as $key) {
  1174. $this->assertIdentical($outcome[$key], $expected[$key]);
  1175. }
  1176. }
  1177. }
  1178. /**
  1179. * Data provider for testStatusLine().
  1180. *
  1181. * @return array
  1182. * Test data.
  1183. */
  1184. protected function statusLineData() {
  1185. return array(
  1186. array(
  1187. 'HTTP/1.1 200 OK',
  1188. array(
  1189. 'http_version' => 'HTTP/1.1',
  1190. 'response_code' => '200',
  1191. 'reason_phrase' => 'OK',
  1192. ),
  1193. ),
  1194. // Data set with no reason phrase.
  1195. array(
  1196. 'HTTP/1.1 200',
  1197. array(
  1198. 'http_version' => 'HTTP/1.1',
  1199. 'response_code' => '200',
  1200. 'reason_phrase' => '',
  1201. ),
  1202. ),
  1203. // Arbitrary strings.
  1204. array(
  1205. 'version code multi word explanation',
  1206. array(
  1207. 'http_version' => 'version',
  1208. 'response_code' => 'code',
  1209. 'reason_phrase' => 'multi word explanation',
  1210. ),
  1211. ),
  1212. );
  1213. }
  1214. }
  1215. /**
  1216. * Testing drupal_add_region_content and drupal_get_region_content.
  1217. */
  1218. class DrupalSetContentTestCase extends DrupalWebTestCase {
  1219. public static function getInfo() {
  1220. return array(
  1221. 'name' => 'Drupal set/get regions',
  1222. 'description' => 'Performs tests on setting and retrieiving content from theme regions.',
  1223. 'group' => 'System'
  1224. );
  1225. }
  1226. /**
  1227. * Test setting and retrieving content for theme regions.
  1228. */
  1229. function testRegions() {
  1230. global $theme_key;
  1231. $block_regions = system_region_list($theme_key, REGIONS_ALL, FALSE);
  1232. $delimiter = $this->randomName(32);
  1233. $values = array();
  1234. // Set some random content for each region available.
  1235. foreach ($block_regions as $region) {
  1236. $first_chunk = $this->randomName(32);
  1237. drupal_add_region_content($region, $first_chunk);
  1238. $second_chunk = $this->randomName(32);
  1239. drupal_add_region_content($region, $second_chunk);
  1240. // Store the expected result for a drupal_get_region_content call for this region.
  1241. $values[$region] = $first_chunk . $delimiter . $second_chunk;
  1242. }
  1243. // Ensure drupal_get_region_content returns expected results when fetching all regions.
  1244. $content = drupal_get_region_content(NULL, $delimiter);
  1245. foreach ($content as $region => $region_content) {
  1246. $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching all regions', array('@region' => $region)));
  1247. }
  1248. // Ensure drupal_get_region_content returns expected results when fetching a single region.
  1249. foreach ($block_regions as $region) {
  1250. $region_content = drupal_get_region_content($region, $delimiter);
  1251. $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching single region.', array('@region' => $region)));
  1252. }
  1253. }
  1254. }
  1255. /**
  1256. * Testing drupal_goto and hook_drupal_goto_alter().
  1257. */
  1258. class DrupalGotoTest extends DrupalWebTestCase {
  1259. public static function getInfo() {
  1260. return array(
  1261. 'name' => 'Drupal goto',
  1262. 'description' => 'Performs tests on the drupal_goto function and hook_drupal_goto_alter',
  1263. 'group' => 'System'
  1264. );
  1265. }
  1266. function setUp() {
  1267. parent::setUp('common_test');
  1268. }
  1269. /**
  1270. * Test drupal_goto().
  1271. */
  1272. function testDrupalGoto() {
  1273. $this->drupalGet('common-test/drupal_goto/redirect');
  1274. $headers = $this->drupalGetHeaders(TRUE);
  1275. list(, $status) = explode(' ', $headers[0][':status'], 3);
  1276. $this->assertEqual($status, 302, 'Expected response code was sent.');
  1277. $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
  1278. $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
  1279. $this->drupalGet('common-test/drupal_goto/redirect_advanced');
  1280. $headers = $this->drupalGetHeaders(TRUE);
  1281. list(, $status) = explode(' ', $headers[0][':status'], 3);
  1282. $this->assertEqual($status, 301, 'Expected response code was sent.');
  1283. $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
  1284. $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('query' => array('foo' => '123'), 'absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
  1285. // Test that calling drupal_goto() on the current path is not dangerous.
  1286. variable_set('common_test_redirect_current_path', TRUE);
  1287. $this->drupalGet('', array('query' => array('q' => 'http://www.example.com/')));
  1288. $headers = $this->drupalGetHeaders(TRUE);
  1289. list(, $status) = explode(' ', $headers[0][':status'], 3);
  1290. $this->assertEqual($status, 302, 'Expected response code was sent.');
  1291. $this->assertNotEqual($this->getUrl(), 'http://www.example.com/', 'Drupal goto did not redirect to external URL.');
  1292. $this->assertTrue(strpos($this->getUrl(), url('<front>', array('absolute' => TRUE))) === 0, 'Drupal redirected to itself.');
  1293. variable_del('common_test_redirect_current_path');
  1294. // Test that drupal_goto() respects ?destination=xxx. Use an complicated URL
  1295. // to test that the path is encoded and decoded properly.
  1296. $destination = 'common-test/drupal_goto/destination?foo=%2525&bar=123';
  1297. $this->drupalGet('common-test/drupal_goto/redirect', array('query' => array('destination' => $destination)));
  1298. $this->assertText('drupal_goto', 'Drupal goto redirect with destination succeeded.');
  1299. $this->assertEqual($this->getUrl(), url('common-test/drupal_goto/destination', array('query' => array('foo' => '%25', 'bar' => '123'), 'absolute' => TRUE)), 'Drupal goto redirected to given query string destination.');
  1300. }
  1301. /**
  1302. * Test hook_drupal_goto_alter().
  1303. */
  1304. function testDrupalGotoAlter() {
  1305. $this->drupalGet('common-test/drupal_goto/redirect_fail');
  1306. $this->assertNoText(t("Drupal goto failed to stop program"), "Drupal goto stopped program.");
  1307. $this->assertNoText('drupal_goto_fail', "Drupal goto redirect failed.");
  1308. }
  1309. /**
  1310. * Test drupal_get_destination().
  1311. */
  1312. function testDrupalGetDestination() {
  1313. $query = $this->randomName(10);
  1314. // Verify that a 'destination' query string is used as destination.
  1315. $this->drupalGet('common-test/destination', array('query' => array('destination' => $query)));
  1316. $this->assertText('The destination: ' . $query, 'The given query string destination is determined as destination.');
  1317. // Verify that the current path is used as destination.
  1318. $this->drupalGet('common-test/destination', array('query' => array($query => NULL)));
  1319. $url = 'common-test/destination?' . $query;
  1320. $this->assertText('The destination: ' . $url, 'The current path is determined as destination.');
  1321. }
  1322. }
  1323. /**
  1324. * Tests for the JavaScript system.
  1325. */
  1326. class JavaScriptTestCase extends DrupalWebTestCase {
  1327. /**
  1328. * Store configured value for JavaScript preprocessing.
  1329. */
  1330. protected $preprocess_js = NULL;
  1331. public static function getInfo() {
  1332. return array(
  1333. 'name' => 'JavaScript',
  1334. 'description' => 'Tests the JavaScript system.',
  1335. 'group' => 'System'
  1336. );
  1337. }
  1338. function setUp() {
  1339. // Enable Locale and SimpleTest in the test environment.
  1340. parent::setUp('locale', 'simpletest', 'common_test');
  1341. // Disable preprocessing
  1342. $this->preprocess_js = variable_get('preprocess_js', 0);
  1343. variable_set('preprocess_js', 0);
  1344. // Reset drupal_add_js() and drupal_add_library() statics before each test.
  1345. drupal_static_reset('drupal_add_js');
  1346. drupal_static_reset('drupal_add_library');
  1347. }
  1348. function tearDown() {
  1349. // Restore configured value for JavaScript preprocessing.
  1350. variable_set('preprocess_js', $this->preprocess_js);
  1351. parent::tearDown();
  1352. }
  1353. /**
  1354. * Test default JavaScript is empty.
  1355. */
  1356. function testDefault() {
  1357. $this->assertEqual(array(), drupal_add_js(), 'Default JavaScript is empty.');
  1358. }
  1359. /**
  1360. * Test adding a JavaScript file.
  1361. */
  1362. function testAddFile() {
  1363. $javascript = drupal_add_js('misc/collapse.js');
  1364. $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when a file is added.');
  1365. $this->assertTrue(array_key_exists('misc/drupal.js', $javascript), 'Drupal.js is added when file is added.');
  1366. $this->assertTrue(array_key_exists('misc/collapse.js', $javascript), 'JavaScript files are correctly added.');
  1367. $this->assertEqual(base_path(), $javascript['settings']['data'][0]['basePath'], 'Base path JavaScript setting is correctly set.');
  1368. url('', array('prefix' => &$prefix));
  1369. $this->assertEqual(empty($prefix) ? '' : $prefix, $javascript['settings']['data'][1]['pathPrefix'], 'Path prefix JavaScript setting is correctly set.');
  1370. }
  1371. /**
  1372. * Test adding settings.
  1373. */
  1374. function testAddSetting() {
  1375. $javascript = drupal_add_js(array('drupal' => 'rocks', 'dries' => 280342800), 'setting');
  1376. $this->assertEqual(280342800, $javascript['settings']['data'][3]['dries'], 'JavaScript setting is set correctly.');
  1377. $this->assertEqual('rocks', $javascript['settings']['data'][3]['drupal'], 'The other JavaScript setting is set correctly.');
  1378. }
  1379. /**
  1380. * Tests adding an external JavaScript File.
  1381. */
  1382. function testAddExternal() {
  1383. $path = 'http://example.com/script.js';
  1384. $javascript = drupal_add_js($path, 'external');
  1385. $this->assertTrue(array_key_exists('http://example.com/script.js', $javascript), 'Added an external JavaScript file.');
  1386. }
  1387. /**
  1388. * Test drupal_get_js() for JavaScript settings.
  1389. */
  1390. function testHeaderSetting() {
  1391. // Only the second of these two entries should appear in Drupal.settings.
  1392. drupal_add_js(array('commonTest' => 'commonTestShouldNotAppear'), 'setting');
  1393. drupal_add_js(array('commonTest' => 'commonTestShouldAppear'), 'setting');
  1394. // All three of these entries should appear in Drupal.settings.
  1395. drupal_add_js(array('commonTestArray' => array('commonTestValue0')), 'setting');
  1396. drupal_add_js(array('commonTestArray' => array('commonTestValue1')), 'setting');
  1397. drupal_add_js(array('commonTestArray' => array('commonTestValue2')), 'setting');
  1398. // Only the second of these two entries should appear in Drupal.settings.
  1399. drupal_add_js(array('commonTestArray' => array('key' => 'commonTestOldValue')), 'setting');
  1400. drupal_add_js(array('commonTestArray' => array('key' => 'commonTestNewValue')), 'setting');
  1401. $javascript = drupal_get_js('header');
  1402. $this->assertTrue(strpos($javascript, 'basePath') > 0, 'Rendered JavaScript header returns basePath setting.');
  1403. $this->assertTrue(strpos($javascript, 'misc/jquery.js') > 0, 'Rendered JavaScript header includes jQuery.');
  1404. $this->assertTrue(strpos($javascript, 'pathPrefix') > 0, 'Rendered JavaScript header returns pathPrefix setting.');
  1405. // Test whether drupal_add_js can be used to override a previous setting.
  1406. $this->assertTrue(strpos($javascript, 'commonTestShouldAppear') > 0, 'Rendered JavaScript header returns custom setting.');
  1407. $this->assertTrue(strpos($javascript, 'commonTestShouldNotAppear') === FALSE, 'drupal_add_js() correctly overrides a custom setting.');
  1408. // Test whether drupal_add_js can be used to add numerically indexed values
  1409. // to an array.
  1410. $array_values_appear = strpos($javascript, 'commonTestValue0') > 0 && strpos($javascript, 'commonTestValue1') > 0 && strpos($javascript, 'commonTestValue2') > 0;
  1411. $this->assertTrue($array_values_appear, 'drupal_add_js() correctly adds settings to the end of an indexed array.');
  1412. // Test whether drupal_add_js can be used to override the entry for an
  1413. // existing key in an associative array.
  1414. $associative_array_override = strpos($javascript, 'commonTestNewValue') > 0 && strpos($javascript, 'commonTestOldValue') === FALSE;
  1415. $this->assertTrue($associative_array_override, 'drupal_add_js() correctly overrides settings within an associative array.');
  1416. }
  1417. /**
  1418. * Test to see if resetting the JavaScript empties the cache.
  1419. */
  1420. function testReset() {
  1421. drupal_add_js('misc/collapse.js');
  1422. drupal_static_reset('drupal_add_js');
  1423. $this->assertEqual(array(), drupal_add_js(), 'Resetting the JavaScript correctly empties the cache.');
  1424. }
  1425. /**
  1426. * Test adding inline scripts.
  1427. */
  1428. function testAddInline() {
  1429. $inline = 'jQuery(function () { });';
  1430. $javascript = drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
  1431. $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when inline scripts are added.');
  1432. $data = end($javascript);
  1433. $this->assertEqual($inline, $data['data'], 'Inline JavaScript is correctly added to the footer.');
  1434. }
  1435. /**
  1436. * Test rendering an external JavaScript file.
  1437. */
  1438. function testRenderExternal() {
  1439. $external = 'http://example.com/example.js';
  1440. drupal_add_js($external, 'external');
  1441. $javascript = drupal_get_js();
  1442. // Local files have a base_path() prefix, external files should not.
  1443. $this->assertTrue(strpos($javascript, 'src="' . $external) > 0, 'Rendering an external JavaScript file.');
  1444. }
  1445. /**
  1446. * Test drupal_get_js() with a footer scope.
  1447. */
  1448. function testFooterHTML() {
  1449. $inline = 'jQuery(function () { });';
  1450. drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
  1451. $javascript = drupal_get_js('footer');
  1452. $this->assertTrue(strpos($javascript, $inline) > 0, 'Rendered JavaScript footer returns the inline code.');
  1453. }
  1454. /**
  1455. * Test the 'javascript_always_use_jquery' variable.
  1456. */
  1457. function testJavaScriptAlwaysUseJQuery() {
  1458. // The default front page of the site should use jQuery and other standard
  1459. // scripts and settings.
  1460. $this->drupalGet('');
  1461. $this->assertRaw('misc/jquery.js', 'Default behavior: The front page of the site includes jquery.js.');
  1462. $this->assertRaw('misc/drupal.js', 'Default behavior: The front page of the site includes drupal.js.');
  1463. $this->assertRaw('Drupal.settings', 'Default behavior: The front page of the site includes Drupal settings.');
  1464. $this->assertRaw('basePath', 'Default behavior: The front page of the site includes the basePath Drupal setting.');
  1465. // The default front page should not use jQuery and other standard scripts
  1466. // and settings when the 'javascript_always_use_jquery' variable is set to
  1467. // FALSE.
  1468. variable_set('javascript_always_use_jquery', FALSE);
  1469. $this->drupalGet('');
  1470. $this->assertNoRaw('misc/jquery.js', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include jquery.js.');
  1471. $this->assertNoRaw('misc/drupal.js', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include drupal.js.');
  1472. $this->assertNoRaw('Drupal.settings', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include Drupal settings.');
  1473. $this->assertNoRaw('basePath', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include the basePath Drupal setting.');
  1474. variable_del('javascript_always_use_jquery');
  1475. // When only settings have been added via drupal_add_js(), drupal_get_js()
  1476. // should still return jQuery and other standard scripts and settings.
  1477. $this->resetStaticVariables();
  1478. drupal_add_js(array('testJavaScriptSetting' => 'test'), 'setting');
  1479. $javascript = drupal_get_js();
  1480. $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes jquery.js.');
  1481. $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes drupal.js.');
  1482. $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes Drupal.settings.');
  1483. $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes the basePath Drupal setting.');
  1484. $this->assertTrue(strpos($javascript, 'testJavaScriptSetting') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes the added Drupal settings.');
  1485. // When only settings have been added via drupal_add_js() and the
  1486. // 'javascript_always_use_jquery' variable is set to FALSE, drupal_get_js()
  1487. // should not return jQuery and other standard scripts and settings, nor
  1488. // should it return the requested settings (since they cannot actually be
  1489. // addded to the page without jQuery).
  1490. $this->resetStaticVariables();
  1491. variable_set('javascript_always_use_jquery', FALSE);
  1492. drupal_add_js(array('testJavaScriptSetting' => 'test'), 'setting');
  1493. $javascript = drupal_get_js();
  1494. $this->assertTrue(strpos($javascript, 'misc/jquery.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include jquery.js.');
  1495. $this->assertTrue(strpos($javascript, 'misc/drupal.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include drupal.js.');
  1496. $this->assertTrue(strpos($javascript, 'Drupal.settings') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include Drupal.settings.');
  1497. $this->assertTrue(strpos($javascript, 'basePath') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include the basePath Drupal setting.');
  1498. $this->assertTrue(strpos($javascript, 'testJavaScriptSetting') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include the added Drupal settings.');
  1499. variable_del('javascript_always_use_jquery');
  1500. // When a regular file has been added via drupal_add_js(), drupal_get_js()
  1501. // should return jQuery and other standard scripts and settings.
  1502. $this->resetStaticVariables();
  1503. drupal_add_js('misc/collapse.js');
  1504. $javascript = drupal_get_js();
  1505. $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes jquery.js.');
  1506. $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes drupal.js.');
  1507. $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes Drupal.settings.');
  1508. $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the basePath Drupal setting.');
  1509. $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the custom file.');
  1510. // When a regular file has been added via drupal_add_js() and the
  1511. // 'javascript_always_use_jquery' variable is set to FALSE, drupal_get_js()
  1512. // should still return jQuery and other standard scripts and settings
  1513. // (since the file is assumed to require jQuery by default).
  1514. $this->resetStaticVariables();
  1515. variable_set('javascript_always_use_jquery', FALSE);
  1516. drupal_add_js('misc/collapse.js');
  1517. $javascript = drupal_get_js();
  1518. $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes jquery.js.');
  1519. $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes drupal.js.');
  1520. $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes Drupal.settings.');
  1521. $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the basePath Drupal setting.');
  1522. $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the custom file.');
  1523. variable_del('javascript_always_use_jquery');
  1524. // When a file that does not require jQuery has been added via
  1525. // drupal_add_js(), drupal_get_js() should still return jQuery and other
  1526. // standard scripts and settings by default.
  1527. $this->resetStaticVariables();
  1528. drupal_add_js('misc/collapse.js', array('requires_jquery' => FALSE));
  1529. $javascript = drupal_get_js();
  1530. $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes jquery.js.');
  1531. $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes drupal.js.');
  1532. $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes Drupal.settings.');
  1533. $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes the basePath Drupal setting.');
  1534. $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes the custom file.');
  1535. // When a file that does not require jQuery has been added via
  1536. // drupal_add_js() and the 'javascript_always_use_jquery' variable is set
  1537. // to FALSE, drupal_get_js() should not return jQuery and other standard
  1538. // scripts and setting, but it should still return the requested file.
  1539. $this->resetStaticVariables();
  1540. variable_set('javascript_always_use_jquery', FALSE);
  1541. drupal_add_js('misc/collapse.js', array('requires_jquery' => FALSE));
  1542. $javascript = drupal_get_js();
  1543. $this->assertTrue(strpos($javascript, 'misc/jquery.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include jquery.js.');
  1544. $this->assertTrue(strpos($javascript, 'misc/drupal.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include drupal.js.');
  1545. $this->assertTrue(strpos($javascript, 'Drupal.settings') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include Drupal.settings.');
  1546. $this->assertTrue(strpos($javascript, 'basePath') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include the basePath Drupal setting.');
  1547. $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes the custom file.');
  1548. variable_del('javascript_always_use_jquery');
  1549. // When 'javascript_always_use_jquery' is set to FALSE and a file that does
  1550. // not require jQuery is added, followed by one that does, drupal_get_js()
  1551. // should return jQuery and other standard scripts and settings, in
  1552. // addition to both of the requested files.
  1553. $this->resetStaticVariables();
  1554. variable_set('javascript_always_use_jquery', FALSE);
  1555. drupal_add_js('misc/collapse.js', array('requires_jquery' => FALSE));
  1556. drupal_add_js('misc/ajax.js');
  1557. $javascript = drupal_get_js();
  1558. $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes jquery.js.');
  1559. $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes drupal.js.');
  1560. $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes Drupal.settings.');
  1561. $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes the basePath Drupal setting.');
  1562. $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes the first custom file.');
  1563. $this->assertTrue(strpos($javascript, 'misc/ajax.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes the second custom file.');
  1564. variable_del('javascript_always_use_jquery');
  1565. }
  1566. /**
  1567. * Tests the double submit form protection and
  1568. * 'javascript_use_double_submit_protection' variable.
  1569. */
  1570. function testDoubleSubmitFormProtection() {
  1571. // The default front page of the site should have the double submit
  1572. // protection enabled as there is a login block.
  1573. $this->drupalGet('');
  1574. $this->assertRaw('misc/form-single-submit.js', 'Default behavior: Double submit protection is enabled.');
  1575. // The default front page should have the double submit protection disabled
  1576. // when the 'javascript_always_use_jquery' variable is set to FALSE or the
  1577. // 'javascript_use_double_submit_protection' variable is set to FALSE.
  1578. variable_set('javascript_always_use_jquery', FALSE);
  1579. $this->drupalGet('');
  1580. $this->assertNoRaw('misc/form-single-submit.js', 'When "javascript_always_use_jquery" is FALSE: Double submit protection is disabled.');
  1581. variable_del('javascript_always_use_jquery');
  1582. variable_set('javascript_use_double_submit_protection', FALSE);
  1583. $this->drupalGet('');
  1584. $this->assertNoRaw('misc/form-single-submit.js', 'When "javascript_use_double_submit_protection" is FALSE: Double submit protection is disabled.');
  1585. variable_del('javascript_use_double_submit_protection');
  1586. }
  1587. /**
  1588. * Test drupal_add_js() sets preproccess to false when cache is set to false.
  1589. */
  1590. function testNoCache() {
  1591. $javascript = drupal_add_js('misc/collapse.js', array('cache' => FALSE));
  1592. $this->assertFalse($javascript['misc/collapse.js']['preprocess'], 'Setting cache to FALSE sets proprocess to FALSE when adding JavaScript.');
  1593. }
  1594. /**
  1595. * Test adding a JavaScript file with a different group.
  1596. */
  1597. function testDifferentGroup() {
  1598. $javascript = drupal_add_js('misc/collapse.js', array('group' => JS_THEME));
  1599. $this->assertEqual($javascript['misc/collapse.js']['group'], JS_THEME, 'Adding a JavaScript file with a different group caches the given group.');
  1600. }
  1601. /**
  1602. * Test adding a JavaScript file with a different weight.
  1603. */
  1604. function testDifferentWeight() {
  1605. $javascript = drupal_add_js('misc/collapse.js', array('weight' => 2));
  1606. $this->assertEqual($javascript['misc/collapse.js']['weight'], 2, 'Adding a JavaScript file with a different weight caches the given weight.');
  1607. }
  1608. /**
  1609. * Tests JavaScript aggregation when files are added to a different scope.
  1610. */
  1611. function testAggregationOrder() {
  1612. // Enable JavaScript aggregation.
  1613. variable_set('preprocess_js', 1);
  1614. drupal_static_reset('drupal_add_js');
  1615. // Add two JavaScript files to the current request and build the cache.
  1616. drupal_add_js('misc/ajax.js');
  1617. drupal_add_js('misc/autocomplete.js');
  1618. $js_items = drupal_add_js();
  1619. drupal_build_js_cache(array(
  1620. 'misc/ajax.js' => $js_items['misc/ajax.js'],
  1621. 'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
  1622. ));
  1623. // Store the expected key for the first item in the cache.
  1624. $cache = array_keys(variable_get('drupal_js_cache_files', array()));
  1625. $expected_key = $cache[0];
  1626. // Reset variables and add a file in a different scope first.
  1627. variable_del('drupal_js_cache_files');
  1628. drupal_static_reset('drupal_add_js');
  1629. drupal_add_js('some/custom/javascript_file.js', array('scope' => 'footer'));
  1630. drupal_add_js('misc/ajax.js');
  1631. drupal_add_js('misc/autocomplete.js');
  1632. // Rebuild the cache.
  1633. $js_items = drupal_add_js();
  1634. drupal_build_js_cache(array(
  1635. 'misc/ajax.js' => $js_items['misc/ajax.js'],
  1636. 'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
  1637. ));
  1638. // Compare the expected key for the first file to the current one.
  1639. $cache = array_keys(variable_get('drupal_js_cache_files', array()));
  1640. $key = $cache[0];
  1641. $this->assertEqual($key, $expected_key, 'JavaScript aggregation is not affected by ordering in different scopes.');
  1642. }
  1643. /**
  1644. * Test JavaScript ordering.
  1645. */
  1646. function testRenderOrder() {
  1647. // Add a bunch of JavaScript in strange ordering.
  1648. drupal_add_js('(function($){alert("Weight 5 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
  1649. drupal_add_js('(function($){alert("Weight 0 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
  1650. drupal_add_js('(function($){alert("Weight 0 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
  1651. drupal_add_js('(function($){alert("Weight -8 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
  1652. drupal_add_js('(function($){alert("Weight -8 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
  1653. drupal_add_js('(function($){alert("Weight -8 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
  1654. drupal_add_js('http://example.com/example.js?Weight -5 #1', array('type' => 'external', 'scope' => 'footer', 'weight' => -5));
  1655. drupal_add_js('(function($){alert("Weight -8 #4");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
  1656. drupal_add_js('(function($){alert("Weight 5 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
  1657. drupal_add_js('(function($){alert("Weight 0 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
  1658. // Construct the expected result from the regex.
  1659. $expected = array(
  1660. "-8 #1",
  1661. "-8 #2",
  1662. "-8 #3",
  1663. "-8 #4",
  1664. "-5 #1", // The external script.
  1665. "0 #1",
  1666. "0 #2",
  1667. "0 #3",
  1668. "5 #1",
  1669. "5 #2",
  1670. );
  1671. // Retrieve the rendered JavaScript and test against the regex.
  1672. $js = drupal_get_js('footer');
  1673. $matches = array();
  1674. if (preg_match_all('/Weight\s([-0-9]+\s[#0-9]+)/', $js, $matches)) {
  1675. $result = $matches[1];
  1676. }
  1677. else {
  1678. $result = array();
  1679. }
  1680. $this->assertIdentical($result, $expected, 'JavaScript is added in the expected weight order.');
  1681. }
  1682. /**
  1683. * Test rendering the JavaScript with a file's weight above jQuery's.
  1684. */
  1685. function testRenderDifferentWeight() {
  1686. // JavaScript files are sorted first by group, then by the 'every_page'
  1687. // flag, then by weight (see drupal_sort_css_js()), so to test the effect of
  1688. // weight, we need the other two options to be the same.
  1689. drupal_add_js('misc/collapse.js', array('group' => JS_LIBRARY, 'every_page' => TRUE, 'weight' => -21));
  1690. $javascript = drupal_get_js();
  1691. $this->assertTrue(strpos($javascript, 'misc/collapse.js') < strpos($javascript, 'misc/jquery.js'), 'Rendering a JavaScript file above jQuery.');
  1692. }
  1693. /**
  1694. * Test altering a JavaScript's weight via hook_js_alter().
  1695. *
  1696. * @see simpletest_js_alter()
  1697. */
  1698. function testAlter() {
  1699. // Add both tableselect.js and simpletest.js, with a larger weight on SimpleTest.
  1700. drupal_add_js('misc/tableselect.js');
  1701. drupal_add_js(drupal_get_path('module', 'simpletest') . '/simpletest.js', array('weight' => 9999));
  1702. // Render the JavaScript, testing if simpletest.js was altered to be before
  1703. // tableselect.js. See simpletest_js_alter() to see where this alteration
  1704. // takes place.
  1705. $javascript = drupal_get_js();
  1706. $this->assertTrue(strpos($javascript, 'simpletest.js') < strpos($javascript, 'misc/tableselect.js'), 'Altering JavaScript weight through the alter hook.');
  1707. }
  1708. /**
  1709. * Adds a library to the page and tests for both its JavaScript and its CSS.
  1710. */
  1711. function testLibraryRender() {
  1712. $result = drupal_add_library('system', 'farbtastic');
  1713. $this->assertTrue($result !== FALSE, 'Library was added without errors.');
  1714. $scripts = drupal_get_js();
  1715. $styles = drupal_get_css();
  1716. $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), 'JavaScript of library was added to the page.');
  1717. $this->assertTrue(strpos($styles, 'misc/farbtastic/farbtastic.css'), 'Stylesheet of library was added to the page.');
  1718. }
  1719. /**
  1720. * Adds a JavaScript library to the page and alters it.
  1721. *
  1722. * @see common_test_library_alter()
  1723. */
  1724. function testLibraryAlter() {
  1725. // Verify that common_test altered the title of Farbtastic.
  1726. $library = drupal_get_library('system', 'farbtastic');
  1727. $this->assertEqual($library['title'], 'Farbtastic: Altered Library', 'Registered libraries were altered.');
  1728. // common_test_library_alter() also added a dependency on jQuery Form.
  1729. drupal_add_library('system', 'farbtastic');
  1730. $scripts = drupal_get_js();
  1731. $this->assertTrue(strpos($scripts, 'misc/jquery.form.js'), 'Altered library dependencies are added to the page.');
  1732. }
  1733. /**
  1734. * Tests that multiple modules can implement the same library.
  1735. *
  1736. * @see common_test_library()
  1737. */
  1738. function testLibraryNameConflicts() {
  1739. $farbtastic = drupal_get_library('common_test', 'farbtastic');
  1740. $this->assertEqual($farbtastic['title'], 'Custom Farbtastic Library', 'Alternative libraries can be added to the page.');
  1741. }
  1742. /**
  1743. * Tests non-existing libraries.
  1744. */
  1745. function testLibraryUnknown() {
  1746. $result = drupal_get_library('unknown', 'unknown');
  1747. $this->assertFalse($result, 'Unknown library returned FALSE.');
  1748. drupal_static_reset('drupal_get_library');
  1749. $result = drupal_add_library('unknown', 'unknown');
  1750. $this->assertFalse($result, 'Unknown library returned FALSE.');
  1751. $scripts = drupal_get_js();
  1752. $this->assertTrue(strpos($scripts, 'unknown') === FALSE, 'Unknown library was not added to the page.');
  1753. }
  1754. /**
  1755. * Tests the addition of libraries through the #attached['library'] property.
  1756. */
  1757. function testAttachedLibrary() {
  1758. $element['#attached']['library'][] = array('system', 'farbtastic');
  1759. drupal_render($element);
  1760. $scripts = drupal_get_js();
  1761. $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), 'The attached_library property adds the additional libraries.');
  1762. }
  1763. /**
  1764. * Tests retrieval of libraries via drupal_get_library().
  1765. */
  1766. function testGetLibrary() {
  1767. // Retrieve all libraries registered by a module.
  1768. $libraries = drupal_get_library('common_test');
  1769. $this->assertTrue(isset($libraries['farbtastic']), 'Retrieved all module libraries.');
  1770. // Retrieve all libraries for a module not implementing hook_library().
  1771. // Note: This test installs Locale module.
  1772. $libraries = drupal_get_library('locale');
  1773. $this->assertEqual($libraries, array(), 'Retrieving libraries from a module not implementing hook_library() returns an emtpy array.');
  1774. // Retrieve a specific library by module and name.
  1775. $farbtastic = drupal_get_library('common_test', 'farbtastic');
  1776. $this->assertEqual($farbtastic['version'], '5.3', 'Retrieved a single library.');
  1777. // Retrieve a non-existing library by module and name.
  1778. $farbtastic = drupal_get_library('common_test', 'foo');
  1779. $this->assertIdentical($farbtastic, FALSE, 'Retrieving a non-existing library returns FALSE.');
  1780. }
  1781. /**
  1782. * Tests that the query string remains intact when adding JavaScript files
  1783. * that have query string parameters.
  1784. */
  1785. function testAddJsFileWithQueryString() {
  1786. $this->drupalGet('common-test/query-string');
  1787. $query_string = variable_get('css_js_query_string', '0');
  1788. $this->assertRaw(drupal_get_path('module', 'node') . '/node.js?' . $query_string, 'Query string was appended correctly to js.');
  1789. }
  1790. /**
  1791. * Tests that the set_has_js_cookie variable is reflected in Drupal.settings.
  1792. */
  1793. function testSetHasJsCookie() {
  1794. $this->drupalGet('');
  1795. $this->assertRaw('"setHasJsCookie":0', 'setHasJsCookie set to 0 by default.');
  1796. variable_set('set_has_js_cookie', TRUE);
  1797. $this->drupalGet('');
  1798. $this->assertRaw('"setHasJsCookie":1', 'setHasJsCookie set to 1 when set_has_js_cookie is set to TRUE.');
  1799. }
  1800. /**
  1801. * Resets static variables related to adding JavaScript to a page.
  1802. */
  1803. function resetStaticVariables() {
  1804. drupal_static_reset('drupal_add_js');
  1805. drupal_static_reset('drupal_add_library');
  1806. drupal_static_reset('drupal_get_library');
  1807. }
  1808. }
  1809. /**
  1810. * Tests for drupal_render().
  1811. */
  1812. class DrupalRenderTestCase extends DrupalWebTestCase {
  1813. public static function getInfo() {
  1814. return array(
  1815. 'name' => 'drupal_render()',
  1816. 'description' => 'Performs functional tests on drupal_render().',
  1817. 'group' => 'System',
  1818. );
  1819. }
  1820. function setUp() {
  1821. parent::setUp('common_test');
  1822. }
  1823. /**
  1824. * Tests the output drupal_render() for some elementary input values.
  1825. */
  1826. function testDrupalRenderBasics() {
  1827. $types = array(
  1828. array(
  1829. 'name' => 'null',
  1830. 'value' => NULL,
  1831. 'expected' => '',
  1832. ),
  1833. array(
  1834. 'name' => 'no value',
  1835. 'expected' => '',
  1836. ),
  1837. array(
  1838. 'name' => 'empty string',
  1839. 'value' => '',
  1840. 'expected' => '',
  1841. ),
  1842. array(
  1843. 'name' => 'not a render array',
  1844. 'value' => 'this is not an array',
  1845. 'expected' => '',
  1846. ),
  1847. array(
  1848. 'name' => 'no access',
  1849. 'value' => array(
  1850. '#markup' => 'foo',
  1851. '#access' => FALSE,
  1852. ),
  1853. 'expected' => '',
  1854. ),
  1855. array(
  1856. 'name' => 'previously printed',
  1857. 'value' => array(
  1858. '#markup' => 'foo',
  1859. '#printed' => TRUE,
  1860. ),
  1861. 'expected' => '',
  1862. ),
  1863. array(
  1864. 'name' => 'printed in prerender',
  1865. 'value' => array(
  1866. '#markup' => 'foo',
  1867. '#pre_render' => array('common_test_drupal_render_printing_pre_render'),
  1868. ),
  1869. 'expected' => '',
  1870. ),
  1871. array(
  1872. 'name' => 'basic renderable array',
  1873. 'value' => array('#markup' => 'foo'),
  1874. 'expected' => 'foo',
  1875. ),
  1876. );
  1877. foreach($types as $type) {
  1878. $this->assertIdentical(drupal_render($type['value']), $type['expected'], '"' . $type['name'] . '" input rendered correctly by drupal_render().');
  1879. }
  1880. }
  1881. /**
  1882. * Test sorting by weight.
  1883. */
  1884. function testDrupalRenderSorting() {
  1885. $first = $this->randomName();
  1886. $second = $this->randomName();
  1887. // Build an array with '#weight' set for each element.
  1888. $elements = array(
  1889. 'second' => array(
  1890. '#weight' => 10,
  1891. '#markup' => $second,
  1892. ),
  1893. 'first' => array(
  1894. '#weight' => 0,
  1895. '#markup' => $first,
  1896. ),
  1897. );
  1898. $output = drupal_render($elements);
  1899. // The lowest weight element should appear last in $output.
  1900. $this->assertTrue(strpos($output, $second) > strpos($output, $first), 'Elements were sorted correctly by weight.');
  1901. // Confirm that the $elements array has '#sorted' set to TRUE.
  1902. $this->assertTrue($elements['#sorted'], "'#sorted' => TRUE was added to the array");
  1903. // Pass $elements through element_children() and ensure it remains
  1904. // sorted in the correct order. drupal_render() will return an empty string
  1905. // if used on the same array in the same request.
  1906. $children = element_children($elements);
  1907. $this->assertTrue(array_shift($children) == 'first', 'Child found in the correct order.');
  1908. $this->assertTrue(array_shift($children) == 'second', 'Child found in the correct order.');
  1909. // The same array structure again, but with #sorted set to TRUE.
  1910. $elements = array(
  1911. 'second' => array(
  1912. '#weight' => 10,
  1913. '#markup' => $second,
  1914. ),
  1915. 'first' => array(
  1916. '#weight' => 0,
  1917. '#markup' => $first,
  1918. ),
  1919. '#sorted' => TRUE,
  1920. );
  1921. $output = drupal_render($elements);
  1922. // The elements should appear in output in the same order as the array.
  1923. $this->assertTrue(strpos($output, $second) < strpos($output, $first), 'Elements were not sorted.');
  1924. // The order of children with same weight should be preserved.
  1925. $element_mixed_weight = array(
  1926. 'child5' => array('#weight' => 10),
  1927. 'child3' => array('#weight' => -10),
  1928. 'child1' => array(),
  1929. 'child4' => array('#weight' => 10),
  1930. 'child2' => array(),
  1931. 'child6' => array('#weight' => 10),
  1932. 'child9' => array(),
  1933. 'child8' => array('#weight' => 10),
  1934. 'child7' => array(),
  1935. );
  1936. $expected = array(
  1937. 'child3',
  1938. 'child1',
  1939. 'child2',
  1940. 'child9',
  1941. 'child7',
  1942. 'child5',
  1943. 'child4',
  1944. 'child6',
  1945. 'child8',
  1946. );
  1947. $this->assertEqual($expected, element_children($element_mixed_weight, TRUE), 'Order of elements with the same weight is preserved.');
  1948. }
  1949. /**
  1950. * Test #attached functionality in children elements.
  1951. */
  1952. function testDrupalRenderChildrenAttached() {
  1953. // The cache system is turned off for POST requests.
  1954. $request_method = $_SERVER['REQUEST_METHOD'];
  1955. $_SERVER['REQUEST_METHOD'] = 'GET';
  1956. // Create an element with a child and subchild. Each element loads a
  1957. // different JavaScript file using #attached.
  1958. $parent_js = drupal_get_path('module', 'user') . '/user.js';
  1959. $child_js = drupal_get_path('module', 'forum') . '/forum.js';
  1960. $subchild_js = drupal_get_path('module', 'book') . '/book.js';
  1961. $element = array(
  1962. '#type' => 'fieldset',
  1963. '#cache' => array(
  1964. 'keys' => array('simpletest', 'drupal_render', 'children_attached'),
  1965. ),
  1966. '#attached' => array('js' => array($parent_js)),
  1967. '#title' => 'Parent',
  1968. );
  1969. $element['child'] = array(
  1970. '#type' => 'fieldset',
  1971. '#attached' => array('js' => array($child_js)),
  1972. '#title' => 'Child',
  1973. );
  1974. $element['child']['subchild'] = array(
  1975. '#attached' => array('js' => array($subchild_js)),
  1976. '#markup' => 'Subchild',
  1977. );
  1978. // Render the element and verify the presence of #attached JavaScript.
  1979. drupal_render($element);
  1980. $scripts = drupal_get_js();
  1981. $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included.');
  1982. $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included.');
  1983. $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included.');
  1984. // Load the element from cache and verify the presence of the #attached
  1985. // JavaScript.
  1986. drupal_static_reset('drupal_add_js');
  1987. $this->assertTrue(drupal_render_cache_get($element), 'The element was retrieved from cache.');
  1988. $scripts = drupal_get_js();
  1989. $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included when loading from cache.');
  1990. $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included when loading from cache.');
  1991. $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included when loading from cache.');
  1992. $_SERVER['REQUEST_METHOD'] = $request_method;
  1993. }
  1994. /**
  1995. * Test passing arguments to the theme function.
  1996. */
  1997. function testDrupalRenderThemeArguments() {
  1998. $element = array(
  1999. '#theme' => 'common_test_foo',
  2000. );
  2001. // Test that defaults work.
  2002. $this->assertEqual(drupal_render($element), 'foobar', 'Defaults work');
  2003. $element = array(
  2004. '#theme' => 'common_test_foo',
  2005. '#foo' => $this->randomName(),
  2006. '#bar' => $this->randomName(),
  2007. );
  2008. // Test that passing arguments to the theme function works.
  2009. $this->assertEqual(drupal_render($element), $element['#foo'] . $element['#bar'], 'Passing arguments to theme functions works');
  2010. }
  2011. /**
  2012. * Test rendering form elements without passing through form_builder().
  2013. */
  2014. function testDrupalRenderFormElements() {
  2015. // Define a series of form elements.
  2016. $element = array(
  2017. '#type' => 'button',
  2018. '#value' => $this->randomName(),
  2019. );
  2020. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'submit'));
  2021. $element = array(
  2022. '#type' => 'textfield',
  2023. '#title' => $this->randomName(),
  2024. '#value' => $this->randomName(),
  2025. );
  2026. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'text'));
  2027. $element = array(
  2028. '#type' => 'password',
  2029. '#title' => $this->randomName(),
  2030. );
  2031. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'password'));
  2032. $element = array(
  2033. '#type' => 'textarea',
  2034. '#title' => $this->randomName(),
  2035. '#value' => $this->randomName(),
  2036. );
  2037. $this->assertRenderedElement($element, '//textarea');
  2038. $element = array(
  2039. '#type' => 'radio',
  2040. '#title' => $this->randomName(),
  2041. '#value' => FALSE,
  2042. );
  2043. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'radio'));
  2044. $element = array(
  2045. '#type' => 'checkbox',
  2046. '#title' => $this->randomName(),
  2047. );
  2048. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'checkbox'));
  2049. $element = array(
  2050. '#type' => 'select',
  2051. '#title' => $this->randomName(),
  2052. '#options' => array(
  2053. 0 => $this->randomName(),
  2054. 1 => $this->randomName(),
  2055. ),
  2056. );
  2057. $this->assertRenderedElement($element, '//select');
  2058. $element = array(
  2059. '#type' => 'file',
  2060. '#title' => $this->randomName(),
  2061. );
  2062. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'file'));
  2063. $element = array(
  2064. '#type' => 'item',
  2065. '#title' => $this->randomName(),
  2066. '#markup' => $this->randomName(),
  2067. );
  2068. $this->assertRenderedElement($element, '//div[contains(@class, :class) and contains(., :markup)]/label[contains(., :label)]', array(
  2069. ':class' => 'form-type-item',
  2070. ':markup' => $element['#markup'],
  2071. ':label' => $element['#title'],
  2072. ));
  2073. $element = array(
  2074. '#type' => 'hidden',
  2075. '#title' => $this->randomName(),
  2076. '#value' => $this->randomName(),
  2077. );
  2078. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'hidden'));
  2079. $element = array(
  2080. '#type' => 'link',
  2081. '#title' => $this->randomName(),
  2082. '#href' => $this->randomName(),
  2083. '#options' => array(
  2084. 'absolute' => TRUE,
  2085. ),
  2086. );
  2087. $this->assertRenderedElement($element, '//a[@href=:href and contains(., :title)]', array(
  2088. ':href' => url($element['#href'], array('absolute' => TRUE)),
  2089. ':title' => $element['#title'],
  2090. ));
  2091. $element = array(
  2092. '#type' => 'fieldset',
  2093. '#title' => $this->randomName(),
  2094. );
  2095. $this->assertRenderedElement($element, '//fieldset/legend[contains(., :title)]', array(
  2096. ':title' => $element['#title'],
  2097. ));
  2098. $element['item'] = array(
  2099. '#type' => 'item',
  2100. '#title' => $this->randomName(),
  2101. '#markup' => $this->randomName(),
  2102. );
  2103. $this->assertRenderedElement($element, '//fieldset/div/div[contains(@class, :class) and contains(., :markup)]', array(
  2104. ':class' => 'form-type-item',
  2105. ':markup' => $element['item']['#markup'],
  2106. ));
  2107. }
  2108. protected function assertRenderedElement(array $element, $xpath, array $xpath_args = array()) {
  2109. $original_element = $element;
  2110. $this->drupalSetContent(drupal_render($element));
  2111. $this->verbose('<pre>' . check_plain(var_export($original_element, TRUE)) . '</pre>'
  2112. . '<pre>' . check_plain(var_export($element, TRUE)) . '</pre>'
  2113. . '<hr />' . $this->drupalGetContent()
  2114. );
  2115. // @see DrupalWebTestCase::xpath()
  2116. $xpath = $this->buildXPathQuery($xpath, $xpath_args);
  2117. $element += array('#value' => NULL);
  2118. $this->assertFieldByXPath($xpath, $element['#value'], format_string('#type @type was properly rendered.', array(
  2119. '@type' => var_export($element['#type'], TRUE),
  2120. )));
  2121. }
  2122. /**
  2123. * Tests caching of render items.
  2124. */
  2125. function testDrupalRenderCache() {
  2126. // Force a request via GET.
  2127. $request_method = $_SERVER['REQUEST_METHOD'];
  2128. $_SERVER['REQUEST_METHOD'] = 'GET';
  2129. // Create an empty element.
  2130. $test_element = array(
  2131. '#cache' => array(
  2132. 'cid' => 'render_cache_test',
  2133. ),
  2134. '#markup' => '',
  2135. );
  2136. // Render the element and confirm that it goes through the rendering
  2137. // process (which will set $element['#printed']).
  2138. $element = $test_element;
  2139. drupal_render($element);
  2140. $this->assertTrue(isset($element['#printed']), 'No cache hit');
  2141. // Render the element again and confirm that it is retrieved from the cache
  2142. // instead (so $element['#printed'] will not be set).
  2143. $element = $test_element;
  2144. drupal_render($element);
  2145. $this->assertFalse(isset($element['#printed']), 'Cache hit');
  2146. // Test that user 1 does not share the cache with other users who have the
  2147. // same roles, even when DRUPAL_CACHE_PER_ROLE is used.
  2148. $user1 = user_load(1);
  2149. $first_authenticated_user = $this->drupalCreateUser();
  2150. $second_authenticated_user = $this->drupalCreateUser();
  2151. $user1->roles = array_intersect_key($user1->roles, array(DRUPAL_AUTHENTICATED_RID => TRUE));
  2152. user_save($user1);
  2153. // Load all the accounts again, to make sure we have complete account
  2154. // objects.
  2155. $user1 = user_load(1);
  2156. $first_authenticated_user = user_load($first_authenticated_user->uid);
  2157. $second_authenticated_user = user_load($second_authenticated_user->uid);
  2158. $this->assertEqual($user1->roles, $first_authenticated_user->roles, 'User 1 has the same roles as an authenticated user.');
  2159. // Impersonate user 1 and render content that only user 1 should have
  2160. // permission to see.
  2161. $original_user = $GLOBALS['user'];
  2162. $original_session_state = drupal_save_session();
  2163. drupal_save_session(FALSE);
  2164. $GLOBALS['user'] = $user1;
  2165. $test_element = array(
  2166. '#cache' => array(
  2167. 'keys' => array('test'),
  2168. 'granularity' => DRUPAL_CACHE_PER_ROLE,
  2169. ),
  2170. );
  2171. $element = $test_element;
  2172. $element['#markup'] = 'content for user 1';
  2173. $output = drupal_render($element);
  2174. $this->assertEqual($output, 'content for user 1');
  2175. // Verify the cache is working by rendering the same element but with
  2176. // different markup passed in; the result should be the same.
  2177. $element = $test_element;
  2178. $element['#markup'] = 'should not be used';
  2179. $output = drupal_render($element);
  2180. $this->assertEqual($output, 'content for user 1');
  2181. // Verify that the first authenticated user does not see the same content
  2182. // as user 1.
  2183. $GLOBALS['user'] = $first_authenticated_user;
  2184. $element = $test_element;
  2185. $element['#markup'] = 'content for authenticated users';
  2186. $output = drupal_render($element);
  2187. $this->assertEqual($output, 'content for authenticated users');
  2188. // Verify that the second authenticated user shares the cache with the
  2189. // first authenticated user.
  2190. $GLOBALS['user'] = $second_authenticated_user;
  2191. $element = $test_element;
  2192. $element['#markup'] = 'should not be used';
  2193. $output = drupal_render($element);
  2194. $this->assertEqual($output, 'content for authenticated users');
  2195. // Restore the original logged-in user.
  2196. $GLOBALS['user'] = $original_user;
  2197. drupal_save_session($original_session_state);
  2198. // Restore the previous request method.
  2199. $_SERVER['REQUEST_METHOD'] = $request_method;
  2200. }
  2201. }
  2202. /**
  2203. * Test for valid_url().
  2204. */
  2205. class ValidUrlTestCase extends DrupalUnitTestCase {
  2206. public static function getInfo() {
  2207. return array(
  2208. 'name' => 'Valid URL',
  2209. 'description' => "Performs tests on Drupal's valid URL function.",
  2210. 'group' => 'System'
  2211. );
  2212. }
  2213. /**
  2214. * Test valid absolute URLs.
  2215. */
  2216. function testValidAbsolute() {
  2217. $url_schemes = array('http', 'https', 'ftp');
  2218. $valid_absolute_urls = array(
  2219. 'example.com',
  2220. 'www.example.com',
  2221. 'ex-ample.com',
  2222. '3xampl3.com',
  2223. 'example.com/paren(the)sis',
  2224. 'example.com/index.html#pagetop',
  2225. 'example.com:8080',
  2226. 'subdomain.example.com',
  2227. 'example.com/index.php?q=node',
  2228. 'example.com/index.php?q=node&param=false',
  2229. 'user@www.example.com',
  2230. 'user:pass@www.example.com:8080/login.php?do=login&style=%23#pagetop',
  2231. '127.0.0.1',
  2232. 'example.org?',
  2233. 'john%20doe:secret:foo@example.org/',
  2234. 'example.org/~,$\'*;',
  2235. 'caf%C3%A9.example.org',
  2236. '[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
  2237. );
  2238. foreach ($url_schemes as $scheme) {
  2239. foreach ($valid_absolute_urls as $url) {
  2240. $test_url = $scheme . '://' . $url;
  2241. $valid_url = valid_url($test_url, TRUE);
  2242. $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
  2243. }
  2244. }
  2245. }
  2246. /**
  2247. * Test invalid absolute URLs.
  2248. */
  2249. function testInvalidAbsolute() {
  2250. $url_schemes = array('http', 'https', 'ftp');
  2251. $invalid_ablosule_urls = array(
  2252. '',
  2253. 'ex!ample.com',
  2254. 'ex%ample.com',
  2255. );
  2256. foreach ($url_schemes as $scheme) {
  2257. foreach ($invalid_ablosule_urls as $url) {
  2258. $test_url = $scheme . '://' . $url;
  2259. $valid_url = valid_url($test_url, TRUE);
  2260. $this->assertFalse($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
  2261. }
  2262. }
  2263. }
  2264. /**
  2265. * Test valid relative URLs.
  2266. */
  2267. function testValidRelative() {
  2268. $valid_relative_urls = array(
  2269. 'paren(the)sis',
  2270. 'index.html#pagetop',
  2271. 'index.php?q=node',
  2272. 'index.php?q=node&param=false',
  2273. 'login.php?do=login&style=%23#pagetop',
  2274. );
  2275. foreach (array('', '/') as $front) {
  2276. foreach ($valid_relative_urls as $url) {
  2277. $test_url = $front . $url;
  2278. $valid_url = valid_url($test_url);
  2279. $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
  2280. }
  2281. }
  2282. }
  2283. /**
  2284. * Test invalid relative URLs.
  2285. */
  2286. function testInvalidRelative() {
  2287. $invalid_relative_urls = array(
  2288. 'ex^mple',
  2289. 'example<>',
  2290. 'ex%ample',
  2291. );
  2292. foreach (array('', '/') as $front) {
  2293. foreach ($invalid_relative_urls as $url) {
  2294. $test_url = $front . $url;
  2295. $valid_url = valid_url($test_url);
  2296. $this->assertFALSE($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
  2297. }
  2298. }
  2299. }
  2300. }
  2301. /**
  2302. * Tests for CRUD API functions.
  2303. */
  2304. class DrupalDataApiTest extends DrupalWebTestCase {
  2305. public static function getInfo() {
  2306. return array(
  2307. 'name' => 'Data API functions',
  2308. 'description' => 'Tests the performance of CRUD APIs.',
  2309. 'group' => 'System',
  2310. );
  2311. }
  2312. function setUp() {
  2313. parent::setUp('database_test');
  2314. }
  2315. /**
  2316. * Test the drupal_write_record() API function.
  2317. */
  2318. function testDrupalWriteRecord() {
  2319. // Insert a record - no columns allow NULL values.
  2320. $person = new stdClass();
  2321. $person->name = 'John';
  2322. $person->unknown_column = 123;
  2323. $insert_result = drupal_write_record('test', $person);
  2324. $this->assertTrue($insert_result == SAVED_NEW, 'Correct value returned when a record is inserted with drupal_write_record() for a table with a single-field primary key.');
  2325. $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
  2326. $this->assertIdentical($person->age, 0, 'Age field set to default value.');
  2327. $this->assertIdentical($person->job, 'Undefined', 'Job field set to default value.');
  2328. // Verify that the record was inserted.
  2329. $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2330. $this->assertIdentical($result->name, 'John', 'Name field set.');
  2331. $this->assertIdentical($result->age, '0', 'Age field set to default value.');
  2332. $this->assertIdentical($result->job, 'Undefined', 'Job field set to default value.');
  2333. $this->assertFalse(isset($result->unknown_column), 'Unknown column was ignored.');
  2334. // Update the newly created record.
  2335. $person->name = 'Peter';
  2336. $person->age = 27;
  2337. $person->job = NULL;
  2338. $update_result = drupal_write_record('test', $person, array('id'));
  2339. $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a record updated with drupal_write_record() for table with single-field primary key.');
  2340. // Verify that the record was updated.
  2341. $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2342. $this->assertIdentical($result->name, 'Peter', 'Name field set.');
  2343. $this->assertIdentical($result->age, '27', 'Age field set.');
  2344. $this->assertIdentical($result->job, '', 'Job field set and cast to string.');
  2345. // Try to insert NULL in columns that does not allow this.
  2346. $person = new stdClass();
  2347. $person->name = 'Ringo';
  2348. $person->age = NULL;
  2349. $person->job = NULL;
  2350. $insert_result = drupal_write_record('test', $person);
  2351. $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
  2352. $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2353. $this->assertIdentical($result->name, 'Ringo', 'Name field set.');
  2354. $this->assertIdentical($result->age, '0', 'Age field set.');
  2355. $this->assertIdentical($result->job, '', 'Job field set.');
  2356. // Insert a record - the "age" column allows NULL.
  2357. $person = new stdClass();
  2358. $person->name = 'Paul';
  2359. $person->age = NULL;
  2360. $insert_result = drupal_write_record('test_null', $person);
  2361. $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
  2362. $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2363. $this->assertIdentical($result->name, 'Paul', 'Name field set.');
  2364. $this->assertIdentical($result->age, NULL, 'Age field set.');
  2365. // Insert a record - do not specify the value of a column that allows NULL.
  2366. $person = new stdClass();
  2367. $person->name = 'Meredith';
  2368. $insert_result = drupal_write_record('test_null', $person);
  2369. $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
  2370. $this->assertIdentical($person->age, 0, 'Age field set to default value.');
  2371. $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2372. $this->assertIdentical($result->name, 'Meredith', 'Name field set.');
  2373. $this->assertIdentical($result->age, '0', 'Age field set to default value.');
  2374. // Update the newly created record.
  2375. $person->name = 'Mary';
  2376. $person->age = NULL;
  2377. $update_result = drupal_write_record('test_null', $person, array('id'));
  2378. $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2379. $this->assertIdentical($result->name, 'Mary', 'Name field set.');
  2380. $this->assertIdentical($result->age, NULL, 'Age field set.');
  2381. // Insert a record - the "data" column should be serialized.
  2382. $person = new stdClass();
  2383. $person->name = 'Dave';
  2384. $update_result = drupal_write_record('test_serialized', $person);
  2385. $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2386. $this->assertIdentical($result->name, 'Dave', 'Name field set.');
  2387. $this->assertIdentical($result->info, NULL, 'Info field set.');
  2388. $person->info = array();
  2389. $update_result = drupal_write_record('test_serialized', $person, array('id'));
  2390. $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2391. $this->assertIdentical(unserialize($result->info), array(), 'Info field updated.');
  2392. // Update the serialized record.
  2393. $data = array('foo' => 'bar', 1 => 2, 'empty' => '', 'null' => NULL);
  2394. $person->info = $data;
  2395. $update_result = drupal_write_record('test_serialized', $person, array('id'));
  2396. $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2397. $this->assertIdentical(unserialize($result->info), $data, 'Info field updated.');
  2398. // Run an update query where no field values are changed. The database
  2399. // layer should return zero for number of affected rows, but
  2400. // db_write_record() should still return SAVED_UPDATED.
  2401. $update_result = drupal_write_record('test_null', $person, array('id'));
  2402. $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a valid update is run without changing any values.');
  2403. // Insert an object record for a table with a multi-field primary key.
  2404. $node_access = new stdClass();
  2405. $node_access->nid = mt_rand();
  2406. $node_access->gid = mt_rand();
  2407. $node_access->realm = $this->randomName();
  2408. $insert_result = drupal_write_record('node_access', $node_access);
  2409. $this->assertTrue($insert_result == SAVED_NEW, 'Correct value returned when a record is inserted with drupal_write_record() for a table with a multi-field primary key.');
  2410. // Update the record.
  2411. $update_result = drupal_write_record('node_access', $node_access, array('nid', 'gid', 'realm'));
  2412. $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a record is updated with drupal_write_record() for a table with a multi-field primary key.');
  2413. // Insert a new record to the table with a database specific data type.
  2414. $person = new stdClass();
  2415. $person->age = 25;
  2416. $insert_result = drupal_write_record('test_db_specific_datatype', $person);
  2417. $this->assertTrue($insert_result == SAVED_NEW, 'Correct value returned when a record is inserted with drupal_write_record() for a table with a database specific data type.');
  2418. }
  2419. }
  2420. /**
  2421. * Tests Simpletest error and exception collector.
  2422. */
  2423. class DrupalErrorCollectionUnitTest extends DrupalWebTestCase {
  2424. /**
  2425. * Errors triggered during the test.
  2426. *
  2427. * Errors are intercepted by the overriden implementation
  2428. * of DrupalWebTestCase::error below.
  2429. *
  2430. * @var Array
  2431. */
  2432. protected $collectedErrors = array();
  2433. public static function getInfo() {
  2434. return array(
  2435. 'name' => 'SimpleTest error collector',
  2436. 'description' => 'Performs tests on the Simpletest error and exception collector.',
  2437. 'group' => 'SimpleTest',
  2438. );
  2439. }
  2440. function setUp() {
  2441. parent::setUp('system_test', 'error_test');
  2442. }
  2443. /**
  2444. * Test that simpletest collects errors from the tested site.
  2445. */
  2446. function testErrorCollect() {
  2447. $this->collectedErrors = array();
  2448. $this->drupalGet('error-test/generate-warnings-with-report');
  2449. $this->assertEqual(count($this->collectedErrors), 3, 'Three errors were collected');
  2450. if (count($this->collectedErrors) == 3) {
  2451. $this->assertError($this->collectedErrors[0], 'Notice', 'error_test_generate_warnings()', 'error_test.module', 'Object of class stdClass could not be converted to int');
  2452. $this->assertError($this->collectedErrors[1], 'Warning', 'error_test_generate_warnings()', 'error_test.module', \PHP_VERSION_ID < 80000 ? 'Invalid argument supplied for foreach()' : 'foreach() argument must be of type array|object, string given');
  2453. $this->assertError($this->collectedErrors[2], 'User warning', 'error_test_generate_warnings()', 'error_test.module', 'Drupal is awesome');
  2454. }
  2455. else {
  2456. // Give back the errors to the log report.
  2457. foreach ($this->collectedErrors as $error) {
  2458. parent::error($error['message'], $error['group'], $error['caller']);
  2459. }
  2460. }
  2461. }
  2462. /**
  2463. * Error handler that collects errors in an array.
  2464. *
  2465. * This test class is trying to verify that simpletest correctly sees errors
  2466. * and warnings. However, it can't generate errors and warnings that
  2467. * propagate up to the testing framework itself, or these tests would always
  2468. * fail. So, this special copy of error() doesn't propagate the errors up
  2469. * the class hierarchy. It just stuffs them into a protected collectedErrors
  2470. * array for various assertions to inspect.
  2471. */
  2472. protected function error($message = '', $group = 'Other', array $caller = NULL) {
  2473. // Due to a WTF elsewhere, simpletest treats debug() and verbose()
  2474. // messages as if they were an 'error'. But, we don't want to collect
  2475. // those here. This function just wants to collect the real errors (PHP
  2476. // notices, PHP fatal errors, etc.), and let all the 'errors' from the
  2477. // 'User notice' group bubble up to the parent classes to be handled (and
  2478. // eventually displayed) as normal.
  2479. if ($group == 'User notice') {
  2480. parent::error($message, $group, $caller);
  2481. }
  2482. // Everything else should be collected but not propagated.
  2483. else {
  2484. $this->collectedErrors[] = array(
  2485. 'message' => $message,
  2486. 'group' => $group,
  2487. 'caller' => $caller
  2488. );
  2489. }
  2490. }
  2491. /**
  2492. * Assert that a collected error matches what we are expecting.
  2493. */
  2494. function assertError($error, $group, $function, $file, $message = NULL) {
  2495. $this->assertEqual($error['group'], $group, format_string("Group was %group", array('%group' => $group)));
  2496. $this->assertEqual($error['caller']['function'], $function, format_string("Function was %function", array('%function' => $function)));
  2497. $this->assertEqual(drupal_basename($error['caller']['file']), $file, format_string("File was %file", array('%file' => $file)));
  2498. if (isset($message)) {
  2499. $this->assertEqual($error['message'], $message, format_string("Message was %message", array('%message' => $message)));
  2500. }
  2501. }
  2502. }
  2503. /**
  2504. * Test the drupal_parse_info_file() API function.
  2505. */
  2506. class ParseInfoFilesTestCase extends DrupalUnitTestCase {
  2507. public static function getInfo() {
  2508. return array(
  2509. 'name' => 'Parsing .info files',
  2510. 'description' => 'Tests parsing .info files.',
  2511. 'group' => 'System',
  2512. );
  2513. }
  2514. /**
  2515. * Parse an example .info file an verify the results.
  2516. */
  2517. function testParseInfoFile() {
  2518. $info_values = drupal_parse_info_file(drupal_get_path('module', 'simpletest') . '/tests/common_test_info.txt');
  2519. $this->assertEqual($info_values['simple_string'], 'A simple string', 'Simple string value was parsed correctly.', 'System');
  2520. $this->assertEqual($info_values['simple_constant'], WATCHDOG_INFO, 'Constant value was parsed correctly.', 'System');
  2521. $this->assertEqual($info_values['double_colon'], 'dummyClassName::', 'Value containing double-colon was parsed correctly.', 'System');
  2522. }
  2523. }
  2524. /**
  2525. * Tests for the drupal_system_listing() function.
  2526. */
  2527. class DrupalSystemListingTestCase extends DrupalWebTestCase {
  2528. /**
  2529. * Use the testing profile; this is needed for testDirectoryPrecedence().
  2530. */
  2531. protected $profile = 'testing';
  2532. public static function getInfo() {
  2533. return array(
  2534. 'name' => 'Drupal system listing',
  2535. 'description' => 'Tests the mechanism for scanning system directories in drupal_system_listing().',
  2536. 'group' => 'System',
  2537. );
  2538. }
  2539. /**
  2540. * Test that files in different directories take precedence as expected.
  2541. */
  2542. function testDirectoryPrecedence() {
  2543. // Define the module files we will search for, and the directory precedence
  2544. // we expect.
  2545. $expected_directories = array(
  2546. // When the copy of the module in the profile directory is incompatible
  2547. // with Drupal core, the copy in the core modules directory takes
  2548. // precedence.
  2549. 'drupal_system_listing_incompatible_test' => array(
  2550. 'modules/simpletest/tests',
  2551. 'profiles/testing/modules',
  2552. ),
  2553. // When both copies of the module are compatible with Drupal core, the
  2554. // copy in the profile directory takes precedence.
  2555. 'drupal_system_listing_compatible_test' => array(
  2556. 'profiles/testing/modules',
  2557. 'modules/simpletest/tests',
  2558. ),
  2559. );
  2560. // This test relies on two versions of the same module existing in
  2561. // different places in the filesystem. Without that, the test has no
  2562. // meaning, so assert their presence first.
  2563. foreach ($expected_directories as $module => $directories) {
  2564. foreach ($directories as $directory) {
  2565. $filename = "$directory/$module/$module.module";
  2566. $this->assertTrue(file_exists(DRUPAL_ROOT . '/' . $filename), format_string('@filename exists.', array('@filename' => $filename)));
  2567. }
  2568. }
  2569. // Now scan the directories and check that the files take precedence as
  2570. // expected.
  2571. $files = drupal_system_listing('/\.module$/', 'modules', 'name', 1);
  2572. foreach ($expected_directories as $module => $directories) {
  2573. $expected_directory = array_shift($directories);
  2574. $expected_filename = "$expected_directory/$module/$module.module";
  2575. $this->assertEqual($files[$module]->uri, $expected_filename, format_string('Module @module was found at @filename.', array('@module' => $module, '@filename' => $expected_filename)));
  2576. }
  2577. }
  2578. }
  2579. /**
  2580. * Tests for the format_date() function.
  2581. */
  2582. class FormatDateUnitTest extends DrupalWebTestCase {
  2583. protected $admin_user;
  2584. /**
  2585. * Arbitrary langcode for a custom language.
  2586. */
  2587. const LANGCODE = 'xx';
  2588. public static function getInfo() {
  2589. return array(
  2590. 'name' => 'Format date',
  2591. 'description' => 'Test the format_date() function.',
  2592. 'group' => 'System',
  2593. );
  2594. }
  2595. function setUp() {
  2596. parent::setUp('locale');
  2597. variable_set('configurable_timezones', 1);
  2598. variable_set('date_format_long', 'l, j. F Y - G:i');
  2599. variable_set('date_format_medium', 'j. F Y - G:i');
  2600. variable_set('date_format_short', 'Y M j - g:ia');
  2601. variable_set('locale_custom_strings_' . self::LANGCODE, array(
  2602. '' => array('Sunday' => 'domingo'),
  2603. 'Long month name' => array('March' => 'marzo'),
  2604. ));
  2605. $this->refreshVariables();
  2606. }
  2607. /**
  2608. * Test admin-defined formats in format_date().
  2609. */
  2610. function testAdminDefinedFormatDate() {
  2611. // Create an admin user.
  2612. $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
  2613. $this->drupalLogin($this->admin_user);
  2614. // Add new date format.
  2615. $admin_date_format = 'j M y';
  2616. $edit = array('date_format' => $admin_date_format);
  2617. $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, 'Add format');
  2618. // Add a new date format which just differs in the case.
  2619. $admin_date_format_uppercase = 'j M Y';
  2620. $edit = array('date_format' => $admin_date_format_uppercase);
  2621. $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
  2622. $this->assertText(t('Custom date format added.'));
  2623. // Add new date type.
  2624. $edit = array(
  2625. 'date_type' => 'Example Style',
  2626. 'machine_name' => 'example_style',
  2627. 'date_format' => $admin_date_format,
  2628. );
  2629. $this->drupalPost('admin/config/regional/date-time/types/add', $edit, 'Add date type');
  2630. // Add a second date format with a different case than the first.
  2631. $edit = array(
  2632. 'machine_name' => 'example_style_uppercase',
  2633. 'date_type' => 'Example Style Uppercase',
  2634. 'date_format' => $admin_date_format_uppercase,
  2635. );
  2636. $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
  2637. $this->assertText(t('New date type added successfully.'));
  2638. $timestamp = strtotime('2007-03-10T00:00:00+00:00');
  2639. $this->assertIdentical(format_date($timestamp, 'example_style', '', 'America/Los_Angeles'), '9 Mar 07', 'Test format_date() using an admin-defined date type.');
  2640. $this->assertIdentical(format_date($timestamp, 'example_style_uppercase', '', 'America/Los_Angeles'), '9 Mar 2007', 'Test format_date() using an admin-defined date type with different case.');
  2641. $this->assertIdentical(format_date($timestamp, 'undefined_style'), format_date($timestamp, 'medium'), 'Test format_date() defaulting to medium when $type not found.');
  2642. }
  2643. /**
  2644. * Tests for the format_date() function.
  2645. */
  2646. function testFormatDate() {
  2647. global $user, $language;
  2648. $timestamp = strtotime('2007-03-26T00:00:00+00:00');
  2649. $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', 'en'), 'Sunday, 25-Mar-07 17:00:00 PDT', 'Test all parameters.');
  2650. $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'domingo, 25-Mar-07 17:00:00 PDT', 'Test translated format.');
  2651. $this->assertIdentical(format_date($timestamp, 'custom', '\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'l, 25-Mar-07 17:00:00 PDT', 'Test an escaped format string.');
  2652. $this->assertIdentical(format_date($timestamp, 'custom', '\\\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), '\\domingo, 25-Mar-07 17:00:00 PDT', 'Test format containing backslash character.');
  2653. $this->assertIdentical(format_date($timestamp, 'custom', '\\\\\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), '\\l, 25-Mar-07 17:00:00 PDT', 'Test format containing backslash followed by escaped format string.');
  2654. $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'Europe/London', 'en'), 'Monday, 26-Mar-07 01:00:00 BST', 'Test a different time zone.');
  2655. // Create an admin user and add Spanish language.
  2656. $admin_user = $this->drupalCreateUser(array('administer languages'));
  2657. $this->drupalLogin($admin_user);
  2658. $edit = array(
  2659. 'langcode' => self::LANGCODE,
  2660. 'name' => self::LANGCODE,
  2661. 'native' => self::LANGCODE,
  2662. 'direction' => LANGUAGE_LTR,
  2663. 'prefix' => self::LANGCODE,
  2664. );
  2665. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  2666. // Create a test user to carry out the tests.
  2667. $test_user = $this->drupalCreateUser();
  2668. $this->drupalLogin($test_user);
  2669. $edit = array('language' => self::LANGCODE, 'mail' => $test_user->mail, 'timezone' => 'America/Los_Angeles');
  2670. $this->drupalPost('user/' . $test_user->uid . '/edit', $edit, t('Save'));
  2671. // Disable session saving as we are about to modify the global $user.
  2672. drupal_save_session(FALSE);
  2673. // Save the original user and language and then replace it with the test user and language.
  2674. $real_user = $user;
  2675. $user = user_load($test_user->uid, TRUE);
  2676. $real_language = $language->language;
  2677. $language->language = $user->language;
  2678. // Simulate a Drupal bootstrap with the logged-in user.
  2679. date_default_timezone_set(drupal_get_user_timezone());
  2680. $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', 'en'), 'Sunday, 25-Mar-07 17:00:00 PDT', 'Test a different language.');
  2681. $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'Europe/London'), 'Monday, 26-Mar-07 01:00:00 BST', 'Test a different time zone.');
  2682. $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T'), 'domingo, 25-Mar-07 17:00:00 PDT', 'Test custom date format.');
  2683. $this->assertIdentical(format_date($timestamp, 'long'), 'domingo, 25. marzo 2007 - 17:00', 'Test long date format.');
  2684. $this->assertIdentical(format_date($timestamp, 'medium'), '25. marzo 2007 - 17:00', 'Test medium date format.');
  2685. $this->assertIdentical(format_date($timestamp, 'short'), '2007 Mar 25 - 5:00pm', 'Test short date format.');
  2686. $this->assertIdentical(format_date($timestamp), '25. marzo 2007 - 17:00', 'Test default date format.');
  2687. // Restore the original user and language, and enable session saving.
  2688. $user = $real_user;
  2689. $language->language = $real_language;
  2690. // Restore default time zone.
  2691. date_default_timezone_set(drupal_get_user_timezone());
  2692. drupal_save_session(TRUE);
  2693. }
  2694. }
  2695. /**
  2696. * Tests for the format_date() function.
  2697. */
  2698. class DrupalAttributesUnitTest extends DrupalUnitTestCase {
  2699. public static function getInfo() {
  2700. return array(
  2701. 'name' => 'HTML Attributes',
  2702. 'description' => 'Perform unit tests on the drupal_attributes() function.',
  2703. 'group' => 'System',
  2704. );
  2705. }
  2706. /**
  2707. * Tests that drupal_html_class() cleans the class name properly.
  2708. */
  2709. function testDrupalAttributes() {
  2710. // Verify that special characters are HTML encoded.
  2711. $this->assertIdentical(drupal_attributes(array('title' => '&"\'<>')), ' title="&amp;&quot;&#039;&lt;&gt;"', 'HTML encode attribute values.');
  2712. // Verify multi-value attributes are concatenated with spaces.
  2713. $attributes = array('class' => array('first', 'last'));
  2714. $this->assertIdentical(drupal_attributes(array('class' => array('first', 'last'))), ' class="first last"', 'Concatenate multi-value attributes.');
  2715. // Verify empty attribute values are rendered.
  2716. $this->assertIdentical(drupal_attributes(array('alt' => '')), ' alt=""', 'Empty attribute value #1.');
  2717. $this->assertIdentical(drupal_attributes(array('alt' => NULL)), ' alt=""', 'Empty attribute value #2.');
  2718. // Verify multiple attributes are rendered.
  2719. $attributes = array(
  2720. 'id' => 'id-test',
  2721. 'class' => array('first', 'last'),
  2722. 'alt' => 'Alternate',
  2723. );
  2724. $this->assertIdentical(drupal_attributes($attributes), ' id="id-test" class="first last" alt="Alternate"', 'Multiple attributes.');
  2725. // Verify empty attributes array is rendered.
  2726. $this->assertIdentical(drupal_attributes(array()), '', 'Empty attributes array.');
  2727. }
  2728. }
  2729. /**
  2730. * Tests converting PHP variables to JSON strings and back.
  2731. */
  2732. class DrupalJSONTest extends DrupalUnitTestCase {
  2733. public static function getInfo() {
  2734. return array(
  2735. 'name' => 'JSON',
  2736. 'description' => 'Perform unit tests on the drupal_json_encode() and drupal_json_decode() functions.',
  2737. 'group' => 'System',
  2738. );
  2739. }
  2740. /**
  2741. * Tests converting PHP variables to JSON strings and back.
  2742. */
  2743. function testJSON() {
  2744. // Setup a string with the full ASCII table.
  2745. // @todo: Add tests for non-ASCII characters and Unicode.
  2746. $str = '';
  2747. for ($i=0; $i < 128; $i++) {
  2748. $str .= chr($i);
  2749. }
  2750. // Characters that must be escaped.
  2751. // We check for unescaped " separately.
  2752. $html_unsafe = array('<', '>', '\'', '&');
  2753. // The following are the encoded forms of: < > ' & "
  2754. $html_unsafe_escaped = array('\u003C', '\u003E', '\u0027', '\u0026', '\u0022');
  2755. // Verify there aren't character encoding problems with the source string.
  2756. $this->assertIdentical(strlen($str), 128, 'A string with the full ASCII table has the correct length.');
  2757. foreach ($html_unsafe as $char) {
  2758. $this->assertTrue(strpos($str, $char) > 0, format_string('A string with the full ASCII table includes @s.', array('@s' => $char)));
  2759. }
  2760. // Verify that JSON encoding produces a string with all of the characters.
  2761. $json = drupal_json_encode($str);
  2762. $this->assertTrue(strlen($json) > strlen($str), 'A JSON encoded string is larger than the source string.');
  2763. // The first and last characters should be ", and no others.
  2764. $this->assertTrue($json[0] == '"', 'A JSON encoded string begins with ".');
  2765. $this->assertTrue($json[strlen($json) - 1] == '"', 'A JSON encoded string ends with ".');
  2766. $this->assertTrue(substr_count($json, '"') == 2, 'A JSON encoded string contains exactly two ".');
  2767. // Verify that encoding/decoding is reversible.
  2768. $json_decoded = drupal_json_decode($json);
  2769. $this->assertIdentical($str, $json_decoded, 'Encoding a string to JSON and decoding back results in the original string.');
  2770. // Verify reversibility for structured data. Also verify that necessary
  2771. // characters are escaped.
  2772. $source = array(TRUE, FALSE, 0, 1, '0', '1', $str, array('key1' => $str, 'key2' => array('nested' => TRUE)));
  2773. $json = drupal_json_encode($source);
  2774. foreach ($html_unsafe as $char) {
  2775. $this->assertTrue(strpos($json, $char) === FALSE, format_string('A JSON encoded string does not contain @s.', array('@s' => $char)));
  2776. }
  2777. // Verify that JSON encoding escapes the HTML unsafe characters
  2778. foreach ($html_unsafe_escaped as $char) {
  2779. $this->assertTrue(strpos($json, $char) > 0, format_string('A JSON encoded string contains @s.', array('@s' => $char)));
  2780. }
  2781. $json_decoded = drupal_json_decode($json);
  2782. $this->assertNotIdentical($source, $json, 'An array encoded in JSON is not identical to the source.');
  2783. $this->assertIdentical($source, $json_decoded, 'Encoding structured data to JSON and decoding back results in the original data.');
  2784. }
  2785. }
  2786. /**
  2787. * Tests for RDF namespaces XML serialization.
  2788. */
  2789. class DrupalGetRdfNamespacesTestCase extends DrupalWebTestCase {
  2790. public static function getInfo() {
  2791. return array(
  2792. 'name' => 'RDF namespaces XML serialization tests',
  2793. 'description' => 'Confirm that the serialization of RDF namespaces via drupal_get_rdf_namespaces() is output and parsed correctly in the XHTML document.',
  2794. 'group' => 'System',
  2795. );
  2796. }
  2797. function setUp() {
  2798. parent::setUp('rdf', 'rdf_test');
  2799. }
  2800. /**
  2801. * Test RDF namespaces.
  2802. */
  2803. function testGetRdfNamespaces() {
  2804. // Fetches the front page and extracts XML namespaces.
  2805. $this->drupalGet('');
  2806. $xml = new SimpleXMLElement($this->content);
  2807. $ns = $xml->getDocNamespaces();
  2808. $this->assertEqual($ns['rdfs'], 'http://www.w3.org/2000/01/rdf-schema#', 'A prefix declared once is displayed.');
  2809. $this->assertEqual($ns['foaf'], 'http://xmlns.com/foaf/0.1/', 'The same prefix declared in several implementations of hook_rdf_namespaces() is valid as long as all the namespaces are the same.');
  2810. $this->assertEqual($ns['foaf1'], 'http://xmlns.com/foaf/0.1/', 'Two prefixes can be assigned the same namespace.');
  2811. $this->assertTrue(!isset($ns['dc']), 'A prefix with conflicting namespaces is discarded.');
  2812. }
  2813. }
  2814. /**
  2815. * Basic tests for drupal_add_feed().
  2816. */
  2817. class DrupalAddFeedTestCase extends DrupalWebTestCase {
  2818. public static function getInfo() {
  2819. return array(
  2820. 'name' => 'drupal_add_feed() tests',
  2821. 'description' => 'Make sure that drupal_add_feed() works correctly with various constructs.',
  2822. 'group' => 'System',
  2823. );
  2824. }
  2825. /**
  2826. * Test drupal_add_feed() with paths, URLs, and titles.
  2827. */
  2828. function testBasicFeedAddNoTitle() {
  2829. $path = $this->randomName(12);
  2830. $external_url = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
  2831. $fully_qualified_local_url = url($this->randomName(12), array('absolute' => TRUE));
  2832. $path_for_title = $this->randomName(12);
  2833. $external_for_title = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
  2834. $fully_qualified_for_title = url($this->randomName(12), array('absolute' => TRUE));
  2835. // Possible permutations of drupal_add_feed() to test.
  2836. // - 'input_url': the path passed to drupal_add_feed(),
  2837. // - 'output_url': the expected URL to be found in the header.
  2838. // - 'title' == the title of the feed as passed into drupal_add_feed().
  2839. $urls = array(
  2840. 'path without title' => array(
  2841. 'input_url' => $path,
  2842. 'output_url' => url($path, array('absolute' => TRUE)),
  2843. 'title' => '',
  2844. ),
  2845. 'external URL without title' => array(
  2846. 'input_url' => $external_url,
  2847. 'output_url' => $external_url,
  2848. 'title' => '',
  2849. ),
  2850. 'local URL without title' => array(
  2851. 'input_url' => $fully_qualified_local_url,
  2852. 'output_url' => $fully_qualified_local_url,
  2853. 'title' => '',
  2854. ),
  2855. 'path with title' => array(
  2856. 'input_url' => $path_for_title,
  2857. 'output_url' => url($path_for_title, array('absolute' => TRUE)),
  2858. 'title' => $this->randomName(12),
  2859. ),
  2860. 'external URL with title' => array(
  2861. 'input_url' => $external_for_title,
  2862. 'output_url' => $external_for_title,
  2863. 'title' => $this->randomName(12),
  2864. ),
  2865. 'local URL with title' => array(
  2866. 'input_url' => $fully_qualified_for_title,
  2867. 'output_url' => $fully_qualified_for_title,
  2868. 'title' => $this->randomName(12),
  2869. ),
  2870. );
  2871. foreach ($urls as $description => $feed_info) {
  2872. drupal_add_feed($feed_info['input_url'], $feed_info['title']);
  2873. }
  2874. $this->drupalSetContent(drupal_get_html_head());
  2875. foreach ($urls as $description => $feed_info) {
  2876. $this->assertPattern($this->urlToRSSLinkPattern($feed_info['output_url'], $feed_info['title']), format_string('Found correct feed header for %description', array('%description' => $description)));
  2877. }
  2878. }
  2879. /**
  2880. * Create a pattern representing the RSS feed in the page.
  2881. */
  2882. function urlToRSSLinkPattern($url, $title = '') {
  2883. // Escape any regular expression characters in the URL ('?' is the worst).
  2884. $url = preg_replace('/([+?.*])/', '[$0]', $url);
  2885. $generated_pattern = '%<link +rel="alternate" +type="application/rss.xml" +title="' . $title . '" +href="' . $url . '" */>%';
  2886. return $generated_pattern;
  2887. }
  2888. }
  2889. /**
  2890. * Test for theme_feed_icon().
  2891. */
  2892. class FeedIconTest extends DrupalWebTestCase {
  2893. public static function getInfo() {
  2894. return array(
  2895. 'name' => 'Feed icon',
  2896. 'description' => 'Check escaping of theme_feed_icon()',
  2897. 'group' => 'System',
  2898. );
  2899. }
  2900. /**
  2901. * Check that special characters are correctly escaped. Test for issue #1211668.
  2902. */
  2903. function testFeedIconEscaping() {
  2904. $variables = array();
  2905. $variables['url'] = 'node';
  2906. $variables['title'] = '<>&"\'';
  2907. $text = theme_feed_icon($variables);
  2908. preg_match('/title="(.*?)"/', $text, $matches);
  2909. $this->assertEqual($matches[1], 'Subscribe to &amp;&quot;&#039;', 'theme_feed_icon() escapes reserved HTML characters.');
  2910. }
  2911. }
  2912. /**
  2913. * Test array diff functions.
  2914. */
  2915. class ArrayDiffUnitTest extends DrupalUnitTestCase {
  2916. /**
  2917. * Array to use for testing.
  2918. *
  2919. * @var array
  2920. */
  2921. protected $array1;
  2922. /**
  2923. * Array to use for testing.
  2924. *
  2925. * @var array
  2926. */
  2927. protected $array2;
  2928. public static function getInfo() {
  2929. return array(
  2930. 'name' => 'Array differences',
  2931. 'description' => 'Performs tests on drupal_array_diff_assoc_recursive().',
  2932. 'group' => 'System',
  2933. );
  2934. }
  2935. function setUp() {
  2936. parent::setUp();
  2937. $this->array1 = array(
  2938. 'same' => 'yes',
  2939. 'different' => 'no',
  2940. 'array_empty_diff' => array(),
  2941. 'null' => NULL,
  2942. 'int_diff' => 1,
  2943. 'array_diff' => array('same' => 'same', 'array' => array('same' => 'same')),
  2944. 'array_compared_to_string' => array('value'),
  2945. 'string_compared_to_array' => 'value',
  2946. 'new' => 'new',
  2947. );
  2948. $this->array2 = array(
  2949. 'same' => 'yes',
  2950. 'different' => 'yes',
  2951. 'array_empty_diff' => array(),
  2952. 'null' => NULL,
  2953. 'int_diff' => '1',
  2954. 'array_diff' => array('same' => 'different', 'array' => array('same' => 'same')),
  2955. 'array_compared_to_string' => 'value',
  2956. 'string_compared_to_array' => array('value'),
  2957. );
  2958. }
  2959. /**
  2960. * Tests drupal_array_diff_assoc_recursive().
  2961. */
  2962. public function testArrayDiffAssocRecursive() {
  2963. $expected = array(
  2964. 'different' => 'no',
  2965. 'int_diff' => 1,
  2966. // The 'array' key should not be returned, as it's the same.
  2967. 'array_diff' => array('same' => 'same'),
  2968. 'array_compared_to_string' => array('value'),
  2969. 'string_compared_to_array' => 'value',
  2970. 'new' => 'new',
  2971. );
  2972. $this->assertIdentical(drupal_array_diff_assoc_recursive($this->array1, $this->array2), $expected);
  2973. }
  2974. }
  2975. /**
  2976. * Tests the functionality of drupal_get_query_array().
  2977. */
  2978. class DrupalGetQueryArrayTestCase extends DrupalWebTestCase {
  2979. public static function getInfo() {
  2980. return array(
  2981. 'name' => 'Query parsing using drupal_get_query_array()',
  2982. 'description' => 'Tests that drupal_get_query_array() correctly parses query parameters.',
  2983. 'group' => 'System',
  2984. );
  2985. }
  2986. /**
  2987. * Tests that drupal_get_query_array() correctly explodes query parameters.
  2988. */
  2989. public function testDrupalGetQueryArray() {
  2990. $url = "http://my.site.com/somepath?foo=/content/folder[@name='foo']/folder[@name='bar']";
  2991. $parsed = parse_url($url);
  2992. $result = drupal_get_query_array($parsed['query']);
  2993. $this->assertEqual($result['foo'], "/content/folder[@name='foo']/folder[@name='bar']", 'drupal_get_query_array() should only explode parameters on the first equals sign.');
  2994. }
  2995. }
  2996. /**
  2997. * Test for drupal_add_html_head_link().
  2998. */
  2999. class DrupalAddHtmlHeadLinkTest extends DrupalWebTestCase {
  3000. /**
  3001. * {@inheritdoc}
  3002. */
  3003. public static function getInfo() {
  3004. return array(
  3005. 'name' => 'Add HTML head link',
  3006. 'description' => 'Test for drupal_add_html_head_link().',
  3007. 'group' => 'System',
  3008. );
  3009. }
  3010. /**
  3011. * {@inheritdoc}
  3012. */
  3013. function setUp() {
  3014. parent::setUp('common_test');
  3015. }
  3016. /**
  3017. * Tests drupal_add_html_head_link().
  3018. */
  3019. function testDrupalAddHtmlHeadLink() {
  3020. $this->drupalGet('common-test/html_head_link');
  3021. $expected_link_header = implode(',', array(
  3022. '</foo?bar=baz>; rel="alternate"',
  3023. '</foo/bar>; hreflang="nl"; rel="alternate"',
  3024. '</foo/bar>; hreflang="de"; rel="alternate"',
  3025. '</foo?bar=baz&baz=false>; hreflang="en"; rel="alternate"',
  3026. ));
  3027. $this->assertEqual($this->drupalGetHeader('Link'), $expected_link_header);
  3028. // Check that duplicate alternate URLs with different hreflangs are allowed.
  3029. $test_link = $this->xpath('//head/link[@rel="alternate"][@href="/foo/bar"]');
  3030. $this->assertEqual(count($test_link), 2, 'Duplicate alternate URLs are allowed.');
  3031. // Check that link element attributes are HTML-encoded.
  3032. $this->assertRaw('<link href="/foo?bar=baz&amp;baz=false" hreflang="en" rel="alternate" />');
  3033. }
  3034. }