common.test 133 KB

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