common.test 137 KB

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