common.test 114 KB

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