common.test 134 KB

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