common.test 112 KB

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