common.test 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089
  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. * - Files imported from external URLs. (https://drupal.org/node/2014851)
  824. */
  825. function testLoadCssBasic() {
  826. // Array of files to test living in 'simpletest/files/css_test_files/'.
  827. // - Original: name.css
  828. // - Unoptimized expected content: name.css.unoptimized.css
  829. // - Optimized expected content: name.css.optimized.css
  830. $testfiles = array(
  831. 'css_input_without_import.css',
  832. 'css_input_with_import.css',
  833. 'css_subfolder/css_input_with_import.css',
  834. 'comment_hacks.css'
  835. );
  836. $path = drupal_get_path('module', 'simpletest') . '/files/css_test_files';
  837. foreach ($testfiles as $file) {
  838. $file_path = $path . '/' . $file;
  839. $file_url = $GLOBALS['base_url'] . '/' . $file_path;
  840. $expected = file_get_contents($file_path . '.unoptimized.css');
  841. $unoptimized_output = drupal_load_stylesheet($file_path, FALSE);
  842. $this->assertEqual($unoptimized_output, $expected, format_string('Unoptimized CSS file has expected contents (@file)', array('@file' => $file)));
  843. $expected = file_get_contents($file_path . '.optimized.css');
  844. $optimized_output = drupal_load_stylesheet($file_path, TRUE);
  845. $this->assertEqual($optimized_output, $expected, format_string('Optimized CSS file has expected contents (@file)', array('@file' => $file)));
  846. // Repeat the tests by accessing the stylesheets by URL.
  847. $expected = file_get_contents($file_path . '.unoptimized.css');
  848. $unoptimized_output_url = drupal_load_stylesheet($file_url, FALSE);
  849. $this->assertEqual($unoptimized_output_url, $expected, format_string('Unoptimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
  850. $expected = file_get_contents($file_path . '.optimized.css');
  851. $optimized_output_url = drupal_load_stylesheet($file_url, TRUE);
  852. $this->assertEqual($optimized_output_url, $expected, format_string('Optimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
  853. }
  854. }
  855. }
  856. /**
  857. * Test drupal_http_request().
  858. */
  859. class DrupalHTTPRequestTestCase extends DrupalWebTestCase {
  860. public static function getInfo() {
  861. return array(
  862. 'name' => 'Drupal HTTP request',
  863. 'description' => "Performs tests on Drupal's HTTP request mechanism.",
  864. 'group' => 'System'
  865. );
  866. }
  867. function setUp() {
  868. parent::setUp('system_test', 'locale');
  869. }
  870. function testDrupalHTTPRequest() {
  871. global $is_https;
  872. // Parse URL schema.
  873. $missing_scheme = drupal_http_request('example.com/path');
  874. $this->assertEqual($missing_scheme->code, -1002, 'Returned with "-1002" error code.');
  875. $this->assertEqual($missing_scheme->error, 'missing schema', 'Returned with "missing schema" error message.');
  876. $unable_to_parse = drupal_http_request('http:///path');
  877. $this->assertEqual($unable_to_parse->code, -1001, 'Returned with "-1001" error code.');
  878. $this->assertEqual($unable_to_parse->error, 'unable to parse URL', 'Returned with "unable to parse URL" error message.');
  879. // Fetch page.
  880. $result = drupal_http_request(url('node', array('absolute' => TRUE)));
  881. $this->assertEqual($result->code, 200, 'Fetched page successfully.');
  882. $this->drupalSetContent($result->data);
  883. $this->assertTitle(t('Welcome to @site-name | @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), 'Site title matches.');
  884. // Test that code and status message is returned.
  885. $result = drupal_http_request(url('pagedoesnotexist', array('absolute' => TRUE)));
  886. $this->assertTrue(!empty($result->protocol), 'Result protocol is returned.');
  887. $this->assertEqual($result->code, '404', 'Result code is 404');
  888. $this->assertEqual($result->status_message, 'Not Found', 'Result status message is "Not Found"');
  889. // Skip the timeout tests when the testing environment is HTTPS because
  890. // stream_set_timeout() does not work for SSL connections.
  891. // @link http://bugs.php.net/bug.php?id=47929
  892. if (!$is_https) {
  893. // Test that timeout is respected. The test machine is expected to be able
  894. // to make the connection (i.e. complete the fsockopen()) in 2 seconds and
  895. // return within a total of 5 seconds. If the test machine is extremely
  896. // slow, the test will fail. fsockopen() has been seen to time out in
  897. // slightly less than the specified timeout, so allow a little slack on
  898. // the minimum expected time (i.e. 1.8 instead of 2).
  899. timer_start(__METHOD__);
  900. $result = drupal_http_request(url('system-test/sleep/10', array('absolute' => TRUE)), array('timeout' => 2));
  901. $time = timer_read(__METHOD__) / 1000;
  902. $this->assertTrue(1.8 < $time && $time < 5, format_string('Request timed out (%time seconds).', array('%time' => $time)));
  903. $this->assertTrue($result->error, 'An error message was returned.');
  904. $this->assertEqual($result->code, HTTP_REQUEST_TIMEOUT, 'Proper error code was returned.');
  905. }
  906. }
  907. function testDrupalHTTPRequestBasicAuth() {
  908. $username = $this->randomName();
  909. $password = $this->randomName();
  910. $url = url('system-test/auth', array('absolute' => TRUE));
  911. $auth = str_replace('://', '://' . $username . ':' . $password . '@', $url);
  912. $result = drupal_http_request($auth);
  913. $this->drupalSetContent($result->data);
  914. $this->assertRaw($username, 'Username is passed correctly.');
  915. $this->assertRaw($password, 'Password is passed correctly.');
  916. }
  917. function testDrupalHTTPRequestRedirect() {
  918. $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 1));
  919. $this->assertEqual($redirect_301->redirect_code, 301, 'drupal_http_request follows the 301 redirect.');
  920. $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 0));
  921. $this->assertFalse(isset($redirect_301->redirect_code), 'drupal_http_request does not follow 301 redirect if max_redirects = 0.');
  922. $redirect_invalid = drupal_http_request(url('system-test/redirect-noscheme', array('absolute' => TRUE)), array('max_redirects' => 1));
  923. $this->assertEqual($redirect_invalid->code, -1002, format_string('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
  924. $this->assertEqual($redirect_invalid->error, 'missing schema', format_string('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
  925. $redirect_invalid = drupal_http_request(url('system-test/redirect-noparse', array('absolute' => TRUE)), array('max_redirects' => 1));
  926. $this->assertEqual($redirect_invalid->code, -1001, format_string('301 redirect to invalid URL returned with error message code "!error".', array('!error' => $redirect_invalid->error)));
  927. $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)));
  928. $redirect_invalid = drupal_http_request(url('system-test/redirect-invalid-scheme', array('absolute' => TRUE)), array('max_redirects' => 1));
  929. $this->assertEqual($redirect_invalid->code, -1003, format_string('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
  930. $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)));
  931. $redirect_302 = drupal_http_request(url('system-test/redirect/302', array('absolute' => TRUE)), array('max_redirects' => 1));
  932. $this->assertEqual($redirect_302->redirect_code, 302, 'drupal_http_request follows the 302 redirect.');
  933. $redirect_302 = drupal_http_request(url('system-test/redirect/302', array('absolute' => TRUE)), array('max_redirects' => 0));
  934. $this->assertFalse(isset($redirect_302->redirect_code), 'drupal_http_request does not follow 302 redirect if $retry = 0.');
  935. $redirect_307 = drupal_http_request(url('system-test/redirect/307', array('absolute' => TRUE)), array('max_redirects' => 1));
  936. $this->assertEqual($redirect_307->redirect_code, 307, 'drupal_http_request follows the 307 redirect.');
  937. $redirect_307 = drupal_http_request(url('system-test/redirect/307', array('absolute' => TRUE)), array('max_redirects' => 0));
  938. $this->assertFalse(isset($redirect_307->redirect_code), 'drupal_http_request does not follow 307 redirect if max_redirects = 0.');
  939. $multiple_redirect_final_url = url('system-test/multiple-redirects/0', array('absolute' => TRUE));
  940. $multiple_redirect_1 = drupal_http_request(url('system-test/multiple-redirects/1', array('absolute' => TRUE)), array('max_redirects' => 1));
  941. $this->assertEqual($multiple_redirect_1->redirect_url, $multiple_redirect_final_url, 'redirect_url contains the final redirection location after 1 redirect.');
  942. $multiple_redirect_3 = drupal_http_request(url('system-test/multiple-redirects/3', array('absolute' => TRUE)), array('max_redirects' => 3));
  943. $this->assertEqual($multiple_redirect_3->redirect_url, $multiple_redirect_final_url, 'redirect_url contains the final redirection location after 3 redirects.');
  944. }
  945. /**
  946. * Tests Content-language headers generated by Drupal.
  947. */
  948. function testDrupalHTTPRequestHeaders() {
  949. // Check the default header.
  950. $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
  951. $this->assertEqual($request->headers['content-language'], 'en', 'Content-Language HTTP header is English.');
  952. // Add German language and set as default.
  953. locale_add_language('de', 'German', 'Deutsch', LANGUAGE_LTR, '', '', TRUE, TRUE);
  954. // Request front page and check for matching Content-Language.
  955. $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
  956. $this->assertEqual($request->headers['content-language'], 'de', 'Content-Language HTTP header is German.');
  957. }
  958. }
  959. /**
  960. * Tests parsing of the HTTP response status line.
  961. */
  962. class DrupalHTTPResponseStatusLineTest extends DrupalUnitTestCase {
  963. public static function getInfo() {
  964. return array(
  965. 'name' => 'Drupal HTTP request response status parsing',
  966. 'description' => 'Perform unit tests on _drupal_parse_response_status().',
  967. 'group' => 'System',
  968. );
  969. }
  970. /**
  971. * Tests parsing HTTP response status line.
  972. */
  973. public function testStatusLine() {
  974. // Grab the big array of test data from statusLineData().
  975. $data = $this->statusLineData();
  976. foreach($data as $test_case) {
  977. $test_data = array_shift($test_case);
  978. $expected = array_shift($test_case);
  979. $outcome = _drupal_parse_response_status($test_data);
  980. foreach(array_keys($expected) as $key) {
  981. $this->assertIdentical($outcome[$key], $expected[$key]);
  982. }
  983. }
  984. }
  985. /**
  986. * Data provider for testStatusLine().
  987. *
  988. * @return array
  989. * Test data.
  990. */
  991. protected function statusLineData() {
  992. return array(
  993. array(
  994. 'HTTP/1.1 200 OK',
  995. array(
  996. 'http_version' => 'HTTP/1.1',
  997. 'response_code' => '200',
  998. 'reason_phrase' => 'OK',
  999. ),
  1000. ),
  1001. // Data set with no reason phrase.
  1002. array(
  1003. 'HTTP/1.1 200',
  1004. array(
  1005. 'http_version' => 'HTTP/1.1',
  1006. 'response_code' => '200',
  1007. 'reason_phrase' => '',
  1008. ),
  1009. ),
  1010. // Arbitrary strings.
  1011. array(
  1012. 'version code multi word explanation',
  1013. array(
  1014. 'http_version' => 'version',
  1015. 'response_code' => 'code',
  1016. 'reason_phrase' => 'multi word explanation',
  1017. ),
  1018. ),
  1019. );
  1020. }
  1021. }
  1022. /**
  1023. * Testing drupal_add_region_content and drupal_get_region_content.
  1024. */
  1025. class DrupalSetContentTestCase extends DrupalWebTestCase {
  1026. public static function getInfo() {
  1027. return array(
  1028. 'name' => 'Drupal set/get regions',
  1029. 'description' => 'Performs tests on setting and retrieiving content from theme regions.',
  1030. 'group' => 'System'
  1031. );
  1032. }
  1033. /**
  1034. * Test setting and retrieving content for theme regions.
  1035. */
  1036. function testRegions() {
  1037. global $theme_key;
  1038. $block_regions = array_keys(system_region_list($theme_key));
  1039. $delimiter = $this->randomName(32);
  1040. $values = array();
  1041. // Set some random content for each region available.
  1042. foreach ($block_regions as $region) {
  1043. $first_chunk = $this->randomName(32);
  1044. drupal_add_region_content($region, $first_chunk);
  1045. $second_chunk = $this->randomName(32);
  1046. drupal_add_region_content($region, $second_chunk);
  1047. // Store the expected result for a drupal_get_region_content call for this region.
  1048. $values[$region] = $first_chunk . $delimiter . $second_chunk;
  1049. }
  1050. // Ensure drupal_get_region_content returns expected results when fetching all regions.
  1051. $content = drupal_get_region_content(NULL, $delimiter);
  1052. foreach ($content as $region => $region_content) {
  1053. $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching all regions', array('@region' => $region)));
  1054. }
  1055. // Ensure drupal_get_region_content returns expected results when fetching a single region.
  1056. foreach ($block_regions as $region) {
  1057. $region_content = drupal_get_region_content($region, $delimiter);
  1058. $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching single region.', array('@region' => $region)));
  1059. }
  1060. }
  1061. }
  1062. /**
  1063. * Testing drupal_goto and hook_drupal_goto_alter().
  1064. */
  1065. class DrupalGotoTest extends DrupalWebTestCase {
  1066. public static function getInfo() {
  1067. return array(
  1068. 'name' => 'Drupal goto',
  1069. 'description' => 'Performs tests on the drupal_goto function and hook_drupal_goto_alter',
  1070. 'group' => 'System'
  1071. );
  1072. }
  1073. function setUp() {
  1074. parent::setUp('common_test');
  1075. }
  1076. /**
  1077. * Test drupal_goto().
  1078. */
  1079. function testDrupalGoto() {
  1080. $this->drupalGet('common-test/drupal_goto/redirect');
  1081. $headers = $this->drupalGetHeaders(TRUE);
  1082. list(, $status) = explode(' ', $headers[0][':status'], 3);
  1083. $this->assertEqual($status, 302, 'Expected response code was sent.');
  1084. $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
  1085. $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
  1086. $this->drupalGet('common-test/drupal_goto/redirect_advanced');
  1087. $headers = $this->drupalGetHeaders(TRUE);
  1088. list(, $status) = explode(' ', $headers[0][':status'], 3);
  1089. $this->assertEqual($status, 301, 'Expected response code was sent.');
  1090. $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
  1091. $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('query' => array('foo' => '123'), 'absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
  1092. // Test that drupal_goto() respects ?destination=xxx. Use an complicated URL
  1093. // to test that the path is encoded and decoded properly.
  1094. $destination = 'common-test/drupal_goto/destination?foo=%2525&bar=123';
  1095. $this->drupalGet('common-test/drupal_goto/redirect', array('query' => array('destination' => $destination)));
  1096. $this->assertText('drupal_goto', 'Drupal goto redirect with destination succeeded.');
  1097. $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.');
  1098. }
  1099. /**
  1100. * Test hook_drupal_goto_alter().
  1101. */
  1102. function testDrupalGotoAlter() {
  1103. $this->drupalGet('common-test/drupal_goto/redirect_fail');
  1104. $this->assertNoText(t("Drupal goto failed to stop program"), "Drupal goto stopped program.");
  1105. $this->assertNoText('drupal_goto_fail', "Drupal goto redirect failed.");
  1106. }
  1107. /**
  1108. * Test drupal_get_destination().
  1109. */
  1110. function testDrupalGetDestination() {
  1111. $query = $this->randomName(10);
  1112. // Verify that a 'destination' query string is used as destination.
  1113. $this->drupalGet('common-test/destination', array('query' => array('destination' => $query)));
  1114. $this->assertText('The destination: ' . $query, 'The given query string destination is determined as destination.');
  1115. // Verify that the current path is used as destination.
  1116. $this->drupalGet('common-test/destination', array('query' => array($query => NULL)));
  1117. $url = 'common-test/destination?' . $query;
  1118. $this->assertText('The destination: ' . $url, 'The current path is determined as destination.');
  1119. }
  1120. }
  1121. /**
  1122. * Tests for the JavaScript system.
  1123. */
  1124. class JavaScriptTestCase extends DrupalWebTestCase {
  1125. /**
  1126. * Store configured value for JavaScript preprocessing.
  1127. */
  1128. protected $preprocess_js = NULL;
  1129. public static function getInfo() {
  1130. return array(
  1131. 'name' => 'JavaScript',
  1132. 'description' => 'Tests the JavaScript system.',
  1133. 'group' => 'System'
  1134. );
  1135. }
  1136. function setUp() {
  1137. // Enable Locale and SimpleTest in the test environment.
  1138. parent::setUp('locale', 'simpletest', 'common_test');
  1139. // Disable preprocessing
  1140. $this->preprocess_js = variable_get('preprocess_js', 0);
  1141. variable_set('preprocess_js', 0);
  1142. // Reset drupal_add_js() and drupal_add_library() statics before each test.
  1143. drupal_static_reset('drupal_add_js');
  1144. drupal_static_reset('drupal_add_library');
  1145. }
  1146. function tearDown() {
  1147. // Restore configured value for JavaScript preprocessing.
  1148. variable_set('preprocess_js', $this->preprocess_js);
  1149. parent::tearDown();
  1150. }
  1151. /**
  1152. * Test default JavaScript is empty.
  1153. */
  1154. function testDefault() {
  1155. $this->assertEqual(array(), drupal_add_js(), 'Default JavaScript is empty.');
  1156. }
  1157. /**
  1158. * Test adding a JavaScript file.
  1159. */
  1160. function testAddFile() {
  1161. $javascript = drupal_add_js('misc/collapse.js');
  1162. $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when a file is added.');
  1163. $this->assertTrue(array_key_exists('misc/drupal.js', $javascript), 'Drupal.js is added when file is added.');
  1164. $this->assertTrue(array_key_exists('misc/collapse.js', $javascript), 'JavaScript files are correctly added.');
  1165. $this->assertEqual(base_path(), $javascript['settings']['data'][0]['basePath'], 'Base path JavaScript setting is correctly set.');
  1166. url('', array('prefix' => &$prefix));
  1167. $this->assertEqual(empty($prefix) ? '' : $prefix, $javascript['settings']['data'][1]['pathPrefix'], 'Path prefix JavaScript setting is correctly set.');
  1168. }
  1169. /**
  1170. * Test adding settings.
  1171. */
  1172. function testAddSetting() {
  1173. $javascript = drupal_add_js(array('drupal' => 'rocks', 'dries' => 280342800), 'setting');
  1174. $this->assertEqual(280342800, $javascript['settings']['data'][2]['dries'], 'JavaScript setting is set correctly.');
  1175. $this->assertEqual('rocks', $javascript['settings']['data'][2]['drupal'], 'The other JavaScript setting is set correctly.');
  1176. }
  1177. /**
  1178. * Tests adding an external JavaScript File.
  1179. */
  1180. function testAddExternal() {
  1181. $path = 'http://example.com/script.js';
  1182. $javascript = drupal_add_js($path, 'external');
  1183. $this->assertTrue(array_key_exists('http://example.com/script.js', $javascript), 'Added an external JavaScript file.');
  1184. }
  1185. /**
  1186. * Test drupal_get_js() for JavaScript settings.
  1187. */
  1188. function testHeaderSetting() {
  1189. // Only the second of these two entries should appear in Drupal.settings.
  1190. drupal_add_js(array('commonTest' => 'commonTestShouldNotAppear'), 'setting');
  1191. drupal_add_js(array('commonTest' => 'commonTestShouldAppear'), 'setting');
  1192. // All three of these entries should appear in Drupal.settings.
  1193. drupal_add_js(array('commonTestArray' => array('commonTestValue0')), 'setting');
  1194. drupal_add_js(array('commonTestArray' => array('commonTestValue1')), 'setting');
  1195. drupal_add_js(array('commonTestArray' => array('commonTestValue2')), 'setting');
  1196. // Only the second of these two entries should appear in Drupal.settings.
  1197. drupal_add_js(array('commonTestArray' => array('key' => 'commonTestOldValue')), 'setting');
  1198. drupal_add_js(array('commonTestArray' => array('key' => 'commonTestNewValue')), 'setting');
  1199. $javascript = drupal_get_js('header');
  1200. $this->assertTrue(strpos($javascript, 'basePath') > 0, 'Rendered JavaScript header returns basePath setting.');
  1201. $this->assertTrue(strpos($javascript, 'misc/jquery.js') > 0, 'Rendered JavaScript header includes jQuery.');
  1202. $this->assertTrue(strpos($javascript, 'pathPrefix') > 0, 'Rendered JavaScript header returns pathPrefix setting.');
  1203. // Test whether drupal_add_js can be used to override a previous setting.
  1204. $this->assertTrue(strpos($javascript, 'commonTestShouldAppear') > 0, 'Rendered JavaScript header returns custom setting.');
  1205. $this->assertTrue(strpos($javascript, 'commonTestShouldNotAppear') === FALSE, 'drupal_add_js() correctly overrides a custom setting.');
  1206. // Test whether drupal_add_js can be used to add numerically indexed values
  1207. // to an array.
  1208. $array_values_appear = strpos($javascript, 'commonTestValue0') > 0 && strpos($javascript, 'commonTestValue1') > 0 && strpos($javascript, 'commonTestValue2') > 0;
  1209. $this->assertTrue($array_values_appear, 'drupal_add_js() correctly adds settings to the end of an indexed array.');
  1210. // Test whether drupal_add_js can be used to override the entry for an
  1211. // existing key in an associative array.
  1212. $associative_array_override = strpos($javascript, 'commonTestNewValue') > 0 && strpos($javascript, 'commonTestOldValue') === FALSE;
  1213. $this->assertTrue($associative_array_override, 'drupal_add_js() correctly overrides settings within an associative array.');
  1214. }
  1215. /**
  1216. * Test to see if resetting the JavaScript empties the cache.
  1217. */
  1218. function testReset() {
  1219. drupal_add_js('misc/collapse.js');
  1220. drupal_static_reset('drupal_add_js');
  1221. $this->assertEqual(array(), drupal_add_js(), 'Resetting the JavaScript correctly empties the cache.');
  1222. }
  1223. /**
  1224. * Test adding inline scripts.
  1225. */
  1226. function testAddInline() {
  1227. $inline = 'jQuery(function () { });';
  1228. $javascript = drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
  1229. $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when inline scripts are added.');
  1230. $data = end($javascript);
  1231. $this->assertEqual($inline, $data['data'], 'Inline JavaScript is correctly added to the footer.');
  1232. }
  1233. /**
  1234. * Test rendering an external JavaScript file.
  1235. */
  1236. function testRenderExternal() {
  1237. $external = 'http://example.com/example.js';
  1238. drupal_add_js($external, 'external');
  1239. $javascript = drupal_get_js();
  1240. // Local files have a base_path() prefix, external files should not.
  1241. $this->assertTrue(strpos($javascript, 'src="' . $external) > 0, 'Rendering an external JavaScript file.');
  1242. }
  1243. /**
  1244. * Test drupal_get_js() with a footer scope.
  1245. */
  1246. function testFooterHTML() {
  1247. $inline = 'jQuery(function () { });';
  1248. drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
  1249. $javascript = drupal_get_js('footer');
  1250. $this->assertTrue(strpos($javascript, $inline) > 0, 'Rendered JavaScript footer returns the inline code.');
  1251. }
  1252. /**
  1253. * Test the 'javascript_always_use_jquery' variable.
  1254. */
  1255. function testJavaScriptAlwaysUseJQuery() {
  1256. // The default front page of the site should use jQuery and other standard
  1257. // scripts and settings.
  1258. $this->drupalGet('');
  1259. $this->assertRaw('misc/jquery.js', 'Default behavior: The front page of the site includes jquery.js.');
  1260. $this->assertRaw('misc/drupal.js', 'Default behavior: The front page of the site includes drupal.js.');
  1261. $this->assertRaw('Drupal.settings', 'Default behavior: The front page of the site includes Drupal settings.');
  1262. $this->assertRaw('basePath', 'Default behavior: The front page of the site includes the basePath Drupal setting.');
  1263. // The default front page should not use jQuery and other standard scripts
  1264. // and settings when the 'javascript_always_use_jquery' variable is set to
  1265. // FALSE.
  1266. variable_set('javascript_always_use_jquery', FALSE);
  1267. $this->drupalGet('');
  1268. $this->assertNoRaw('misc/jquery.js', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include jquery.js.');
  1269. $this->assertNoRaw('misc/drupal.js', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include drupal.js.');
  1270. $this->assertNoRaw('Drupal.settings', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include Drupal settings.');
  1271. $this->assertNoRaw('basePath', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include the basePath Drupal setting.');
  1272. variable_del('javascript_always_use_jquery');
  1273. // When only settings have been added via drupal_add_js(), drupal_get_js()
  1274. // should still return jQuery and other standard scripts and settings.
  1275. $this->resetStaticVariables();
  1276. drupal_add_js(array('testJavaScriptSetting' => 'test'), 'setting');
  1277. $javascript = drupal_get_js();
  1278. $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.');
  1279. $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.');
  1280. $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.');
  1281. $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.');
  1282. $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.');
  1283. // When only settings have been added via drupal_add_js() and the
  1284. // 'javascript_always_use_jquery' variable is set to FALSE, drupal_get_js()
  1285. // should not return jQuery and other standard scripts and settings, nor
  1286. // should it return the requested settings (since they cannot actually be
  1287. // addded to the page without jQuery).
  1288. $this->resetStaticVariables();
  1289. variable_set('javascript_always_use_jquery', FALSE);
  1290. drupal_add_js(array('testJavaScriptSetting' => 'test'), 'setting');
  1291. $javascript = drupal_get_js();
  1292. $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.');
  1293. $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.');
  1294. $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.');
  1295. $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.');
  1296. $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.');
  1297. variable_del('javascript_always_use_jquery');
  1298. // When a regular file has been added via drupal_add_js(), drupal_get_js()
  1299. // should return jQuery and other standard scripts and settings.
  1300. $this->resetStaticVariables();
  1301. drupal_add_js('misc/collapse.js');
  1302. $javascript = drupal_get_js();
  1303. $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.');
  1304. $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.');
  1305. $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.');
  1306. $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.');
  1307. $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.');
  1308. // When a regular file has been added via drupal_add_js() and the
  1309. // 'javascript_always_use_jquery' variable is set to FALSE, drupal_get_js()
  1310. // should still return jQuery and other standard scripts and settings
  1311. // (since the file is assumed to require jQuery by default).
  1312. $this->resetStaticVariables();
  1313. variable_set('javascript_always_use_jquery', FALSE);
  1314. drupal_add_js('misc/collapse.js');
  1315. $javascript = drupal_get_js();
  1316. $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.');
  1317. $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.');
  1318. $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.');
  1319. $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.');
  1320. $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.');
  1321. variable_del('javascript_always_use_jquery');
  1322. // When a file that does not require jQuery has been added via
  1323. // drupal_add_js(), drupal_get_js() should still return jQuery and other
  1324. // standard scripts and settings by default.
  1325. $this->resetStaticVariables();
  1326. drupal_add_js('misc/collapse.js', array('requires_jquery' => FALSE));
  1327. $javascript = drupal_get_js();
  1328. $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.');
  1329. $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.');
  1330. $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.');
  1331. $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.');
  1332. $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.');
  1333. // When a file that does not require jQuery has been added via
  1334. // drupal_add_js() and the 'javascript_always_use_jquery' variable is set
  1335. // to FALSE, drupal_get_js() should not return jQuery and other standard
  1336. // scripts and setting, but it should still return the requested file.
  1337. $this->resetStaticVariables();
  1338. variable_set('javascript_always_use_jquery', FALSE);
  1339. drupal_add_js('misc/collapse.js', array('requires_jquery' => FALSE));
  1340. $javascript = drupal_get_js();
  1341. $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.');
  1342. $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.');
  1343. $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.');
  1344. $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.');
  1345. $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.');
  1346. variable_del('javascript_always_use_jquery');
  1347. // When 'javascript_always_use_jquery' is set to FALSE and a file that does
  1348. // not require jQuery is added, followed by one that does, drupal_get_js()
  1349. // should return jQuery and other standard scripts and settings, in
  1350. // addition to both of the requested files.
  1351. $this->resetStaticVariables();
  1352. variable_set('javascript_always_use_jquery', FALSE);
  1353. drupal_add_js('misc/collapse.js', array('requires_jquery' => FALSE));
  1354. drupal_add_js('misc/ajax.js');
  1355. $javascript = drupal_get_js();
  1356. $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.');
  1357. $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.');
  1358. $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.');
  1359. $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.');
  1360. $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.');
  1361. $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.');
  1362. variable_del('javascript_always_use_jquery');
  1363. }
  1364. /**
  1365. * Test drupal_add_js() sets preproccess to false when cache is set to false.
  1366. */
  1367. function testNoCache() {
  1368. $javascript = drupal_add_js('misc/collapse.js', array('cache' => FALSE));
  1369. $this->assertFalse($javascript['misc/collapse.js']['preprocess'], 'Setting cache to FALSE sets proprocess to FALSE when adding JavaScript.');
  1370. }
  1371. /**
  1372. * Test adding a JavaScript file with a different group.
  1373. */
  1374. function testDifferentGroup() {
  1375. $javascript = drupal_add_js('misc/collapse.js', array('group' => JS_THEME));
  1376. $this->assertEqual($javascript['misc/collapse.js']['group'], JS_THEME, 'Adding a JavaScript file with a different group caches the given group.');
  1377. }
  1378. /**
  1379. * Test adding a JavaScript file with a different weight.
  1380. */
  1381. function testDifferentWeight() {
  1382. $javascript = drupal_add_js('misc/collapse.js', array('weight' => 2));
  1383. $this->assertEqual($javascript['misc/collapse.js']['weight'], 2, 'Adding a JavaScript file with a different weight caches the given weight.');
  1384. }
  1385. /**
  1386. * Tests JavaScript aggregation when files are added to a different scope.
  1387. */
  1388. function testAggregationOrder() {
  1389. // Enable JavaScript aggregation.
  1390. variable_set('preprocess_js', 1);
  1391. drupal_static_reset('drupal_add_js');
  1392. // Add two JavaScript files to the current request and build the cache.
  1393. drupal_add_js('misc/ajax.js');
  1394. drupal_add_js('misc/autocomplete.js');
  1395. $js_items = drupal_add_js();
  1396. drupal_build_js_cache(array(
  1397. 'misc/ajax.js' => $js_items['misc/ajax.js'],
  1398. 'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
  1399. ));
  1400. // Store the expected key for the first item in the cache.
  1401. $cache = array_keys(variable_get('drupal_js_cache_files', array()));
  1402. $expected_key = $cache[0];
  1403. // Reset variables and add a file in a different scope first.
  1404. variable_del('drupal_js_cache_files');
  1405. drupal_static_reset('drupal_add_js');
  1406. drupal_add_js('some/custom/javascript_file.js', array('scope' => 'footer'));
  1407. drupal_add_js('misc/ajax.js');
  1408. drupal_add_js('misc/autocomplete.js');
  1409. // Rebuild the cache.
  1410. $js_items = drupal_add_js();
  1411. drupal_build_js_cache(array(
  1412. 'misc/ajax.js' => $js_items['misc/ajax.js'],
  1413. 'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
  1414. ));
  1415. // Compare the expected key for the first file to the current one.
  1416. $cache = array_keys(variable_get('drupal_js_cache_files', array()));
  1417. $key = $cache[0];
  1418. $this->assertEqual($key, $expected_key, 'JavaScript aggregation is not affected by ordering in different scopes.');
  1419. }
  1420. /**
  1421. * Test JavaScript ordering.
  1422. */
  1423. function testRenderOrder() {
  1424. // Add a bunch of JavaScript in strange ordering.
  1425. drupal_add_js('(function($){alert("Weight 5 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
  1426. drupal_add_js('(function($){alert("Weight 0 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
  1427. drupal_add_js('(function($){alert("Weight 0 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
  1428. drupal_add_js('(function($){alert("Weight -8 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
  1429. drupal_add_js('(function($){alert("Weight -8 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
  1430. drupal_add_js('(function($){alert("Weight -8 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
  1431. drupal_add_js('http://example.com/example.js?Weight -5 #1', array('type' => 'external', 'scope' => 'footer', 'weight' => -5));
  1432. drupal_add_js('(function($){alert("Weight -8 #4");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
  1433. drupal_add_js('(function($){alert("Weight 5 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
  1434. drupal_add_js('(function($){alert("Weight 0 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
  1435. // Construct the expected result from the regex.
  1436. $expected = array(
  1437. "-8 #1",
  1438. "-8 #2",
  1439. "-8 #3",
  1440. "-8 #4",
  1441. "-5 #1", // The external script.
  1442. "0 #1",
  1443. "0 #2",
  1444. "0 #3",
  1445. "5 #1",
  1446. "5 #2",
  1447. );
  1448. // Retrieve the rendered JavaScript and test against the regex.
  1449. $js = drupal_get_js('footer');
  1450. $matches = array();
  1451. if (preg_match_all('/Weight\s([-0-9]+\s[#0-9]+)/', $js, $matches)) {
  1452. $result = $matches[1];
  1453. }
  1454. else {
  1455. $result = array();
  1456. }
  1457. $this->assertIdentical($result, $expected, 'JavaScript is added in the expected weight order.');
  1458. }
  1459. /**
  1460. * Test rendering the JavaScript with a file's weight above jQuery's.
  1461. */
  1462. function testRenderDifferentWeight() {
  1463. // JavaScript files are sorted first by group, then by the 'every_page'
  1464. // flag, then by weight (see drupal_sort_css_js()), so to test the effect of
  1465. // weight, we need the other two options to be the same.
  1466. drupal_add_js('misc/collapse.js', array('group' => JS_LIBRARY, 'every_page' => TRUE, 'weight' => -21));
  1467. $javascript = drupal_get_js();
  1468. $this->assertTrue(strpos($javascript, 'misc/collapse.js') < strpos($javascript, 'misc/jquery.js'), 'Rendering a JavaScript file above jQuery.');
  1469. }
  1470. /**
  1471. * Test altering a JavaScript's weight via hook_js_alter().
  1472. *
  1473. * @see simpletest_js_alter()
  1474. */
  1475. function testAlter() {
  1476. // Add both tableselect.js and simpletest.js, with a larger weight on SimpleTest.
  1477. drupal_add_js('misc/tableselect.js');
  1478. drupal_add_js(drupal_get_path('module', 'simpletest') . '/simpletest.js', array('weight' => 9999));
  1479. // Render the JavaScript, testing if simpletest.js was altered to be before
  1480. // tableselect.js. See simpletest_js_alter() to see where this alteration
  1481. // takes place.
  1482. $javascript = drupal_get_js();
  1483. $this->assertTrue(strpos($javascript, 'simpletest.js') < strpos($javascript, 'misc/tableselect.js'), 'Altering JavaScript weight through the alter hook.');
  1484. }
  1485. /**
  1486. * Adds a library to the page and tests for both its JavaScript and its CSS.
  1487. */
  1488. function testLibraryRender() {
  1489. $result = drupal_add_library('system', 'farbtastic');
  1490. $this->assertTrue($result !== FALSE, 'Library was added without errors.');
  1491. $scripts = drupal_get_js();
  1492. $styles = drupal_get_css();
  1493. $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), 'JavaScript of library was added to the page.');
  1494. $this->assertTrue(strpos($styles, 'misc/farbtastic/farbtastic.css'), 'Stylesheet of library was added to the page.');
  1495. }
  1496. /**
  1497. * Adds a JavaScript library to the page and alters it.
  1498. *
  1499. * @see common_test_library_alter()
  1500. */
  1501. function testLibraryAlter() {
  1502. // Verify that common_test altered the title of Farbtastic.
  1503. $library = drupal_get_library('system', 'farbtastic');
  1504. $this->assertEqual($library['title'], 'Farbtastic: Altered Library', 'Registered libraries were altered.');
  1505. // common_test_library_alter() also added a dependency on jQuery Form.
  1506. drupal_add_library('system', 'farbtastic');
  1507. $scripts = drupal_get_js();
  1508. $this->assertTrue(strpos($scripts, 'misc/jquery.form.js'), 'Altered library dependencies are added to the page.');
  1509. }
  1510. /**
  1511. * Tests that multiple modules can implement the same library.
  1512. *
  1513. * @see common_test_library()
  1514. */
  1515. function testLibraryNameConflicts() {
  1516. $farbtastic = drupal_get_library('common_test', 'farbtastic');
  1517. $this->assertEqual($farbtastic['title'], 'Custom Farbtastic Library', 'Alternative libraries can be added to the page.');
  1518. }
  1519. /**
  1520. * Tests non-existing libraries.
  1521. */
  1522. function testLibraryUnknown() {
  1523. $result = drupal_get_library('unknown', 'unknown');
  1524. $this->assertFalse($result, 'Unknown library returned FALSE.');
  1525. drupal_static_reset('drupal_get_library');
  1526. $result = drupal_add_library('unknown', 'unknown');
  1527. $this->assertFalse($result, 'Unknown library returned FALSE.');
  1528. $scripts = drupal_get_js();
  1529. $this->assertTrue(strpos($scripts, 'unknown') === FALSE, 'Unknown library was not added to the page.');
  1530. }
  1531. /**
  1532. * Tests the addition of libraries through the #attached['library'] property.
  1533. */
  1534. function testAttachedLibrary() {
  1535. $element['#attached']['library'][] = array('system', 'farbtastic');
  1536. drupal_render($element);
  1537. $scripts = drupal_get_js();
  1538. $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), 'The attached_library property adds the additional libraries.');
  1539. }
  1540. /**
  1541. * Tests retrieval of libraries via drupal_get_library().
  1542. */
  1543. function testGetLibrary() {
  1544. // Retrieve all libraries registered by a module.
  1545. $libraries = drupal_get_library('common_test');
  1546. $this->assertTrue(isset($libraries['farbtastic']), 'Retrieved all module libraries.');
  1547. // Retrieve all libraries for a module not implementing hook_library().
  1548. // Note: This test installs Locale module.
  1549. $libraries = drupal_get_library('locale');
  1550. $this->assertEqual($libraries, array(), 'Retrieving libraries from a module not implementing hook_library() returns an emtpy array.');
  1551. // Retrieve a specific library by module and name.
  1552. $farbtastic = drupal_get_library('common_test', 'farbtastic');
  1553. $this->assertEqual($farbtastic['version'], '5.3', 'Retrieved a single library.');
  1554. // Retrieve a non-existing library by module and name.
  1555. $farbtastic = drupal_get_library('common_test', 'foo');
  1556. $this->assertIdentical($farbtastic, FALSE, 'Retrieving a non-existing library returns FALSE.');
  1557. }
  1558. /**
  1559. * Tests that the query string remains intact when adding JavaScript files
  1560. * that have query string parameters.
  1561. */
  1562. function testAddJsFileWithQueryString() {
  1563. $this->drupalGet('common-test/query-string');
  1564. $query_string = variable_get('css_js_query_string', '0');
  1565. $this->assertRaw(drupal_get_path('module', 'node') . '/node.js?' . $query_string, 'Query string was appended correctly to js.');
  1566. }
  1567. /**
  1568. * Resets static variables related to adding JavaScript to a page.
  1569. */
  1570. function resetStaticVariables() {
  1571. drupal_static_reset('drupal_add_js');
  1572. drupal_static_reset('drupal_add_library');
  1573. drupal_static_reset('drupal_get_library');
  1574. }
  1575. }
  1576. /**
  1577. * Tests for drupal_render().
  1578. */
  1579. class DrupalRenderTestCase extends DrupalWebTestCase {
  1580. public static function getInfo() {
  1581. return array(
  1582. 'name' => 'drupal_render()',
  1583. 'description' => 'Performs functional tests on drupal_render().',
  1584. 'group' => 'System',
  1585. );
  1586. }
  1587. function setUp() {
  1588. parent::setUp('common_test');
  1589. }
  1590. /**
  1591. * Tests the output drupal_render() for some elementary input values.
  1592. */
  1593. function testDrupalRenderBasics() {
  1594. $types = array(
  1595. array(
  1596. 'name' => 'null',
  1597. 'value' => NULL,
  1598. 'expected' => '',
  1599. ),
  1600. array(
  1601. 'name' => 'no value',
  1602. 'expected' => '',
  1603. ),
  1604. array(
  1605. 'name' => 'empty string',
  1606. 'value' => '',
  1607. 'expected' => '',
  1608. ),
  1609. array(
  1610. 'name' => 'no access',
  1611. 'value' => array(
  1612. '#markup' => 'foo',
  1613. '#access' => FALSE,
  1614. ),
  1615. 'expected' => '',
  1616. ),
  1617. array(
  1618. 'name' => 'previously printed',
  1619. 'value' => array(
  1620. '#markup' => 'foo',
  1621. '#printed' => TRUE,
  1622. ),
  1623. 'expected' => '',
  1624. ),
  1625. array(
  1626. 'name' => 'printed in prerender',
  1627. 'value' => array(
  1628. '#markup' => 'foo',
  1629. '#pre_render' => array('common_test_drupal_render_printing_pre_render'),
  1630. ),
  1631. 'expected' => '',
  1632. ),
  1633. array(
  1634. 'name' => 'basic renderable array',
  1635. 'value' => array('#markup' => 'foo'),
  1636. 'expected' => 'foo',
  1637. ),
  1638. );
  1639. foreach($types as $type) {
  1640. $this->assertIdentical(drupal_render($type['value']), $type['expected'], '"' . $type['name'] . '" input rendered correctly by drupal_render().');
  1641. }
  1642. }
  1643. /**
  1644. * Test sorting by weight.
  1645. */
  1646. function testDrupalRenderSorting() {
  1647. $first = $this->randomName();
  1648. $second = $this->randomName();
  1649. // Build an array with '#weight' set for each element.
  1650. $elements = array(
  1651. 'second' => array(
  1652. '#weight' => 10,
  1653. '#markup' => $second,
  1654. ),
  1655. 'first' => array(
  1656. '#weight' => 0,
  1657. '#markup' => $first,
  1658. ),
  1659. );
  1660. $output = drupal_render($elements);
  1661. // The lowest weight element should appear last in $output.
  1662. $this->assertTrue(strpos($output, $second) > strpos($output, $first), 'Elements were sorted correctly by weight.');
  1663. // Confirm that the $elements array has '#sorted' set to TRUE.
  1664. $this->assertTrue($elements['#sorted'], "'#sorted' => TRUE was added to the array");
  1665. // Pass $elements through element_children() and ensure it remains
  1666. // sorted in the correct order. drupal_render() will return an empty string
  1667. // if used on the same array in the same request.
  1668. $children = element_children($elements);
  1669. $this->assertTrue(array_shift($children) == 'first', 'Child found in the correct order.');
  1670. $this->assertTrue(array_shift($children) == 'second', 'Child found in the correct order.');
  1671. // The same array structure again, but with #sorted set to TRUE.
  1672. $elements = array(
  1673. 'second' => array(
  1674. '#weight' => 10,
  1675. '#markup' => $second,
  1676. ),
  1677. 'first' => array(
  1678. '#weight' => 0,
  1679. '#markup' => $first,
  1680. ),
  1681. '#sorted' => TRUE,
  1682. );
  1683. $output = drupal_render($elements);
  1684. // The elements should appear in output in the same order as the array.
  1685. $this->assertTrue(strpos($output, $second) < strpos($output, $first), 'Elements were not sorted.');
  1686. }
  1687. /**
  1688. * Test #attached functionality in children elements.
  1689. */
  1690. function testDrupalRenderChildrenAttached() {
  1691. // The cache system is turned off for POST requests.
  1692. $request_method = $_SERVER['REQUEST_METHOD'];
  1693. $_SERVER['REQUEST_METHOD'] = 'GET';
  1694. // Create an element with a child and subchild. Each element loads a
  1695. // different JavaScript file using #attached.
  1696. $parent_js = drupal_get_path('module', 'user') . '/user.js';
  1697. $child_js = drupal_get_path('module', 'forum') . '/forum.js';
  1698. $subchild_js = drupal_get_path('module', 'book') . '/book.js';
  1699. $element = array(
  1700. '#type' => 'fieldset',
  1701. '#cache' => array(
  1702. 'keys' => array('simpletest', 'drupal_render', 'children_attached'),
  1703. ),
  1704. '#attached' => array('js' => array($parent_js)),
  1705. '#title' => 'Parent',
  1706. );
  1707. $element['child'] = array(
  1708. '#type' => 'fieldset',
  1709. '#attached' => array('js' => array($child_js)),
  1710. '#title' => 'Child',
  1711. );
  1712. $element['child']['subchild'] = array(
  1713. '#attached' => array('js' => array($subchild_js)),
  1714. '#markup' => 'Subchild',
  1715. );
  1716. // Render the element and verify the presence of #attached JavaScript.
  1717. drupal_render($element);
  1718. $scripts = drupal_get_js();
  1719. $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included.');
  1720. $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included.');
  1721. $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included.');
  1722. // Load the element from cache and verify the presence of the #attached
  1723. // JavaScript.
  1724. drupal_static_reset('drupal_add_js');
  1725. $this->assertTrue(drupal_render_cache_get($element), 'The element was retrieved from cache.');
  1726. $scripts = drupal_get_js();
  1727. $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included when loading from cache.');
  1728. $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included when loading from cache.');
  1729. $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included when loading from cache.');
  1730. $_SERVER['REQUEST_METHOD'] = $request_method;
  1731. }
  1732. /**
  1733. * Test passing arguments to the theme function.
  1734. */
  1735. function testDrupalRenderThemeArguments() {
  1736. $element = array(
  1737. '#theme' => 'common_test_foo',
  1738. );
  1739. // Test that defaults work.
  1740. $this->assertEqual(drupal_render($element), 'foobar', 'Defaults work');
  1741. $element = array(
  1742. '#theme' => 'common_test_foo',
  1743. '#foo' => $this->randomName(),
  1744. '#bar' => $this->randomName(),
  1745. );
  1746. // Test that passing arguments to the theme function works.
  1747. $this->assertEqual(drupal_render($element), $element['#foo'] . $element['#bar'], 'Passing arguments to theme functions works');
  1748. }
  1749. /**
  1750. * Test rendering form elements without passing through form_builder().
  1751. */
  1752. function testDrupalRenderFormElements() {
  1753. // Define a series of form elements.
  1754. $element = array(
  1755. '#type' => 'button',
  1756. '#value' => $this->randomName(),
  1757. );
  1758. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'submit'));
  1759. $element = array(
  1760. '#type' => 'textfield',
  1761. '#title' => $this->randomName(),
  1762. '#value' => $this->randomName(),
  1763. );
  1764. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'text'));
  1765. $element = array(
  1766. '#type' => 'password',
  1767. '#title' => $this->randomName(),
  1768. );
  1769. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'password'));
  1770. $element = array(
  1771. '#type' => 'textarea',
  1772. '#title' => $this->randomName(),
  1773. '#value' => $this->randomName(),
  1774. );
  1775. $this->assertRenderedElement($element, '//textarea');
  1776. $element = array(
  1777. '#type' => 'radio',
  1778. '#title' => $this->randomName(),
  1779. '#value' => FALSE,
  1780. );
  1781. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'radio'));
  1782. $element = array(
  1783. '#type' => 'checkbox',
  1784. '#title' => $this->randomName(),
  1785. );
  1786. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'checkbox'));
  1787. $element = array(
  1788. '#type' => 'select',
  1789. '#title' => $this->randomName(),
  1790. '#options' => array(
  1791. 0 => $this->randomName(),
  1792. 1 => $this->randomName(),
  1793. ),
  1794. );
  1795. $this->assertRenderedElement($element, '//select');
  1796. $element = array(
  1797. '#type' => 'file',
  1798. '#title' => $this->randomName(),
  1799. );
  1800. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'file'));
  1801. $element = array(
  1802. '#type' => 'item',
  1803. '#title' => $this->randomName(),
  1804. '#markup' => $this->randomName(),
  1805. );
  1806. $this->assertRenderedElement($element, '//div[contains(@class, :class) and contains(., :markup)]/label[contains(., :label)]', array(
  1807. ':class' => 'form-type-item',
  1808. ':markup' => $element['#markup'],
  1809. ':label' => $element['#title'],
  1810. ));
  1811. $element = array(
  1812. '#type' => 'hidden',
  1813. '#title' => $this->randomName(),
  1814. '#value' => $this->randomName(),
  1815. );
  1816. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'hidden'));
  1817. $element = array(
  1818. '#type' => 'link',
  1819. '#title' => $this->randomName(),
  1820. '#href' => $this->randomName(),
  1821. '#options' => array(
  1822. 'absolute' => TRUE,
  1823. ),
  1824. );
  1825. $this->assertRenderedElement($element, '//a[@href=:href and contains(., :title)]', array(
  1826. ':href' => url($element['#href'], array('absolute' => TRUE)),
  1827. ':title' => $element['#title'],
  1828. ));
  1829. $element = array(
  1830. '#type' => 'fieldset',
  1831. '#title' => $this->randomName(),
  1832. );
  1833. $this->assertRenderedElement($element, '//fieldset/legend[contains(., :title)]', array(
  1834. ':title' => $element['#title'],
  1835. ));
  1836. $element['item'] = array(
  1837. '#type' => 'item',
  1838. '#title' => $this->randomName(),
  1839. '#markup' => $this->randomName(),
  1840. );
  1841. $this->assertRenderedElement($element, '//fieldset/div/div[contains(@class, :class) and contains(., :markup)]', array(
  1842. ':class' => 'form-type-item',
  1843. ':markup' => $element['item']['#markup'],
  1844. ));
  1845. }
  1846. protected function assertRenderedElement(array $element, $xpath, array $xpath_args = array()) {
  1847. $original_element = $element;
  1848. $this->drupalSetContent(drupal_render($element));
  1849. $this->verbose('<pre>' . check_plain(var_export($original_element, TRUE)) . '</pre>'
  1850. . '<pre>' . check_plain(var_export($element, TRUE)) . '</pre>'
  1851. . '<hr />' . $this->drupalGetContent()
  1852. );
  1853. // @see DrupalWebTestCase::xpath()
  1854. $xpath = $this->buildXPathQuery($xpath, $xpath_args);
  1855. $element += array('#value' => NULL);
  1856. $this->assertFieldByXPath($xpath, $element['#value'], format_string('#type @type was properly rendered.', array(
  1857. '@type' => var_export($element['#type'], TRUE),
  1858. )));
  1859. }
  1860. /**
  1861. * Tests caching of render items.
  1862. */
  1863. function testDrupalRenderCache() {
  1864. // Force a request via GET.
  1865. $request_method = $_SERVER['REQUEST_METHOD'];
  1866. $_SERVER['REQUEST_METHOD'] = 'GET';
  1867. // Create an empty element.
  1868. $test_element = array(
  1869. '#cache' => array(
  1870. 'cid' => 'render_cache_test',
  1871. ),
  1872. '#markup' => '',
  1873. );
  1874. // Render the element and confirm that it goes through the rendering
  1875. // process (which will set $element['#printed']).
  1876. $element = $test_element;
  1877. drupal_render($element);
  1878. $this->assertTrue(isset($element['#printed']), 'No cache hit');
  1879. // Render the element again and confirm that it is retrieved from the cache
  1880. // instead (so $element['#printed'] will not be set).
  1881. $element = $test_element;
  1882. drupal_render($element);
  1883. $this->assertFalse(isset($element['#printed']), 'Cache hit');
  1884. // Test that user 1 does not share the cache with other users who have the
  1885. // same roles, even when DRUPAL_CACHE_PER_ROLE is used.
  1886. $user1 = user_load(1);
  1887. $first_authenticated_user = $this->drupalCreateUser();
  1888. $second_authenticated_user = $this->drupalCreateUser();
  1889. $user1->roles = array_intersect_key($user1->roles, array(DRUPAL_AUTHENTICATED_RID => TRUE));
  1890. user_save($user1);
  1891. // Load all the accounts again, to make sure we have complete account
  1892. // objects.
  1893. $user1 = user_load(1);
  1894. $first_authenticated_user = user_load($first_authenticated_user->uid);
  1895. $second_authenticated_user = user_load($second_authenticated_user->uid);
  1896. $this->assertEqual($user1->roles, $first_authenticated_user->roles, 'User 1 has the same roles as an authenticated user.');
  1897. // Impersonate user 1 and render content that only user 1 should have
  1898. // permission to see.
  1899. $original_user = $GLOBALS['user'];
  1900. $original_session_state = drupal_save_session();
  1901. drupal_save_session(FALSE);
  1902. $GLOBALS['user'] = $user1;
  1903. $test_element = array(
  1904. '#cache' => array(
  1905. 'keys' => array('test'),
  1906. 'granularity' => DRUPAL_CACHE_PER_ROLE,
  1907. ),
  1908. );
  1909. $element = $test_element;
  1910. $element['#markup'] = 'content for user 1';
  1911. $output = drupal_render($element);
  1912. $this->assertEqual($output, 'content for user 1');
  1913. // Verify the cache is working by rendering the same element but with
  1914. // different markup passed in; the result should be the same.
  1915. $element = $test_element;
  1916. $element['#markup'] = 'should not be used';
  1917. $output = drupal_render($element);
  1918. $this->assertEqual($output, 'content for user 1');
  1919. // Verify that the first authenticated user does not see the same content
  1920. // as user 1.
  1921. $GLOBALS['user'] = $first_authenticated_user;
  1922. $element = $test_element;
  1923. $element['#markup'] = 'content for authenticated users';
  1924. $output = drupal_render($element);
  1925. $this->assertEqual($output, 'content for authenticated users');
  1926. // Verify that the second authenticated user shares the cache with the
  1927. // first authenticated user.
  1928. $GLOBALS['user'] = $second_authenticated_user;
  1929. $element = $test_element;
  1930. $element['#markup'] = 'should not be used';
  1931. $output = drupal_render($element);
  1932. $this->assertEqual($output, 'content for authenticated users');
  1933. // Restore the original logged-in user.
  1934. $GLOBALS['user'] = $original_user;
  1935. drupal_save_session($original_session_state);
  1936. // Restore the previous request method.
  1937. $_SERVER['REQUEST_METHOD'] = $request_method;
  1938. }
  1939. }
  1940. /**
  1941. * Test for valid_url().
  1942. */
  1943. class ValidUrlTestCase extends DrupalUnitTestCase {
  1944. public static function getInfo() {
  1945. return array(
  1946. 'name' => 'Valid URL',
  1947. 'description' => "Performs tests on Drupal's valid URL function.",
  1948. 'group' => 'System'
  1949. );
  1950. }
  1951. /**
  1952. * Test valid absolute URLs.
  1953. */
  1954. function testValidAbsolute() {
  1955. $url_schemes = array('http', 'https', 'ftp');
  1956. $valid_absolute_urls = array(
  1957. 'example.com',
  1958. 'www.example.com',
  1959. 'ex-ample.com',
  1960. '3xampl3.com',
  1961. 'example.com/paren(the)sis',
  1962. 'example.com/index.html#pagetop',
  1963. 'example.com:8080',
  1964. 'subdomain.example.com',
  1965. 'example.com/index.php?q=node',
  1966. 'example.com/index.php?q=node&param=false',
  1967. 'user@www.example.com',
  1968. 'user:pass@www.example.com:8080/login.php?do=login&style=%23#pagetop',
  1969. '127.0.0.1',
  1970. 'example.org?',
  1971. 'john%20doe:secret:foo@example.org/',
  1972. 'example.org/~,$\'*;',
  1973. 'caf%C3%A9.example.org',
  1974. '[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
  1975. );
  1976. foreach ($url_schemes as $scheme) {
  1977. foreach ($valid_absolute_urls as $url) {
  1978. $test_url = $scheme . '://' . $url;
  1979. $valid_url = valid_url($test_url, TRUE);
  1980. $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
  1981. }
  1982. }
  1983. }
  1984. /**
  1985. * Test invalid absolute URLs.
  1986. */
  1987. function testInvalidAbsolute() {
  1988. $url_schemes = array('http', 'https', 'ftp');
  1989. $invalid_ablosule_urls = array(
  1990. '',
  1991. 'ex!ample.com',
  1992. 'ex%ample.com',
  1993. );
  1994. foreach ($url_schemes as $scheme) {
  1995. foreach ($invalid_ablosule_urls as $url) {
  1996. $test_url = $scheme . '://' . $url;
  1997. $valid_url = valid_url($test_url, TRUE);
  1998. $this->assertFalse($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
  1999. }
  2000. }
  2001. }
  2002. /**
  2003. * Test valid relative URLs.
  2004. */
  2005. function testValidRelative() {
  2006. $valid_relative_urls = array(
  2007. 'paren(the)sis',
  2008. 'index.html#pagetop',
  2009. 'index.php?q=node',
  2010. 'index.php?q=node&param=false',
  2011. 'login.php?do=login&style=%23#pagetop',
  2012. );
  2013. foreach (array('', '/') as $front) {
  2014. foreach ($valid_relative_urls as $url) {
  2015. $test_url = $front . $url;
  2016. $valid_url = valid_url($test_url);
  2017. $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
  2018. }
  2019. }
  2020. }
  2021. /**
  2022. * Test invalid relative URLs.
  2023. */
  2024. function testInvalidRelative() {
  2025. $invalid_relative_urls = array(
  2026. 'ex^mple',
  2027. 'example<>',
  2028. 'ex%ample',
  2029. );
  2030. foreach (array('', '/') as $front) {
  2031. foreach ($invalid_relative_urls as $url) {
  2032. $test_url = $front . $url;
  2033. $valid_url = valid_url($test_url);
  2034. $this->assertFALSE($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
  2035. }
  2036. }
  2037. }
  2038. }
  2039. /**
  2040. * Tests for CRUD API functions.
  2041. */
  2042. class DrupalDataApiTest extends DrupalWebTestCase {
  2043. public static function getInfo() {
  2044. return array(
  2045. 'name' => 'Data API functions',
  2046. 'description' => 'Tests the performance of CRUD APIs.',
  2047. 'group' => 'System',
  2048. );
  2049. }
  2050. function setUp() {
  2051. parent::setUp('database_test');
  2052. }
  2053. /**
  2054. * Test the drupal_write_record() API function.
  2055. */
  2056. function testDrupalWriteRecord() {
  2057. // Insert a record - no columns allow NULL values.
  2058. $person = new stdClass();
  2059. $person->name = 'John';
  2060. $person->unknown_column = 123;
  2061. $insert_result = drupal_write_record('test', $person);
  2062. $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.');
  2063. $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
  2064. $this->assertIdentical($person->age, 0, 'Age field set to default value.');
  2065. $this->assertIdentical($person->job, 'Undefined', 'Job field set to default value.');
  2066. // Verify that the record was inserted.
  2067. $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2068. $this->assertIdentical($result->name, 'John', 'Name field set.');
  2069. $this->assertIdentical($result->age, '0', 'Age field set to default value.');
  2070. $this->assertIdentical($result->job, 'Undefined', 'Job field set to default value.');
  2071. $this->assertFalse(isset($result->unknown_column), 'Unknown column was ignored.');
  2072. // Update the newly created record.
  2073. $person->name = 'Peter';
  2074. $person->age = 27;
  2075. $person->job = NULL;
  2076. $update_result = drupal_write_record('test', $person, array('id'));
  2077. $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a record updated with drupal_write_record() for table with single-field primary key.');
  2078. // Verify that the record was updated.
  2079. $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2080. $this->assertIdentical($result->name, 'Peter', 'Name field set.');
  2081. $this->assertIdentical($result->age, '27', 'Age field set.');
  2082. $this->assertIdentical($result->job, '', 'Job field set and cast to string.');
  2083. // Try to insert NULL in columns that does not allow this.
  2084. $person = new stdClass();
  2085. $person->name = 'Ringo';
  2086. $person->age = NULL;
  2087. $person->job = NULL;
  2088. $insert_result = drupal_write_record('test', $person);
  2089. $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
  2090. $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2091. $this->assertIdentical($result->name, 'Ringo', 'Name field set.');
  2092. $this->assertIdentical($result->age, '0', 'Age field set.');
  2093. $this->assertIdentical($result->job, '', 'Job field set.');
  2094. // Insert a record - the "age" column allows NULL.
  2095. $person = new stdClass();
  2096. $person->name = 'Paul';
  2097. $person->age = NULL;
  2098. $insert_result = drupal_write_record('test_null', $person);
  2099. $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
  2100. $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2101. $this->assertIdentical($result->name, 'Paul', 'Name field set.');
  2102. $this->assertIdentical($result->age, NULL, 'Age field set.');
  2103. // Insert a record - do not specify the value of a column that allows NULL.
  2104. $person = new stdClass();
  2105. $person->name = 'Meredith';
  2106. $insert_result = drupal_write_record('test_null', $person);
  2107. $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
  2108. $this->assertIdentical($person->age, 0, 'Age field set to default value.');
  2109. $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2110. $this->assertIdentical($result->name, 'Meredith', 'Name field set.');
  2111. $this->assertIdentical($result->age, '0', 'Age field set to default value.');
  2112. // Update the newly created record.
  2113. $person->name = 'Mary';
  2114. $person->age = NULL;
  2115. $update_result = drupal_write_record('test_null', $person, array('id'));
  2116. $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2117. $this->assertIdentical($result->name, 'Mary', 'Name field set.');
  2118. $this->assertIdentical($result->age, NULL, 'Age field set.');
  2119. // Insert a record - the "data" column should be serialized.
  2120. $person = new stdClass();
  2121. $person->name = 'Dave';
  2122. $update_result = drupal_write_record('test_serialized', $person);
  2123. $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2124. $this->assertIdentical($result->name, 'Dave', 'Name field set.');
  2125. $this->assertIdentical($result->info, NULL, 'Info field set.');
  2126. $person->info = array();
  2127. $update_result = drupal_write_record('test_serialized', $person, array('id'));
  2128. $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2129. $this->assertIdentical(unserialize($result->info), array(), 'Info field updated.');
  2130. // Update the serialized record.
  2131. $data = array('foo' => 'bar', 1 => 2, 'empty' => '', 'null' => NULL);
  2132. $person->info = $data;
  2133. $update_result = drupal_write_record('test_serialized', $person, array('id'));
  2134. $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  2135. $this->assertIdentical(unserialize($result->info), $data, 'Info field updated.');
  2136. // Run an update query where no field values are changed. The database
  2137. // layer should return zero for number of affected rows, but
  2138. // db_write_record() should still return SAVED_UPDATED.
  2139. $update_result = drupal_write_record('test_null', $person, array('id'));
  2140. $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a valid update is run without changing any values.');
  2141. // Insert an object record for a table with a multi-field primary key.
  2142. $node_access = new stdClass();
  2143. $node_access->nid = mt_rand();
  2144. $node_access->gid = mt_rand();
  2145. $node_access->realm = $this->randomName();
  2146. $insert_result = drupal_write_record('node_access', $node_access);
  2147. $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.');
  2148. // Update the record.
  2149. $update_result = drupal_write_record('node_access', $node_access, array('nid', 'gid', 'realm'));
  2150. $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.');
  2151. }
  2152. }
  2153. /**
  2154. * Tests Simpletest error and exception collector.
  2155. */
  2156. class DrupalErrorCollectionUnitTest extends DrupalWebTestCase {
  2157. /**
  2158. * Errors triggered during the test.
  2159. *
  2160. * Errors are intercepted by the overriden implementation
  2161. * of DrupalWebTestCase::error below.
  2162. *
  2163. * @var Array
  2164. */
  2165. protected $collectedErrors = array();
  2166. public static function getInfo() {
  2167. return array(
  2168. 'name' => 'SimpleTest error collector',
  2169. 'description' => 'Performs tests on the Simpletest error and exception collector.',
  2170. 'group' => 'SimpleTest',
  2171. );
  2172. }
  2173. function setUp() {
  2174. parent::setUp('system_test', 'error_test');
  2175. }
  2176. /**
  2177. * Test that simpletest collects errors from the tested site.
  2178. */
  2179. function testErrorCollect() {
  2180. $this->collectedErrors = array();
  2181. $this->drupalGet('error-test/generate-warnings-with-report');
  2182. $this->assertEqual(count($this->collectedErrors), 3, 'Three errors were collected');
  2183. if (count($this->collectedErrors) == 3) {
  2184. $this->assertError($this->collectedErrors[0], 'Notice', 'error_test_generate_warnings()', 'error_test.module', 'Undefined variable: bananas');
  2185. $this->assertError($this->collectedErrors[1], 'Warning', 'error_test_generate_warnings()', 'error_test.module', 'Division by zero');
  2186. $this->assertError($this->collectedErrors[2], 'User warning', 'error_test_generate_warnings()', 'error_test.module', 'Drupal is awesome');
  2187. }
  2188. else {
  2189. // Give back the errors to the log report.
  2190. foreach ($this->collectedErrors as $error) {
  2191. parent::error($error['message'], $error['group'], $error['caller']);
  2192. }
  2193. }
  2194. }
  2195. /**
  2196. * Error handler that collects errors in an array.
  2197. *
  2198. * This test class is trying to verify that simpletest correctly sees errors
  2199. * and warnings. However, it can't generate errors and warnings that
  2200. * propagate up to the testing framework itself, or these tests would always
  2201. * fail. So, this special copy of error() doesn't propagate the errors up
  2202. * the class hierarchy. It just stuffs them into a protected collectedErrors
  2203. * array for various assertions to inspect.
  2204. */
  2205. protected function error($message = '', $group = 'Other', array $caller = NULL) {
  2206. // Due to a WTF elsewhere, simpletest treats debug() and verbose()
  2207. // messages as if they were an 'error'. But, we don't want to collect
  2208. // those here. This function just wants to collect the real errors (PHP
  2209. // notices, PHP fatal errors, etc.), and let all the 'errors' from the
  2210. // 'User notice' group bubble up to the parent classes to be handled (and
  2211. // eventually displayed) as normal.
  2212. if ($group == 'User notice') {
  2213. parent::error($message, $group, $caller);
  2214. }
  2215. // Everything else should be collected but not propagated.
  2216. else {
  2217. $this->collectedErrors[] = array(
  2218. 'message' => $message,
  2219. 'group' => $group,
  2220. 'caller' => $caller
  2221. );
  2222. }
  2223. }
  2224. /**
  2225. * Assert that a collected error matches what we are expecting.
  2226. */
  2227. function assertError($error, $group, $function, $file, $message = NULL) {
  2228. $this->assertEqual($error['group'], $group, format_string("Group was %group", array('%group' => $group)));
  2229. $this->assertEqual($error['caller']['function'], $function, format_string("Function was %function", array('%function' => $function)));
  2230. $this->assertEqual(drupal_basename($error['caller']['file']), $file, format_string("File was %file", array('%file' => $file)));
  2231. if (isset($message)) {
  2232. $this->assertEqual($error['message'], $message, format_string("Message was %message", array('%message' => $message)));
  2233. }
  2234. }
  2235. }
  2236. /**
  2237. * Test the drupal_parse_info_file() API function.
  2238. */
  2239. class ParseInfoFilesTestCase extends DrupalUnitTestCase {
  2240. public static function getInfo() {
  2241. return array(
  2242. 'name' => 'Parsing .info files',
  2243. 'description' => 'Tests parsing .info files.',
  2244. 'group' => 'System',
  2245. );
  2246. }
  2247. /**
  2248. * Parse an example .info file an verify the results.
  2249. */
  2250. function testParseInfoFile() {
  2251. $info_values = drupal_parse_info_file(drupal_get_path('module', 'simpletest') . '/tests/common_test_info.txt');
  2252. $this->assertEqual($info_values['simple_string'], 'A simple string', 'Simple string value was parsed correctly.', 'System');
  2253. $this->assertEqual($info_values['simple_constant'], WATCHDOG_INFO, 'Constant value was parsed correctly.', 'System');
  2254. $this->assertEqual($info_values['double_colon'], 'dummyClassName::', 'Value containing double-colon was parsed correctly.', 'System');
  2255. }
  2256. }
  2257. /**
  2258. * Tests for the drupal_system_listing() function.
  2259. */
  2260. class DrupalSystemListingTestCase extends DrupalWebTestCase {
  2261. /**
  2262. * Use the testing profile; this is needed for testDirectoryPrecedence().
  2263. */
  2264. protected $profile = 'testing';
  2265. public static function getInfo() {
  2266. return array(
  2267. 'name' => 'Drupal system listing',
  2268. 'description' => 'Tests the mechanism for scanning system directories in drupal_system_listing().',
  2269. 'group' => 'System',
  2270. );
  2271. }
  2272. /**
  2273. * Test that files in different directories take precedence as expected.
  2274. */
  2275. function testDirectoryPrecedence() {
  2276. // Define the module files we will search for, and the directory precedence
  2277. // we expect.
  2278. $expected_directories = array(
  2279. // When the copy of the module in the profile directory is incompatible
  2280. // with Drupal core, the copy in the core modules directory takes
  2281. // precedence.
  2282. 'drupal_system_listing_incompatible_test' => array(
  2283. 'modules/simpletest/tests',
  2284. 'profiles/testing/modules',
  2285. ),
  2286. // When both copies of the module are compatible with Drupal core, the
  2287. // copy in the profile directory takes precedence.
  2288. 'drupal_system_listing_compatible_test' => array(
  2289. 'profiles/testing/modules',
  2290. 'modules/simpletest/tests',
  2291. ),
  2292. );
  2293. // This test relies on two versions of the same module existing in
  2294. // different places in the filesystem. Without that, the test has no
  2295. // meaning, so assert their presence first.
  2296. foreach ($expected_directories as $module => $directories) {
  2297. foreach ($directories as $directory) {
  2298. $filename = "$directory/$module/$module.module";
  2299. $this->assertTrue(file_exists(DRUPAL_ROOT . '/' . $filename), format_string('@filename exists.', array('@filename' => $filename)));
  2300. }
  2301. }
  2302. // Now scan the directories and check that the files take precedence as
  2303. // expected.
  2304. $files = drupal_system_listing('/\.module$/', 'modules', 'name', 1);
  2305. foreach ($expected_directories as $module => $directories) {
  2306. $expected_directory = array_shift($directories);
  2307. $expected_filename = "$expected_directory/$module/$module.module";
  2308. $this->assertEqual($files[$module]->uri, $expected_filename, format_string('Module @module was found at @filename.', array('@module' => $module, '@filename' => $expected_filename)));
  2309. }
  2310. }
  2311. }
  2312. /**
  2313. * Tests for the format_date() function.
  2314. */
  2315. class FormatDateUnitTest extends DrupalWebTestCase {
  2316. /**
  2317. * Arbitrary langcode for a custom language.
  2318. */
  2319. const LANGCODE = 'xx';
  2320. public static function getInfo() {
  2321. return array(
  2322. 'name' => 'Format date',
  2323. 'description' => 'Test the format_date() function.',
  2324. 'group' => 'System',
  2325. );
  2326. }
  2327. function setUp() {
  2328. parent::setUp('locale');
  2329. variable_set('configurable_timezones', 1);
  2330. variable_set('date_format_long', 'l, j. F Y - G:i');
  2331. variable_set('date_format_medium', 'j. F Y - G:i');
  2332. variable_set('date_format_short', 'Y M j - g:ia');
  2333. variable_set('locale_custom_strings_' . self::LANGCODE, array(
  2334. '' => array('Sunday' => 'domingo'),
  2335. 'Long month name' => array('March' => 'marzo'),
  2336. ));
  2337. $this->refreshVariables();
  2338. }
  2339. /**
  2340. * Test admin-defined formats in format_date().
  2341. */
  2342. function testAdminDefinedFormatDate() {
  2343. // Create an admin user.
  2344. $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
  2345. $this->drupalLogin($this->admin_user);
  2346. // Add new date format.
  2347. $admin_date_format = 'j M y';
  2348. $edit = array('date_format' => $admin_date_format);
  2349. $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, 'Add format');
  2350. // Add a new date format which just differs in the case.
  2351. $admin_date_format_uppercase = 'j M Y';
  2352. $edit = array('date_format' => $admin_date_format_uppercase);
  2353. $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
  2354. $this->assertText(t('Custom date format added.'));
  2355. // Add new date type.
  2356. $edit = array(
  2357. 'date_type' => 'Example Style',
  2358. 'machine_name' => 'example_style',
  2359. 'date_format' => $admin_date_format,
  2360. );
  2361. $this->drupalPost('admin/config/regional/date-time/types/add', $edit, 'Add date type');
  2362. // Add a second date format with a different case than the first.
  2363. $edit = array(
  2364. 'machine_name' => 'example_style_uppercase',
  2365. 'date_type' => 'Example Style Uppercase',
  2366. 'date_format' => $admin_date_format_uppercase,
  2367. );
  2368. $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
  2369. $this->assertText(t('New date type added successfully.'));
  2370. $timestamp = strtotime('2007-03-10T00:00:00+00:00');
  2371. $this->assertIdentical(format_date($timestamp, 'example_style', '', 'America/Los_Angeles'), '9 Mar 07', 'Test format_date() using an admin-defined date type.');
  2372. $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.');
  2373. $this->assertIdentical(format_date($timestamp, 'undefined_style'), format_date($timestamp, 'medium'), 'Test format_date() defaulting to medium when $type not found.');
  2374. }
  2375. /**
  2376. * Tests for the format_date() function.
  2377. */
  2378. function testFormatDate() {
  2379. global $user, $language;
  2380. $timestamp = strtotime('2007-03-26T00:00:00+00:00');
  2381. $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.');
  2382. $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.');
  2383. $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.');
  2384. $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.');
  2385. $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.');
  2386. $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.');
  2387. // Create an admin user and add Spanish language.
  2388. $admin_user = $this->drupalCreateUser(array('administer languages'));
  2389. $this->drupalLogin($admin_user);
  2390. $edit = array(
  2391. 'langcode' => self::LANGCODE,
  2392. 'name' => self::LANGCODE,
  2393. 'native' => self::LANGCODE,
  2394. 'direction' => LANGUAGE_LTR,
  2395. 'prefix' => self::LANGCODE,
  2396. );
  2397. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  2398. // Create a test user to carry out the tests.
  2399. $test_user = $this->drupalCreateUser();
  2400. $this->drupalLogin($test_user);
  2401. $edit = array('language' => self::LANGCODE, 'mail' => $test_user->mail, 'timezone' => 'America/Los_Angeles');
  2402. $this->drupalPost('user/' . $test_user->uid . '/edit', $edit, t('Save'));
  2403. // Disable session saving as we are about to modify the global $user.
  2404. drupal_save_session(FALSE);
  2405. // Save the original user and language and then replace it with the test user and language.
  2406. $real_user = $user;
  2407. $user = user_load($test_user->uid, TRUE);
  2408. $real_language = $language->language;
  2409. $language->language = $user->language;
  2410. // Simulate a Drupal bootstrap with the logged-in user.
  2411. date_default_timezone_set(drupal_get_user_timezone());
  2412. $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.');
  2413. $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.');
  2414. $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.');
  2415. $this->assertIdentical(format_date($timestamp, 'long'), 'domingo, 25. marzo 2007 - 17:00', 'Test long date format.');
  2416. $this->assertIdentical(format_date($timestamp, 'medium'), '25. marzo 2007 - 17:00', 'Test medium date format.');
  2417. $this->assertIdentical(format_date($timestamp, 'short'), '2007 Mar 25 - 5:00pm', 'Test short date format.');
  2418. $this->assertIdentical(format_date($timestamp), '25. marzo 2007 - 17:00', 'Test default date format.');
  2419. // Restore the original user and language, and enable session saving.
  2420. $user = $real_user;
  2421. $language->language = $real_language;
  2422. // Restore default time zone.
  2423. date_default_timezone_set(drupal_get_user_timezone());
  2424. drupal_save_session(TRUE);
  2425. }
  2426. }
  2427. /**
  2428. * Tests for the format_date() function.
  2429. */
  2430. class DrupalAttributesUnitTest extends DrupalUnitTestCase {
  2431. public static function getInfo() {
  2432. return array(
  2433. 'name' => 'HTML Attributes',
  2434. 'description' => 'Perform unit tests on the drupal_attributes() function.',
  2435. 'group' => 'System',
  2436. );
  2437. }
  2438. /**
  2439. * Tests that drupal_html_class() cleans the class name properly.
  2440. */
  2441. function testDrupalAttributes() {
  2442. // Verify that special characters are HTML encoded.
  2443. $this->assertIdentical(drupal_attributes(array('title' => '&"\'<>')), ' title="&amp;&quot;&#039;&lt;&gt;"', 'HTML encode attribute values.');
  2444. // Verify multi-value attributes are concatenated with spaces.
  2445. $attributes = array('class' => array('first', 'last'));
  2446. $this->assertIdentical(drupal_attributes(array('class' => array('first', 'last'))), ' class="first last"', 'Concatenate multi-value attributes.');
  2447. // Verify empty attribute values are rendered.
  2448. $this->assertIdentical(drupal_attributes(array('alt' => '')), ' alt=""', 'Empty attribute value #1.');
  2449. $this->assertIdentical(drupal_attributes(array('alt' => NULL)), ' alt=""', 'Empty attribute value #2.');
  2450. // Verify multiple attributes are rendered.
  2451. $attributes = array(
  2452. 'id' => 'id-test',
  2453. 'class' => array('first', 'last'),
  2454. 'alt' => 'Alternate',
  2455. );
  2456. $this->assertIdentical(drupal_attributes($attributes), ' id="id-test" class="first last" alt="Alternate"', 'Multiple attributes.');
  2457. // Verify empty attributes array is rendered.
  2458. $this->assertIdentical(drupal_attributes(array()), '', 'Empty attributes array.');
  2459. }
  2460. }
  2461. /**
  2462. * Tests converting PHP variables to JSON strings and back.
  2463. */
  2464. class DrupalJSONTest extends DrupalUnitTestCase {
  2465. public static function getInfo() {
  2466. return array(
  2467. 'name' => 'JSON',
  2468. 'description' => 'Perform unit tests on the drupal_json_encode() and drupal_json_decode() functions.',
  2469. 'group' => 'System',
  2470. );
  2471. }
  2472. /**
  2473. * Tests converting PHP variables to JSON strings and back.
  2474. */
  2475. function testJSON() {
  2476. // Setup a string with the full ASCII table.
  2477. // @todo: Add tests for non-ASCII characters and Unicode.
  2478. $str = '';
  2479. for ($i=0; $i < 128; $i++) {
  2480. $str .= chr($i);
  2481. }
  2482. // Characters that must be escaped.
  2483. // We check for unescaped " separately.
  2484. $html_unsafe = array('<', '>', '\'', '&');
  2485. // The following are the encoded forms of: < > ' & "
  2486. $html_unsafe_escaped = array('\u003C', '\u003E', '\u0027', '\u0026', '\u0022');
  2487. // Verify there aren't character encoding problems with the source string.
  2488. $this->assertIdentical(strlen($str), 128, 'A string with the full ASCII table has the correct length.');
  2489. foreach ($html_unsafe as $char) {
  2490. $this->assertTrue(strpos($str, $char) > 0, format_string('A string with the full ASCII table includes @s.', array('@s' => $char)));
  2491. }
  2492. // Verify that JSON encoding produces a string with all of the characters.
  2493. $json = drupal_json_encode($str);
  2494. $this->assertTrue(strlen($json) > strlen($str), 'A JSON encoded string is larger than the source string.');
  2495. // The first and last characters should be ", and no others.
  2496. $this->assertTrue($json[0] == '"', 'A JSON encoded string begins with ".');
  2497. $this->assertTrue($json[strlen($json) - 1] == '"', 'A JSON encoded string ends with ".');
  2498. $this->assertTrue(substr_count($json, '"') == 2, 'A JSON encoded string contains exactly two ".');
  2499. // Verify that encoding/decoding is reversible.
  2500. $json_decoded = drupal_json_decode($json);
  2501. $this->assertIdentical($str, $json_decoded, 'Encoding a string to JSON and decoding back results in the original string.');
  2502. // Verify reversibility for structured data. Also verify that necessary
  2503. // characters are escaped.
  2504. $source = array(TRUE, FALSE, 0, 1, '0', '1', $str, array('key1' => $str, 'key2' => array('nested' => TRUE)));
  2505. $json = drupal_json_encode($source);
  2506. foreach ($html_unsafe as $char) {
  2507. $this->assertTrue(strpos($json, $char) === FALSE, format_string('A JSON encoded string does not contain @s.', array('@s' => $char)));
  2508. }
  2509. // Verify that JSON encoding escapes the HTML unsafe characters
  2510. foreach ($html_unsafe_escaped as $char) {
  2511. $this->assertTrue(strpos($json, $char) > 0, format_string('A JSON encoded string contains @s.', array('@s' => $char)));
  2512. }
  2513. $json_decoded = drupal_json_decode($json);
  2514. $this->assertNotIdentical($source, $json, 'An array encoded in JSON is not identical to the source.');
  2515. $this->assertIdentical($source, $json_decoded, 'Encoding structured data to JSON and decoding back results in the original data.');
  2516. }
  2517. }
  2518. /**
  2519. * Tests for RDF namespaces XML serialization.
  2520. */
  2521. class DrupalGetRdfNamespacesTestCase extends DrupalWebTestCase {
  2522. public static function getInfo() {
  2523. return array(
  2524. 'name' => 'RDF namespaces XML serialization tests',
  2525. 'description' => 'Confirm that the serialization of RDF namespaces via drupal_get_rdf_namespaces() is output and parsed correctly in the XHTML document.',
  2526. 'group' => 'System',
  2527. );
  2528. }
  2529. function setUp() {
  2530. parent::setUp('rdf', 'rdf_test');
  2531. }
  2532. /**
  2533. * Test RDF namespaces.
  2534. */
  2535. function testGetRdfNamespaces() {
  2536. // Fetches the front page and extracts XML namespaces.
  2537. $this->drupalGet('');
  2538. $xml = new SimpleXMLElement($this->content);
  2539. $ns = $xml->getDocNamespaces();
  2540. $this->assertEqual($ns['rdfs'], 'http://www.w3.org/2000/01/rdf-schema#', 'A prefix declared once is displayed.');
  2541. $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.');
  2542. $this->assertEqual($ns['foaf1'], 'http://xmlns.com/foaf/0.1/', 'Two prefixes can be assigned the same namespace.');
  2543. $this->assertTrue(!isset($ns['dc']), 'A prefix with conflicting namespaces is discarded.');
  2544. }
  2545. }
  2546. /**
  2547. * Basic tests for drupal_add_feed().
  2548. */
  2549. class DrupalAddFeedTestCase extends DrupalWebTestCase {
  2550. public static function getInfo() {
  2551. return array(
  2552. 'name' => 'drupal_add_feed() tests',
  2553. 'description' => 'Make sure that drupal_add_feed() works correctly with various constructs.',
  2554. 'group' => 'System',
  2555. );
  2556. }
  2557. /**
  2558. * Test drupal_add_feed() with paths, URLs, and titles.
  2559. */
  2560. function testBasicFeedAddNoTitle() {
  2561. $path = $this->randomName(12);
  2562. $external_url = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
  2563. $fully_qualified_local_url = url($this->randomName(12), array('absolute' => TRUE));
  2564. $path_for_title = $this->randomName(12);
  2565. $external_for_title = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
  2566. $fully_qualified_for_title = url($this->randomName(12), array('absolute' => TRUE));
  2567. // Possible permutations of drupal_add_feed() to test.
  2568. // - 'input_url': the path passed to drupal_add_feed(),
  2569. // - 'output_url': the expected URL to be found in the header.
  2570. // - 'title' == the title of the feed as passed into drupal_add_feed().
  2571. $urls = array(
  2572. 'path without title' => array(
  2573. 'input_url' => $path,
  2574. 'output_url' => url($path, array('absolute' => TRUE)),
  2575. 'title' => '',
  2576. ),
  2577. 'external URL without title' => array(
  2578. 'input_url' => $external_url,
  2579. 'output_url' => $external_url,
  2580. 'title' => '',
  2581. ),
  2582. 'local URL without title' => array(
  2583. 'input_url' => $fully_qualified_local_url,
  2584. 'output_url' => $fully_qualified_local_url,
  2585. 'title' => '',
  2586. ),
  2587. 'path with title' => array(
  2588. 'input_url' => $path_for_title,
  2589. 'output_url' => url($path_for_title, array('absolute' => TRUE)),
  2590. 'title' => $this->randomName(12),
  2591. ),
  2592. 'external URL with title' => array(
  2593. 'input_url' => $external_for_title,
  2594. 'output_url' => $external_for_title,
  2595. 'title' => $this->randomName(12),
  2596. ),
  2597. 'local URL with title' => array(
  2598. 'input_url' => $fully_qualified_for_title,
  2599. 'output_url' => $fully_qualified_for_title,
  2600. 'title' => $this->randomName(12),
  2601. ),
  2602. );
  2603. foreach ($urls as $description => $feed_info) {
  2604. drupal_add_feed($feed_info['input_url'], $feed_info['title']);
  2605. }
  2606. $this->drupalSetContent(drupal_get_html_head());
  2607. foreach ($urls as $description => $feed_info) {
  2608. $this->assertPattern($this->urlToRSSLinkPattern($feed_info['output_url'], $feed_info['title']), format_string('Found correct feed header for %description', array('%description' => $description)));
  2609. }
  2610. }
  2611. /**
  2612. * Create a pattern representing the RSS feed in the page.
  2613. */
  2614. function urlToRSSLinkPattern($url, $title = '') {
  2615. // Escape any regular expression characters in the URL ('?' is the worst).
  2616. $url = preg_replace('/([+?.*])/', '[$0]', $url);
  2617. $generated_pattern = '%<link +rel="alternate" +type="application/rss.xml" +title="' . $title . '" +href="' . $url . '" */>%';
  2618. return $generated_pattern;
  2619. }
  2620. }
  2621. /**
  2622. * Test for theme_feed_icon().
  2623. */
  2624. class FeedIconTest extends DrupalWebTestCase {
  2625. public static function getInfo() {
  2626. return array(
  2627. 'name' => 'Feed icon',
  2628. 'description' => 'Check escaping of theme_feed_icon()',
  2629. 'group' => 'System',
  2630. );
  2631. }
  2632. /**
  2633. * Check that special characters are correctly escaped. Test for issue #1211668.
  2634. */
  2635. function testFeedIconEscaping() {
  2636. $variables = array();
  2637. $variables['url'] = 'node';
  2638. $variables['title'] = '<>&"\'';
  2639. $text = theme_feed_icon($variables);
  2640. preg_match('/title="(.*?)"/', $text, $matches);
  2641. $this->assertEqual($matches[1], 'Subscribe to &amp;&quot;&#039;', 'theme_feed_icon() escapes reserved HTML characters.');
  2642. }
  2643. }
  2644. /**
  2645. * Test array diff functions.
  2646. */
  2647. class ArrayDiffUnitTest extends DrupalUnitTestCase {
  2648. /**
  2649. * Array to use for testing.
  2650. *
  2651. * @var array
  2652. */
  2653. protected $array1;
  2654. /**
  2655. * Array to use for testing.
  2656. *
  2657. * @var array
  2658. */
  2659. protected $array2;
  2660. public static function getInfo() {
  2661. return array(
  2662. 'name' => 'Array differences',
  2663. 'description' => 'Performs tests on drupal_array_diff_assoc_recursive().',
  2664. 'group' => 'System',
  2665. );
  2666. }
  2667. function setUp() {
  2668. parent::setUp();
  2669. $this->array1 = array(
  2670. 'same' => 'yes',
  2671. 'different' => 'no',
  2672. 'array_empty_diff' => array(),
  2673. 'null' => NULL,
  2674. 'int_diff' => 1,
  2675. 'array_diff' => array('same' => 'same', 'array' => array('same' => 'same')),
  2676. 'array_compared_to_string' => array('value'),
  2677. 'string_compared_to_array' => 'value',
  2678. 'new' => 'new',
  2679. );
  2680. $this->array2 = array(
  2681. 'same' => 'yes',
  2682. 'different' => 'yes',
  2683. 'array_empty_diff' => array(),
  2684. 'null' => NULL,
  2685. 'int_diff' => '1',
  2686. 'array_diff' => array('same' => 'different', 'array' => array('same' => 'same')),
  2687. 'array_compared_to_string' => 'value',
  2688. 'string_compared_to_array' => array('value'),
  2689. );
  2690. }
  2691. /**
  2692. * Tests drupal_array_diff_assoc_recursive().
  2693. */
  2694. public function testArrayDiffAssocRecursive() {
  2695. $expected = array(
  2696. 'different' => 'no',
  2697. 'int_diff' => 1,
  2698. // The 'array' key should not be returned, as it's the same.
  2699. 'array_diff' => array('same' => 'same'),
  2700. 'array_compared_to_string' => array('value'),
  2701. 'string_compared_to_array' => 'value',
  2702. 'new' => 'new',
  2703. );
  2704. $this->assertIdentical(drupal_array_diff_assoc_recursive($this->array1, $this->array2), $expected);
  2705. }
  2706. }
  2707. /**
  2708. * Tests the functionality of drupal_get_query_array().
  2709. */
  2710. class DrupalGetQueryArrayTestCase extends DrupalWebTestCase {
  2711. public static function getInfo() {
  2712. return array(
  2713. 'name' => 'Query parsing using drupal_get_query_array()',
  2714. 'description' => 'Tests that drupal_get_query_array() correctly parses query parameters.',
  2715. 'group' => 'System',
  2716. );
  2717. }
  2718. /**
  2719. * Tests that drupal_get_query_array() correctly explodes query parameters.
  2720. */
  2721. public function testDrupalGetQueryArray() {
  2722. $url = "http://my.site.com/somepath?foo=/content/folder[@name='foo']/folder[@name='bar']";
  2723. $parsed = parse_url($url);
  2724. $result = drupal_get_query_array($parsed['query']);
  2725. $this->assertEqual($result['foo'], "/content/folder[@name='foo']/folder[@name='bar']", 'drupal_get_query_array() should only explode parameters on the first equals sign.');
  2726. }
  2727. }