common.test 136 KB

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