common.test 128 KB

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