common.test 128 KB

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