common.test 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758
  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 rendering inline stylesheets with preprocessing off.
  604. */
  605. function testRenderInlineNoPreprocess() {
  606. $css = 'body { padding: 0px; }';
  607. drupal_add_css($css, array('type' => 'inline', 'preprocess' => FALSE));
  608. $styles = drupal_get_css();
  609. $this->assertTrue(strpos($styles, $css) > 0, 'Rendering non-preprocessed inline CSS adds it to the page.');
  610. }
  611. /**
  612. * Tests rendering inline stylesheets through a full page request.
  613. */
  614. function testRenderInlineFullPage() {
  615. $css = 'body { font-size: 254px; }';
  616. // Inline CSS is minified unless 'preprocess' => FALSE is passed as a
  617. // drupal_add_css() option.
  618. $expected = 'body{font-size:254px;}';
  619. // Create a node, using the PHP filter that tests drupal_add_css().
  620. $php_format_id = 'php_code';
  621. $settings = array(
  622. 'type' => 'page',
  623. 'body' => array(
  624. LANGUAGE_NONE => array(
  625. array(
  626. 'value' => t('This tests the inline CSS!') . "<?php drupal_add_css('$css', 'inline'); ?>",
  627. 'format' => $php_format_id,
  628. ),
  629. ),
  630. ),
  631. 'promote' => 1,
  632. );
  633. $node = $this->drupalCreateNode($settings);
  634. // Fetch the page.
  635. $this->drupalGet('node/' . $node->nid);
  636. $this->assertRaw($expected, 'Inline stylesheets appear in the full page rendering.');
  637. }
  638. /**
  639. * Test CSS ordering.
  640. */
  641. function testRenderOrder() {
  642. // A module CSS file.
  643. drupal_add_css(drupal_get_path('module', 'simpletest') . '/simpletest.css');
  644. // A few system CSS files, ordered in a strange way.
  645. $system_path = drupal_get_path('module', 'system');
  646. drupal_add_css($system_path . '/system.menus.css', array('group' => CSS_SYSTEM));
  647. drupal_add_css($system_path . '/system.base.css', array('group' => CSS_SYSTEM, 'weight' => -10));
  648. drupal_add_css($system_path . '/system.theme.css', array('group' => CSS_SYSTEM));
  649. $expected = array(
  650. $system_path . '/system.base.css',
  651. $system_path . '/system.menus.css',
  652. $system_path . '/system.theme.css',
  653. drupal_get_path('module', 'simpletest') . '/simpletest.css',
  654. );
  655. $styles = drupal_get_css();
  656. // Stylesheet URL may be the href of a LINK tag or in an @import statement
  657. // of a STYLE tag.
  658. if (preg_match_all('/(href="|url\(")' . preg_quote($GLOBALS['base_url'] . '/', '/') . '([^?]+)\?/', $styles, $matches)) {
  659. $result = $matches[2];
  660. }
  661. else {
  662. $result = array();
  663. }
  664. $this->assertIdentical($result, $expected, 'The CSS files are in the expected order.');
  665. }
  666. /**
  667. * Test CSS override.
  668. */
  669. function testRenderOverride() {
  670. $system = drupal_get_path('module', 'system');
  671. $simpletest = drupal_get_path('module', 'simpletest');
  672. drupal_add_css($system . '/system.base.css');
  673. drupal_add_css($simpletest . '/tests/system.base.css');
  674. // The dummy stylesheet should be the only one included.
  675. $styles = drupal_get_css();
  676. $this->assert(strpos($styles, $simpletest . '/tests/system.base.css') !== FALSE, 'The overriding CSS file is output.');
  677. $this->assert(strpos($styles, $system . '/system.base.css') === FALSE, 'The overridden CSS file is not output.');
  678. drupal_add_css($simpletest . '/tests/system.base.css');
  679. drupal_add_css($system . '/system.base.css');
  680. // The standard stylesheet should be the only one included.
  681. $styles = drupal_get_css();
  682. $this->assert(strpos($styles, $system . '/system.base.css') !== FALSE, 'The overriding CSS file is output.');
  683. $this->assert(strpos($styles, $simpletest . '/tests/system.base.css') === FALSE, 'The overridden CSS file is not output.');
  684. }
  685. /**
  686. * Tests Locale module's CSS Alter to include RTL overrides.
  687. */
  688. function testAlter() {
  689. // Switch the language to a right to left language and add system.base.css.
  690. global $language;
  691. $language->direction = LANGUAGE_RTL;
  692. $path = drupal_get_path('module', 'system');
  693. drupal_add_css($path . '/system.base.css');
  694. // Check to see if system.base-rtl.css was also added.
  695. $styles = drupal_get_css();
  696. $this->assert(strpos($styles, $path . '/system.base-rtl.css') !== FALSE, 'CSS is alterable as right to left overrides are added.');
  697. // Change the language back to left to right.
  698. $language->direction = LANGUAGE_LTR;
  699. }
  700. /**
  701. * Tests that the query string remains intact when adding CSS files that have
  702. * query string parameters.
  703. */
  704. function testAddCssFileWithQueryString() {
  705. $this->drupalGet('common-test/query-string');
  706. $query_string = variable_get('css_js_query_string', '0');
  707. $this->assertRaw(drupal_get_path('module', 'node') . '/node.css?' . $query_string, 'Query string was appended correctly to css.');
  708. $this->assertRaw(drupal_get_path('module', 'node') . '/node-fake.css?arg1=value1&amp;arg2=value2', 'Query string not escaped on a URI.');
  709. }
  710. }
  711. /**
  712. * Test for cleaning HTML identifiers.
  713. */
  714. class DrupalHTMLIdentifierTestCase extends DrupalUnitTestCase {
  715. public static function getInfo() {
  716. return array(
  717. 'name' => 'HTML identifiers',
  718. 'description' => 'Test the functions drupal_html_class(), drupal_html_id() and drupal_clean_css_identifier() for expected behavior',
  719. 'group' => 'System',
  720. );
  721. }
  722. /**
  723. * Tests that drupal_clean_css_identifier() cleans the identifier properly.
  724. */
  725. function testDrupalCleanCSSIdentifier() {
  726. // Verify that no valid ASCII characters are stripped from the identifier.
  727. $identifier = 'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789';
  728. $this->assertIdentical(drupal_clean_css_identifier($identifier, array()), $identifier, 'Verify valid ASCII characters pass through.');
  729. // Verify that valid UTF-8 characters are not stripped from the identifier.
  730. $identifier = '¡¢£¤¥';
  731. $this->assertIdentical(drupal_clean_css_identifier($identifier, array()), $identifier, 'Verify valid UTF-8 characters pass through.');
  732. // Verify that invalid characters (including non-breaking space) are stripped from the identifier.
  733. $this->assertIdentical(drupal_clean_css_identifier('invalid !"#$%&\'()*+,./:;<=>?@[\\]^`{|}~ identifier', array()), 'invalididentifier', 'Strip invalid characters.');
  734. }
  735. /**
  736. * Tests that drupal_html_class() cleans the class name properly.
  737. */
  738. function testDrupalHTMLClass() {
  739. // Verify Drupal coding standards are enforced.
  740. $this->assertIdentical(drupal_html_class('CLASS NAME_[Ü]'), 'class-name--ü', 'Enforce Drupal coding standards.');
  741. }
  742. /**
  743. * Tests that drupal_html_id() cleans the ID properly.
  744. */
  745. function testDrupalHTMLId() {
  746. // Verify that letters, digits, and hyphens are not stripped from the ID.
  747. $id = 'abcdefghijklmnopqrstuvwxyz-0123456789';
  748. $this->assertIdentical(drupal_html_id($id), $id, 'Verify valid characters pass through.');
  749. // Verify that invalid characters are stripped from the ID.
  750. $this->assertIdentical(drupal_html_id('invalid,./:@\\^`{Üidentifier'), 'invalididentifier', 'Strip invalid characters.');
  751. // Verify Drupal coding standards are enforced.
  752. $this->assertIdentical(drupal_html_id('ID NAME_[1]'), 'id-name-1', 'Enforce Drupal coding standards.');
  753. // Reset the static cache so we can ensure the unique id count is at zero.
  754. drupal_static_reset('drupal_html_id');
  755. // Clean up IDs with invalid starting characters.
  756. $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id', 'Test the uniqueness of IDs #1.');
  757. $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id--2', 'Test the uniqueness of IDs #2.');
  758. $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id--3', 'Test the uniqueness of IDs #3.');
  759. }
  760. }
  761. /**
  762. * CSS Unit Tests.
  763. */
  764. class CascadingStylesheetsUnitTest extends DrupalUnitTestCase {
  765. public static function getInfo() {
  766. return array(
  767. 'name' => 'CSS Unit Tests',
  768. 'description' => 'Unit tests on CSS functions like aggregation.',
  769. 'group' => 'System',
  770. );
  771. }
  772. /**
  773. * Tests basic CSS loading with and without optimization via drupal_load_stylesheet().
  774. *
  775. * Known tests:
  776. * - Retain white-space in selectors. (http://drupal.org/node/472820)
  777. * - Proper URLs in imported files. (http://drupal.org/node/265719)
  778. * - Retain pseudo-selectors. (http://drupal.org/node/460448)
  779. */
  780. function testLoadCssBasic() {
  781. // Array of files to test living in 'simpletest/files/css_test_files/'.
  782. // - Original: name.css
  783. // - Unoptimized expected content: name.css.unoptimized.css
  784. // - Optimized expected content: name.css.optimized.css
  785. $testfiles = array(
  786. 'css_input_without_import.css',
  787. 'css_input_with_import.css',
  788. 'comment_hacks.css'
  789. );
  790. $path = drupal_get_path('module', 'simpletest') . '/files/css_test_files';
  791. foreach ($testfiles as $file) {
  792. $expected = file_get_contents("$path/$file.unoptimized.css");
  793. $unoptimized_output = drupal_load_stylesheet("$path/$file.unoptimized.css", FALSE);
  794. $this->assertEqual($unoptimized_output, $expected, format_string('Unoptimized CSS file has expected contents (@file)', array('@file' => $file)));
  795. $expected = file_get_contents("$path/$file.optimized.css");
  796. $optimized_output = drupal_load_stylesheet("$path/$file", TRUE);
  797. $this->assertEqual($optimized_output, $expected, format_string('Optimized CSS file has expected contents (@file)', array('@file' => $file)));
  798. // Repeat the tests by accessing the stylesheets by URL.
  799. $expected = file_get_contents("$path/$file.unoptimized.css");
  800. $unoptimized_output_url = drupal_load_stylesheet($GLOBALS['base_url'] . "/$path/$file.unoptimized.css", FALSE);
  801. $this->assertEqual($unoptimized_output, $expected, format_string('Unoptimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
  802. $expected = file_get_contents("$path/$file.optimized.css");
  803. $optimized_output = drupal_load_stylesheet($GLOBALS['base_url'] . "/$path/$file", TRUE);
  804. $this->assertEqual($optimized_output, $expected, format_string('Optimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
  805. }
  806. }
  807. }
  808. /**
  809. * Test drupal_http_request().
  810. */
  811. class DrupalHTTPRequestTestCase extends DrupalWebTestCase {
  812. public static function getInfo() {
  813. return array(
  814. 'name' => 'Drupal HTTP request',
  815. 'description' => "Performs tests on Drupal's HTTP request mechanism.",
  816. 'group' => 'System'
  817. );
  818. }
  819. function setUp() {
  820. parent::setUp('system_test', 'locale');
  821. }
  822. function testDrupalHTTPRequest() {
  823. global $is_https;
  824. // Parse URL schema.
  825. $missing_scheme = drupal_http_request('example.com/path');
  826. $this->assertEqual($missing_scheme->code, -1002, 'Returned with "-1002" error code.');
  827. $this->assertEqual($missing_scheme->error, 'missing schema', 'Returned with "missing schema" error message.');
  828. $unable_to_parse = drupal_http_request('http:///path');
  829. $this->assertEqual($unable_to_parse->code, -1001, 'Returned with "-1001" error code.');
  830. $this->assertEqual($unable_to_parse->error, 'unable to parse URL', 'Returned with "unable to parse URL" error message.');
  831. // Fetch page.
  832. $result = drupal_http_request(url('node', array('absolute' => TRUE)));
  833. $this->assertEqual($result->code, 200, 'Fetched page successfully.');
  834. $this->drupalSetContent($result->data);
  835. $this->assertTitle(t('Welcome to @site-name | @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), 'Site title matches.');
  836. // Test that code and status message is returned.
  837. $result = drupal_http_request(url('pagedoesnotexist', array('absolute' => TRUE)));
  838. $this->assertTrue(!empty($result->protocol), 'Result protocol is returned.');
  839. $this->assertEqual($result->code, '404', 'Result code is 404');
  840. $this->assertEqual($result->status_message, 'Not Found', 'Result status message is "Not Found"');
  841. // Skip the timeout tests when the testing environment is HTTPS because
  842. // stream_set_timeout() does not work for SSL connections.
  843. // @link http://bugs.php.net/bug.php?id=47929
  844. if (!$is_https) {
  845. // Test that timeout is respected. The test machine is expected to be able
  846. // to make the connection (i.e. complete the fsockopen()) in 2 seconds and
  847. // return within a total of 5 seconds. If the test machine is extremely
  848. // slow, the test will fail. fsockopen() has been seen to time out in
  849. // slightly less than the specified timeout, so allow a little slack on
  850. // the minimum expected time (i.e. 1.8 instead of 2).
  851. timer_start(__METHOD__);
  852. $result = drupal_http_request(url('system-test/sleep/10', array('absolute' => TRUE)), array('timeout' => 2));
  853. $time = timer_read(__METHOD__) / 1000;
  854. $this->assertTrue(1.8 < $time && $time < 5, format_string('Request timed out (%time seconds).', array('%time' => $time)));
  855. $this->assertTrue($result->error, 'An error message was returned.');
  856. $this->assertEqual($result->code, HTTP_REQUEST_TIMEOUT, 'Proper error code was returned.');
  857. }
  858. }
  859. function testDrupalHTTPRequestBasicAuth() {
  860. $username = $this->randomName();
  861. $password = $this->randomName();
  862. $url = url('system-test/auth', array('absolute' => TRUE));
  863. $auth = str_replace('://', '://' . $username . ':' . $password . '@', $url);
  864. $result = drupal_http_request($auth);
  865. $this->drupalSetContent($result->data);
  866. $this->assertRaw($username, '$_SERVER["PHP_AUTH_USER"] is passed correctly.');
  867. $this->assertRaw($password, '$_SERVER["PHP_AUTH_PW"] is passed correctly.');
  868. }
  869. function testDrupalHTTPRequestRedirect() {
  870. $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 1));
  871. $this->assertEqual($redirect_301->redirect_code, 301, 'drupal_http_request follows the 301 redirect.');
  872. $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 0));
  873. $this->assertFalse(isset($redirect_301->redirect_code), 'drupal_http_request does not follow 301 redirect if max_redirects = 0.');
  874. $redirect_invalid = drupal_http_request(url('system-test/redirect-noscheme', array('absolute' => TRUE)), array('max_redirects' => 1));
  875. $this->assertEqual($redirect_invalid->code, -1002, format_string('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
  876. $this->assertEqual($redirect_invalid->error, 'missing schema', format_string('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
  877. $redirect_invalid = drupal_http_request(url('system-test/redirect-noparse', array('absolute' => TRUE)), array('max_redirects' => 1));
  878. $this->assertEqual($redirect_invalid->code, -1001, format_string('301 redirect to invalid URL returned with error message code "!error".', array('!error' => $redirect_invalid->error)));
  879. $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)));
  880. $redirect_invalid = drupal_http_request(url('system-test/redirect-invalid-scheme', array('absolute' => TRUE)), array('max_redirects' => 1));
  881. $this->assertEqual($redirect_invalid->code, -1003, format_string('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
  882. $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)));
  883. $redirect_302 = drupal_http_request(url('system-test/redirect/302', array('absolute' => TRUE)), array('max_redirects' => 1));
  884. $this->assertEqual($redirect_302->redirect_code, 302, 'drupal_http_request follows the 302 redirect.');
  885. $redirect_302 = drupal_http_request(url('system-test/redirect/302', array('absolute' => TRUE)), array('max_redirects' => 0));
  886. $this->assertFalse(isset($redirect_302->redirect_code), 'drupal_http_request does not follow 302 redirect if $retry = 0.');
  887. $redirect_307 = drupal_http_request(url('system-test/redirect/307', array('absolute' => TRUE)), array('max_redirects' => 1));
  888. $this->assertEqual($redirect_307->redirect_code, 307, 'drupal_http_request follows the 307 redirect.');
  889. $redirect_307 = drupal_http_request(url('system-test/redirect/307', array('absolute' => TRUE)), array('max_redirects' => 0));
  890. $this->assertFalse(isset($redirect_307->redirect_code), 'drupal_http_request does not follow 307 redirect if max_redirects = 0.');
  891. $multiple_redirect_final_url = url('system-test/multiple-redirects/0', array('absolute' => TRUE));
  892. $multiple_redirect_1 = drupal_http_request(url('system-test/multiple-redirects/1', array('absolute' => TRUE)), array('max_redirects' => 1));
  893. $this->assertEqual($multiple_redirect_1->redirect_url, $multiple_redirect_final_url, 'redirect_url contains the final redirection location after 1 redirect.');
  894. $multiple_redirect_3 = drupal_http_request(url('system-test/multiple-redirects/3', array('absolute' => TRUE)), array('max_redirects' => 3));
  895. $this->assertEqual($multiple_redirect_3->redirect_url, $multiple_redirect_final_url, 'redirect_url contains the final redirection location after 3 redirects.');
  896. }
  897. /**
  898. * Tests Content-language headers generated by Drupal.
  899. */
  900. function testDrupalHTTPRequestHeaders() {
  901. // Check the default header.
  902. $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
  903. $this->assertEqual($request->headers['content-language'], 'en', 'Content-Language HTTP header is English.');
  904. // Add German language and set as default.
  905. locale_add_language('de', 'German', 'Deutsch', LANGUAGE_LTR, '', '', TRUE, TRUE);
  906. // Request front page and check for matching Content-Language.
  907. $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
  908. $this->assertEqual($request->headers['content-language'], 'de', 'Content-Language HTTP header is German.');
  909. }
  910. }
  911. /**
  912. * Testing drupal_add_region_content and drupal_get_region_content.
  913. */
  914. class DrupalSetContentTestCase extends DrupalWebTestCase {
  915. public static function getInfo() {
  916. return array(
  917. 'name' => 'Drupal set/get regions',
  918. 'description' => 'Performs tests on setting and retrieiving content from theme regions.',
  919. 'group' => 'System'
  920. );
  921. }
  922. /**
  923. * Test setting and retrieving content for theme regions.
  924. */
  925. function testRegions() {
  926. global $theme_key;
  927. $block_regions = array_keys(system_region_list($theme_key));
  928. $delimiter = $this->randomName(32);
  929. $values = array();
  930. // Set some random content for each region available.
  931. foreach ($block_regions as $region) {
  932. $first_chunk = $this->randomName(32);
  933. drupal_add_region_content($region, $first_chunk);
  934. $second_chunk = $this->randomName(32);
  935. drupal_add_region_content($region, $second_chunk);
  936. // Store the expected result for a drupal_get_region_content call for this region.
  937. $values[$region] = $first_chunk . $delimiter . $second_chunk;
  938. }
  939. // Ensure drupal_get_region_content returns expected results when fetching all regions.
  940. $content = drupal_get_region_content(NULL, $delimiter);
  941. foreach ($content as $region => $region_content) {
  942. $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching all regions', array('@region' => $region)));
  943. }
  944. // Ensure drupal_get_region_content returns expected results when fetching a single region.
  945. foreach ($block_regions as $region) {
  946. $region_content = drupal_get_region_content($region, $delimiter);
  947. $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching single region.', array('@region' => $region)));
  948. }
  949. }
  950. }
  951. /**
  952. * Testing drupal_goto and hook_drupal_goto_alter().
  953. */
  954. class DrupalGotoTest extends DrupalWebTestCase {
  955. public static function getInfo() {
  956. return array(
  957. 'name' => 'Drupal goto',
  958. 'description' => 'Performs tests on the drupal_goto function and hook_drupal_goto_alter',
  959. 'group' => 'System'
  960. );
  961. }
  962. function setUp() {
  963. parent::setUp('common_test');
  964. }
  965. /**
  966. * Test drupal_goto().
  967. */
  968. function testDrupalGoto() {
  969. $this->drupalGet('common-test/drupal_goto/redirect');
  970. $headers = $this->drupalGetHeaders(TRUE);
  971. list(, $status) = explode(' ', $headers[0][':status'], 3);
  972. $this->assertEqual($status, 302, 'Expected response code was sent.');
  973. $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
  974. $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
  975. $this->drupalGet('common-test/drupal_goto/redirect_advanced');
  976. $headers = $this->drupalGetHeaders(TRUE);
  977. list(, $status) = explode(' ', $headers[0][':status'], 3);
  978. $this->assertEqual($status, 301, 'Expected response code was sent.');
  979. $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
  980. $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('query' => array('foo' => '123'), 'absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
  981. // Test that drupal_goto() respects ?destination=xxx. Use an complicated URL
  982. // to test that the path is encoded and decoded properly.
  983. $destination = 'common-test/drupal_goto/destination?foo=%2525&bar=123';
  984. $this->drupalGet('common-test/drupal_goto/redirect', array('query' => array('destination' => $destination)));
  985. $this->assertText('drupal_goto', 'Drupal goto redirect with destination succeeded.');
  986. $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.');
  987. }
  988. /**
  989. * Test hook_drupal_goto_alter().
  990. */
  991. function testDrupalGotoAlter() {
  992. $this->drupalGet('common-test/drupal_goto/redirect_fail');
  993. $this->assertNoText(t("Drupal goto failed to stop program"), "Drupal goto stopped program.");
  994. $this->assertNoText('drupal_goto_fail', "Drupal goto redirect failed.");
  995. }
  996. /**
  997. * Test drupal_get_destination().
  998. */
  999. function testDrupalGetDestination() {
  1000. $query = $this->randomName(10);
  1001. // Verify that a 'destination' query string is used as destination.
  1002. $this->drupalGet('common-test/destination', array('query' => array('destination' => $query)));
  1003. $this->assertText('The destination: ' . $query, 'The given query string destination is determined as destination.');
  1004. // Verify that the current path is used as destination.
  1005. $this->drupalGet('common-test/destination', array('query' => array($query => NULL)));
  1006. $url = 'common-test/destination?' . $query;
  1007. $this->assertText('The destination: ' . $url, 'The current path is determined as destination.');
  1008. }
  1009. }
  1010. /**
  1011. * Tests for the JavaScript system.
  1012. */
  1013. class JavaScriptTestCase extends DrupalWebTestCase {
  1014. /**
  1015. * Store configured value for JavaScript preprocessing.
  1016. */
  1017. protected $preprocess_js = NULL;
  1018. public static function getInfo() {
  1019. return array(
  1020. 'name' => 'JavaScript',
  1021. 'description' => 'Tests the JavaScript system.',
  1022. 'group' => 'System'
  1023. );
  1024. }
  1025. function setUp() {
  1026. // Enable Locale and SimpleTest in the test environment.
  1027. parent::setUp('locale', 'simpletest', 'common_test');
  1028. // Disable preprocessing
  1029. $this->preprocess_js = variable_get('preprocess_js', 0);
  1030. variable_set('preprocess_js', 0);
  1031. // Reset drupal_add_js() and drupal_add_library() statics before each test.
  1032. drupal_static_reset('drupal_add_js');
  1033. drupal_static_reset('drupal_add_library');
  1034. }
  1035. function tearDown() {
  1036. // Restore configured value for JavaScript preprocessing.
  1037. variable_set('preprocess_js', $this->preprocess_js);
  1038. parent::tearDown();
  1039. }
  1040. /**
  1041. * Test default JavaScript is empty.
  1042. */
  1043. function testDefault() {
  1044. $this->assertEqual(array(), drupal_add_js(), 'Default JavaScript is empty.');
  1045. }
  1046. /**
  1047. * Test adding a JavaScript file.
  1048. */
  1049. function testAddFile() {
  1050. $javascript = drupal_add_js('misc/collapse.js');
  1051. $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when a file is added.');
  1052. $this->assertTrue(array_key_exists('misc/drupal.js', $javascript), 'Drupal.js is added when file is added.');
  1053. $this->assertTrue(array_key_exists('misc/collapse.js', $javascript), 'JavaScript files are correctly added.');
  1054. $this->assertEqual(base_path(), $javascript['settings']['data'][0]['basePath'], 'Base path JavaScript setting is correctly set.');
  1055. url('', array('prefix' => &$prefix));
  1056. $this->assertEqual(empty($prefix) ? '' : $prefix, $javascript['settings']['data'][1]['pathPrefix'], 'Path prefix JavaScript setting is correctly set.');
  1057. }
  1058. /**
  1059. * Test adding settings.
  1060. */
  1061. function testAddSetting() {
  1062. $javascript = drupal_add_js(array('drupal' => 'rocks', 'dries' => 280342800), 'setting');
  1063. $this->assertEqual(280342800, $javascript['settings']['data'][2]['dries'], 'JavaScript setting is set correctly.');
  1064. $this->assertEqual('rocks', $javascript['settings']['data'][2]['drupal'], 'The other JavaScript setting is set correctly.');
  1065. }
  1066. /**
  1067. * Tests adding an external JavaScript File.
  1068. */
  1069. function testAddExternal() {
  1070. $path = 'http://example.com/script.js';
  1071. $javascript = drupal_add_js($path, 'external');
  1072. $this->assertTrue(array_key_exists('http://example.com/script.js', $javascript), 'Added an external JavaScript file.');
  1073. }
  1074. /**
  1075. * Test drupal_get_js() for JavaScript settings.
  1076. */
  1077. function testHeaderSetting() {
  1078. // Only the second of these two entries should appear in Drupal.settings.
  1079. drupal_add_js(array('commonTest' => 'commonTestShouldNotAppear'), 'setting');
  1080. drupal_add_js(array('commonTest' => 'commonTestShouldAppear'), 'setting');
  1081. // All three of these entries should appear in Drupal.settings.
  1082. drupal_add_js(array('commonTestArray' => array('commonTestValue0')), 'setting');
  1083. drupal_add_js(array('commonTestArray' => array('commonTestValue1')), 'setting');
  1084. drupal_add_js(array('commonTestArray' => array('commonTestValue2')), 'setting');
  1085. // Only the second of these two entries should appear in Drupal.settings.
  1086. drupal_add_js(array('commonTestArray' => array('key' => 'commonTestOldValue')), 'setting');
  1087. drupal_add_js(array('commonTestArray' => array('key' => 'commonTestNewValue')), 'setting');
  1088. $javascript = drupal_get_js('header');
  1089. $this->assertTrue(strpos($javascript, 'basePath') > 0, 'Rendered JavaScript header returns basePath setting.');
  1090. $this->assertTrue(strpos($javascript, 'misc/jquery.js') > 0, 'Rendered JavaScript header includes jQuery.');
  1091. $this->assertTrue(strpos($javascript, 'pathPrefix') > 0, 'Rendered JavaScript header returns pathPrefix setting.');
  1092. // Test whether drupal_add_js can be used to override a previous setting.
  1093. $this->assertTrue(strpos($javascript, 'commonTestShouldAppear') > 0, 'Rendered JavaScript header returns custom setting.');
  1094. $this->assertTrue(strpos($javascript, 'commonTestShouldNotAppear') === FALSE, 'drupal_add_js() correctly overrides a custom setting.');
  1095. // Test whether drupal_add_js can be used to add numerically indexed values
  1096. // to an array.
  1097. $array_values_appear = strpos($javascript, 'commonTestValue0') > 0 && strpos($javascript, 'commonTestValue1') > 0 && strpos($javascript, 'commonTestValue2') > 0;
  1098. $this->assertTrue($array_values_appear, 'drupal_add_js() correctly adds settings to the end of an indexed array.');
  1099. // Test whether drupal_add_js can be used to override the entry for an
  1100. // existing key in an associative array.
  1101. $associative_array_override = strpos($javascript, 'commonTestNewValue') > 0 && strpos($javascript, 'commonTestOldValue') === FALSE;
  1102. $this->assertTrue($associative_array_override, 'drupal_add_js() correctly overrides settings within an associative array.');
  1103. }
  1104. /**
  1105. * Test to see if resetting the JavaScript empties the cache.
  1106. */
  1107. function testReset() {
  1108. drupal_add_js('misc/collapse.js');
  1109. drupal_static_reset('drupal_add_js');
  1110. $this->assertEqual(array(), drupal_add_js(), 'Resetting the JavaScript correctly empties the cache.');
  1111. }
  1112. /**
  1113. * Test adding inline scripts.
  1114. */
  1115. function testAddInline() {
  1116. $inline = 'jQuery(function () { });';
  1117. $javascript = drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
  1118. $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when inline scripts are added.');
  1119. $data = end($javascript);
  1120. $this->assertEqual($inline, $data['data'], 'Inline JavaScript is correctly added to the footer.');
  1121. }
  1122. /**
  1123. * Test rendering an external JavaScript file.
  1124. */
  1125. function testRenderExternal() {
  1126. $external = 'http://example.com/example.js';
  1127. drupal_add_js($external, 'external');
  1128. $javascript = drupal_get_js();
  1129. // Local files have a base_path() prefix, external files should not.
  1130. $this->assertTrue(strpos($javascript, 'src="' . $external) > 0, 'Rendering an external JavaScript file.');
  1131. }
  1132. /**
  1133. * Test drupal_get_js() with a footer scope.
  1134. */
  1135. function testFooterHTML() {
  1136. $inline = 'jQuery(function () { });';
  1137. drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
  1138. $javascript = drupal_get_js('footer');
  1139. $this->assertTrue(strpos($javascript, $inline) > 0, 'Rendered JavaScript footer returns the inline code.');
  1140. }
  1141. /**
  1142. * Test drupal_add_js() sets preproccess to false when cache is set to false.
  1143. */
  1144. function testNoCache() {
  1145. $javascript = drupal_add_js('misc/collapse.js', array('cache' => FALSE));
  1146. $this->assertFalse($javascript['misc/collapse.js']['preprocess'], 'Setting cache to FALSE sets proprocess to FALSE when adding JavaScript.');
  1147. }
  1148. /**
  1149. * Test adding a JavaScript file with a different group.
  1150. */
  1151. function testDifferentGroup() {
  1152. $javascript = drupal_add_js('misc/collapse.js', array('group' => JS_THEME));
  1153. $this->assertEqual($javascript['misc/collapse.js']['group'], JS_THEME, 'Adding a JavaScript file with a different group caches the given group.');
  1154. }
  1155. /**
  1156. * Test adding a JavaScript file with a different weight.
  1157. */
  1158. function testDifferentWeight() {
  1159. $javascript = drupal_add_js('misc/collapse.js', array('weight' => 2));
  1160. $this->assertEqual($javascript['misc/collapse.js']['weight'], 2, 'Adding a JavaScript file with a different weight caches the given weight.');
  1161. }
  1162. /**
  1163. * Tests JavaScript aggregation when files are added to a different scope.
  1164. */
  1165. function testAggregationOrder() {
  1166. // Enable JavaScript aggregation.
  1167. variable_set('preprocess_js', 1);
  1168. drupal_static_reset('drupal_add_js');
  1169. // Add two JavaScript files to the current request and build the cache.
  1170. drupal_add_js('misc/ajax.js');
  1171. drupal_add_js('misc/autocomplete.js');
  1172. $js_items = drupal_add_js();
  1173. drupal_build_js_cache(array(
  1174. 'misc/ajax.js' => $js_items['misc/ajax.js'],
  1175. 'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
  1176. ));
  1177. // Store the expected key for the first item in the cache.
  1178. $cache = array_keys(variable_get('drupal_js_cache_files', array()));
  1179. $expected_key = $cache[0];
  1180. // Reset variables and add a file in a different scope first.
  1181. variable_del('drupal_js_cache_files');
  1182. drupal_static_reset('drupal_add_js');
  1183. drupal_add_js('some/custom/javascript_file.js', array('scope' => 'footer'));
  1184. drupal_add_js('misc/ajax.js');
  1185. drupal_add_js('misc/autocomplete.js');
  1186. // Rebuild the cache.
  1187. $js_items = drupal_add_js();
  1188. drupal_build_js_cache(array(
  1189. 'misc/ajax.js' => $js_items['misc/ajax.js'],
  1190. 'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
  1191. ));
  1192. // Compare the expected key for the first file to the current one.
  1193. $cache = array_keys(variable_get('drupal_js_cache_files', array()));
  1194. $key = $cache[0];
  1195. $this->assertEqual($key, $expected_key, 'JavaScript aggregation is not affected by ordering in different scopes.');
  1196. }
  1197. /**
  1198. * Test JavaScript ordering.
  1199. */
  1200. function testRenderOrder() {
  1201. // Add a bunch of JavaScript in strange ordering.
  1202. drupal_add_js('(function($){alert("Weight 5 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
  1203. drupal_add_js('(function($){alert("Weight 0 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
  1204. drupal_add_js('(function($){alert("Weight 0 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
  1205. drupal_add_js('(function($){alert("Weight -8 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
  1206. drupal_add_js('(function($){alert("Weight -8 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
  1207. drupal_add_js('(function($){alert("Weight -8 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
  1208. drupal_add_js('http://example.com/example.js?Weight -5 #1', array('type' => 'external', 'scope' => 'footer', 'weight' => -5));
  1209. drupal_add_js('(function($){alert("Weight -8 #4");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
  1210. drupal_add_js('(function($){alert("Weight 5 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
  1211. drupal_add_js('(function($){alert("Weight 0 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
  1212. // Construct the expected result from the regex.
  1213. $expected = array(
  1214. "-8 #1",
  1215. "-8 #2",
  1216. "-8 #3",
  1217. "-8 #4",
  1218. "-5 #1", // The external script.
  1219. "0 #1",
  1220. "0 #2",
  1221. "0 #3",
  1222. "5 #1",
  1223. "5 #2",
  1224. );
  1225. // Retrieve the rendered JavaScript and test against the regex.
  1226. $js = drupal_get_js('footer');
  1227. $matches = array();
  1228. if (preg_match_all('/Weight\s([-0-9]+\s[#0-9]+)/', $js, $matches)) {
  1229. $result = $matches[1];
  1230. }
  1231. else {
  1232. $result = array();
  1233. }
  1234. $this->assertIdentical($result, $expected, 'JavaScript is added in the expected weight order.');
  1235. }
  1236. /**
  1237. * Test rendering the JavaScript with a file's weight above jQuery's.
  1238. */
  1239. function testRenderDifferentWeight() {
  1240. // JavaScript files are sorted first by group, then by the 'every_page'
  1241. // flag, then by weight (see drupal_sort_css_js()), so to test the effect of
  1242. // weight, we need the other two options to be the same.
  1243. drupal_add_js('misc/collapse.js', array('group' => JS_LIBRARY, 'every_page' => TRUE, 'weight' => -21));
  1244. $javascript = drupal_get_js();
  1245. $this->assertTrue(strpos($javascript, 'misc/collapse.js') < strpos($javascript, 'misc/jquery.js'), 'Rendering a JavaScript file above jQuery.');
  1246. }
  1247. /**
  1248. * Test altering a JavaScript's weight via hook_js_alter().
  1249. *
  1250. * @see simpletest_js_alter()
  1251. */
  1252. function testAlter() {
  1253. // Add both tableselect.js and simpletest.js, with a larger weight on SimpleTest.
  1254. drupal_add_js('misc/tableselect.js');
  1255. drupal_add_js(drupal_get_path('module', 'simpletest') . '/simpletest.js', array('weight' => 9999));
  1256. // Render the JavaScript, testing if simpletest.js was altered to be before
  1257. // tableselect.js. See simpletest_js_alter() to see where this alteration
  1258. // takes place.
  1259. $javascript = drupal_get_js();
  1260. $this->assertTrue(strpos($javascript, 'simpletest.js') < strpos($javascript, 'misc/tableselect.js'), 'Altering JavaScript weight through the alter hook.');
  1261. }
  1262. /**
  1263. * Adds a library to the page and tests for both its JavaScript and its CSS.
  1264. */
  1265. function testLibraryRender() {
  1266. $result = drupal_add_library('system', 'farbtastic');
  1267. $this->assertTrue($result !== FALSE, 'Library was added without errors.');
  1268. $scripts = drupal_get_js();
  1269. $styles = drupal_get_css();
  1270. $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), 'JavaScript of library was added to the page.');
  1271. $this->assertTrue(strpos($styles, 'misc/farbtastic/farbtastic.css'), 'Stylesheet of library was added to the page.');
  1272. }
  1273. /**
  1274. * Adds a JavaScript library to the page and alters it.
  1275. *
  1276. * @see common_test_library_alter()
  1277. */
  1278. function testLibraryAlter() {
  1279. // Verify that common_test altered the title of Farbtastic.
  1280. $library = drupal_get_library('system', 'farbtastic');
  1281. $this->assertEqual($library['title'], 'Farbtastic: Altered Library', 'Registered libraries were altered.');
  1282. // common_test_library_alter() also added a dependency on jQuery Form.
  1283. drupal_add_library('system', 'farbtastic');
  1284. $scripts = drupal_get_js();
  1285. $this->assertTrue(strpos($scripts, 'misc/jquery.form.js'), 'Altered library dependencies are added to the page.');
  1286. }
  1287. /**
  1288. * Tests that multiple modules can implement the same library.
  1289. *
  1290. * @see common_test_library()
  1291. */
  1292. function testLibraryNameConflicts() {
  1293. $farbtastic = drupal_get_library('common_test', 'farbtastic');
  1294. $this->assertEqual($farbtastic['title'], 'Custom Farbtastic Library', 'Alternative libraries can be added to the page.');
  1295. }
  1296. /**
  1297. * Tests non-existing libraries.
  1298. */
  1299. function testLibraryUnknown() {
  1300. $result = drupal_get_library('unknown', 'unknown');
  1301. $this->assertFalse($result, 'Unknown library returned FALSE.');
  1302. drupal_static_reset('drupal_get_library');
  1303. $result = drupal_add_library('unknown', 'unknown');
  1304. $this->assertFalse($result, 'Unknown library returned FALSE.');
  1305. $scripts = drupal_get_js();
  1306. $this->assertTrue(strpos($scripts, 'unknown') === FALSE, 'Unknown library was not added to the page.');
  1307. }
  1308. /**
  1309. * Tests the addition of libraries through the #attached['library'] property.
  1310. */
  1311. function testAttachedLibrary() {
  1312. $element['#attached']['library'][] = array('system', 'farbtastic');
  1313. drupal_render($element);
  1314. $scripts = drupal_get_js();
  1315. $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), 'The attached_library property adds the additional libraries.');
  1316. }
  1317. /**
  1318. * Tests retrieval of libraries via drupal_get_library().
  1319. */
  1320. function testGetLibrary() {
  1321. // Retrieve all libraries registered by a module.
  1322. $libraries = drupal_get_library('common_test');
  1323. $this->assertTrue(isset($libraries['farbtastic']), 'Retrieved all module libraries.');
  1324. // Retrieve all libraries for a module not implementing hook_library().
  1325. // Note: This test installs Locale module.
  1326. $libraries = drupal_get_library('locale');
  1327. $this->assertEqual($libraries, array(), 'Retrieving libraries from a module not implementing hook_library() returns an emtpy array.');
  1328. // Retrieve a specific library by module and name.
  1329. $farbtastic = drupal_get_library('common_test', 'farbtastic');
  1330. $this->assertEqual($farbtastic['version'], '5.3', 'Retrieved a single library.');
  1331. // Retrieve a non-existing library by module and name.
  1332. $farbtastic = drupal_get_library('common_test', 'foo');
  1333. $this->assertIdentical($farbtastic, FALSE, 'Retrieving a non-existing library returns FALSE.');
  1334. }
  1335. /**
  1336. * Tests that the query string remains intact when adding JavaScript files
  1337. * that have query string parameters.
  1338. */
  1339. function testAddJsFileWithQueryString() {
  1340. $this->drupalGet('common-test/query-string');
  1341. $query_string = variable_get('css_js_query_string', '0');
  1342. $this->assertRaw(drupal_get_path('module', 'node') . '/node.js?' . $query_string, 'Query string was appended correctly to js.');
  1343. }
  1344. }
  1345. /**
  1346. * Tests for drupal_render().
  1347. */
  1348. class DrupalRenderTestCase extends DrupalWebTestCase {
  1349. public static function getInfo() {
  1350. return array(
  1351. 'name' => 'drupal_render()',
  1352. 'description' => 'Performs functional tests on drupal_render().',
  1353. 'group' => 'System',
  1354. );
  1355. }
  1356. function setUp() {
  1357. parent::setUp('common_test');
  1358. }
  1359. /**
  1360. * Tests the output drupal_render() for some elementary input values.
  1361. */
  1362. function testDrupalRenderBasics() {
  1363. $types = array(
  1364. array(
  1365. 'name' => 'null',
  1366. 'value' => NULL,
  1367. 'expected' => '',
  1368. ),
  1369. array(
  1370. 'name' => 'no value',
  1371. 'expected' => '',
  1372. ),
  1373. array(
  1374. 'name' => 'empty string',
  1375. 'value' => '',
  1376. 'expected' => '',
  1377. ),
  1378. array(
  1379. 'name' => 'no access',
  1380. 'value' => array(
  1381. '#markup' => 'foo',
  1382. '#access' => FALSE,
  1383. ),
  1384. 'expected' => '',
  1385. ),
  1386. array(
  1387. 'name' => 'previously printed',
  1388. 'value' => array(
  1389. '#markup' => 'foo',
  1390. '#printed' => TRUE,
  1391. ),
  1392. 'expected' => '',
  1393. ),
  1394. array(
  1395. 'name' => 'printed in prerender',
  1396. 'value' => array(
  1397. '#markup' => 'foo',
  1398. '#pre_render' => array('common_test_drupal_render_printing_pre_render'),
  1399. ),
  1400. 'expected' => '',
  1401. ),
  1402. array(
  1403. 'name' => 'basic renderable array',
  1404. 'value' => array('#markup' => 'foo'),
  1405. 'expected' => 'foo',
  1406. ),
  1407. );
  1408. foreach($types as $type) {
  1409. $this->assertIdentical(drupal_render($type['value']), $type['expected'], '"' . $type['name'] . '" input rendered correctly by drupal_render().');
  1410. }
  1411. }
  1412. /**
  1413. * Test sorting by weight.
  1414. */
  1415. function testDrupalRenderSorting() {
  1416. $first = $this->randomName();
  1417. $second = $this->randomName();
  1418. // Build an array with '#weight' set for each element.
  1419. $elements = array(
  1420. 'second' => array(
  1421. '#weight' => 10,
  1422. '#markup' => $second,
  1423. ),
  1424. 'first' => array(
  1425. '#weight' => 0,
  1426. '#markup' => $first,
  1427. ),
  1428. );
  1429. $output = drupal_render($elements);
  1430. // The lowest weight element should appear last in $output.
  1431. $this->assertTrue(strpos($output, $second) > strpos($output, $first), 'Elements were sorted correctly by weight.');
  1432. // Confirm that the $elements array has '#sorted' set to TRUE.
  1433. $this->assertTrue($elements['#sorted'], "'#sorted' => TRUE was added to the array");
  1434. // Pass $elements through element_children() and ensure it remains
  1435. // sorted in the correct order. drupal_render() will return an empty string
  1436. // if used on the same array in the same request.
  1437. $children = element_children($elements);
  1438. $this->assertTrue(array_shift($children) == 'first', 'Child found in the correct order.');
  1439. $this->assertTrue(array_shift($children) == 'second', 'Child found in the correct order.');
  1440. // The same array structure again, but with #sorted set to TRUE.
  1441. $elements = array(
  1442. 'second' => array(
  1443. '#weight' => 10,
  1444. '#markup' => $second,
  1445. ),
  1446. 'first' => array(
  1447. '#weight' => 0,
  1448. '#markup' => $first,
  1449. ),
  1450. '#sorted' => TRUE,
  1451. );
  1452. $output = drupal_render($elements);
  1453. // The elements should appear in output in the same order as the array.
  1454. $this->assertTrue(strpos($output, $second) < strpos($output, $first), 'Elements were not sorted.');
  1455. }
  1456. /**
  1457. * Test #attached functionality in children elements.
  1458. */
  1459. function testDrupalRenderChildrenAttached() {
  1460. // The cache system is turned off for POST requests.
  1461. $request_method = $_SERVER['REQUEST_METHOD'];
  1462. $_SERVER['REQUEST_METHOD'] = 'GET';
  1463. // Create an element with a child and subchild. Each element loads a
  1464. // different JavaScript file using #attached.
  1465. $parent_js = drupal_get_path('module', 'user') . '/user.js';
  1466. $child_js = drupal_get_path('module', 'forum') . '/forum.js';
  1467. $subchild_js = drupal_get_path('module', 'book') . '/book.js';
  1468. $element = array(
  1469. '#type' => 'fieldset',
  1470. '#cache' => array(
  1471. 'keys' => array('simpletest', 'drupal_render', 'children_attached'),
  1472. ),
  1473. '#attached' => array('js' => array($parent_js)),
  1474. '#title' => 'Parent',
  1475. );
  1476. $element['child'] = array(
  1477. '#type' => 'fieldset',
  1478. '#attached' => array('js' => array($child_js)),
  1479. '#title' => 'Child',
  1480. );
  1481. $element['child']['subchild'] = array(
  1482. '#attached' => array('js' => array($subchild_js)),
  1483. '#markup' => 'Subchild',
  1484. );
  1485. // Render the element and verify the presence of #attached JavaScript.
  1486. drupal_render($element);
  1487. $scripts = drupal_get_js();
  1488. $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included.');
  1489. $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included.');
  1490. $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included.');
  1491. // Load the element from cache and verify the presence of the #attached
  1492. // JavaScript.
  1493. drupal_static_reset('drupal_add_js');
  1494. $this->assertTrue(drupal_render_cache_get($element), 'The element was retrieved from cache.');
  1495. $scripts = drupal_get_js();
  1496. $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included when loading from cache.');
  1497. $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included when loading from cache.');
  1498. $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included when loading from cache.');
  1499. $_SERVER['REQUEST_METHOD'] = $request_method;
  1500. }
  1501. /**
  1502. * Test passing arguments to the theme function.
  1503. */
  1504. function testDrupalRenderThemeArguments() {
  1505. $element = array(
  1506. '#theme' => 'common_test_foo',
  1507. );
  1508. // Test that defaults work.
  1509. $this->assertEqual(drupal_render($element), 'foobar', 'Defaults work');
  1510. $element = array(
  1511. '#theme' => 'common_test_foo',
  1512. '#foo' => $this->randomName(),
  1513. '#bar' => $this->randomName(),
  1514. );
  1515. // Test that passing arguments to the theme function works.
  1516. $this->assertEqual(drupal_render($element), $element['#foo'] . $element['#bar'], 'Passing arguments to theme functions works');
  1517. }
  1518. /**
  1519. * Test rendering form elements without passing through form_builder().
  1520. */
  1521. function testDrupalRenderFormElements() {
  1522. // Define a series of form elements.
  1523. $element = array(
  1524. '#type' => 'button',
  1525. '#value' => $this->randomName(),
  1526. );
  1527. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'submit'));
  1528. $element = array(
  1529. '#type' => 'textfield',
  1530. '#title' => $this->randomName(),
  1531. '#value' => $this->randomName(),
  1532. );
  1533. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'text'));
  1534. $element = array(
  1535. '#type' => 'password',
  1536. '#title' => $this->randomName(),
  1537. );
  1538. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'password'));
  1539. $element = array(
  1540. '#type' => 'textarea',
  1541. '#title' => $this->randomName(),
  1542. '#value' => $this->randomName(),
  1543. );
  1544. $this->assertRenderedElement($element, '//textarea');
  1545. $element = array(
  1546. '#type' => 'radio',
  1547. '#title' => $this->randomName(),
  1548. '#value' => FALSE,
  1549. );
  1550. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'radio'));
  1551. $element = array(
  1552. '#type' => 'checkbox',
  1553. '#title' => $this->randomName(),
  1554. );
  1555. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'checkbox'));
  1556. $element = array(
  1557. '#type' => 'select',
  1558. '#title' => $this->randomName(),
  1559. '#options' => array(
  1560. 0 => $this->randomName(),
  1561. 1 => $this->randomName(),
  1562. ),
  1563. );
  1564. $this->assertRenderedElement($element, '//select');
  1565. $element = array(
  1566. '#type' => 'file',
  1567. '#title' => $this->randomName(),
  1568. );
  1569. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'file'));
  1570. $element = array(
  1571. '#type' => 'item',
  1572. '#title' => $this->randomName(),
  1573. '#markup' => $this->randomName(),
  1574. );
  1575. $this->assertRenderedElement($element, '//div[contains(@class, :class) and contains(., :markup)]/label[contains(., :label)]', array(
  1576. ':class' => 'form-type-item',
  1577. ':markup' => $element['#markup'],
  1578. ':label' => $element['#title'],
  1579. ));
  1580. $element = array(
  1581. '#type' => 'hidden',
  1582. '#title' => $this->randomName(),
  1583. '#value' => $this->randomName(),
  1584. );
  1585. $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'hidden'));
  1586. $element = array(
  1587. '#type' => 'link',
  1588. '#title' => $this->randomName(),
  1589. '#href' => $this->randomName(),
  1590. '#options' => array(
  1591. 'absolute' => TRUE,
  1592. ),
  1593. );
  1594. $this->assertRenderedElement($element, '//a[@href=:href and contains(., :title)]', array(
  1595. ':href' => url($element['#href'], array('absolute' => TRUE)),
  1596. ':title' => $element['#title'],
  1597. ));
  1598. $element = array(
  1599. '#type' => 'fieldset',
  1600. '#title' => $this->randomName(),
  1601. );
  1602. $this->assertRenderedElement($element, '//fieldset/legend[contains(., :title)]', array(
  1603. ':title' => $element['#title'],
  1604. ));
  1605. $element['item'] = array(
  1606. '#type' => 'item',
  1607. '#title' => $this->randomName(),
  1608. '#markup' => $this->randomName(),
  1609. );
  1610. $this->assertRenderedElement($element, '//fieldset/div/div[contains(@class, :class) and contains(., :markup)]', array(
  1611. ':class' => 'form-type-item',
  1612. ':markup' => $element['item']['#markup'],
  1613. ));
  1614. }
  1615. protected function assertRenderedElement(array $element, $xpath, array $xpath_args = array()) {
  1616. $original_element = $element;
  1617. $this->drupalSetContent(drupal_render($element));
  1618. $this->verbose('<pre>' . check_plain(var_export($original_element, TRUE)) . '</pre>'
  1619. . '<pre>' . check_plain(var_export($element, TRUE)) . '</pre>'
  1620. . '<hr />' . $this->drupalGetContent()
  1621. );
  1622. // @see DrupalWebTestCase::xpath()
  1623. $xpath = $this->buildXPathQuery($xpath, $xpath_args);
  1624. $element += array('#value' => NULL);
  1625. $this->assertFieldByXPath($xpath, $element['#value'], format_string('#type @type was properly rendered.', array(
  1626. '@type' => var_export($element['#type'], TRUE),
  1627. )));
  1628. }
  1629. /**
  1630. * Tests caching of an empty render item.
  1631. */
  1632. function testDrupalRenderCache() {
  1633. // Force a request via GET.
  1634. $request_method = $_SERVER['REQUEST_METHOD'];
  1635. $_SERVER['REQUEST_METHOD'] = 'GET';
  1636. // Create an empty element.
  1637. $test_element = array(
  1638. '#cache' => array(
  1639. 'cid' => 'render_cache_test',
  1640. ),
  1641. '#markup' => '',
  1642. );
  1643. // Render the element and confirm that it goes through the rendering
  1644. // process (which will set $element['#printed']).
  1645. $element = $test_element;
  1646. drupal_render($element);
  1647. $this->assertTrue(isset($element['#printed']), 'No cache hit');
  1648. // Render the element again and confirm that it is retrieved from the cache
  1649. // instead (so $element['#printed'] will not be set).
  1650. $element = $test_element;
  1651. drupal_render($element);
  1652. $this->assertFalse(isset($element['#printed']), 'Cache hit');
  1653. // Restore the previous request method.
  1654. $_SERVER['REQUEST_METHOD'] = $request_method;
  1655. }
  1656. }
  1657. /**
  1658. * Test for valid_url().
  1659. */
  1660. class ValidUrlTestCase extends DrupalUnitTestCase {
  1661. public static function getInfo() {
  1662. return array(
  1663. 'name' => 'Valid URL',
  1664. 'description' => "Performs tests on Drupal's valid URL function.",
  1665. 'group' => 'System'
  1666. );
  1667. }
  1668. /**
  1669. * Test valid absolute URLs.
  1670. */
  1671. function testValidAbsolute() {
  1672. $url_schemes = array('http', 'https', 'ftp');
  1673. $valid_absolute_urls = array(
  1674. 'example.com',
  1675. 'www.example.com',
  1676. 'ex-ample.com',
  1677. '3xampl3.com',
  1678. 'example.com/paren(the)sis',
  1679. 'example.com/index.html#pagetop',
  1680. 'example.com:8080',
  1681. 'subdomain.example.com',
  1682. 'example.com/index.php?q=node',
  1683. 'example.com/index.php?q=node&param=false',
  1684. 'user@www.example.com',
  1685. 'user:pass@www.example.com:8080/login.php?do=login&style=%23#pagetop',
  1686. '127.0.0.1',
  1687. 'example.org?',
  1688. 'john%20doe:secret:foo@example.org/',
  1689. 'example.org/~,$\'*;',
  1690. 'caf%C3%A9.example.org',
  1691. '[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
  1692. );
  1693. foreach ($url_schemes as $scheme) {
  1694. foreach ($valid_absolute_urls as $url) {
  1695. $test_url = $scheme . '://' . $url;
  1696. $valid_url = valid_url($test_url, TRUE);
  1697. $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
  1698. }
  1699. }
  1700. }
  1701. /**
  1702. * Test invalid absolute URLs.
  1703. */
  1704. function testInvalidAbsolute() {
  1705. $url_schemes = array('http', 'https', 'ftp');
  1706. $invalid_ablosule_urls = array(
  1707. '',
  1708. 'ex!ample.com',
  1709. 'ex%ample.com',
  1710. );
  1711. foreach ($url_schemes as $scheme) {
  1712. foreach ($invalid_ablosule_urls as $url) {
  1713. $test_url = $scheme . '://' . $url;
  1714. $valid_url = valid_url($test_url, TRUE);
  1715. $this->assertFalse($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
  1716. }
  1717. }
  1718. }
  1719. /**
  1720. * Test valid relative URLs.
  1721. */
  1722. function testValidRelative() {
  1723. $valid_relative_urls = array(
  1724. 'paren(the)sis',
  1725. 'index.html#pagetop',
  1726. 'index.php?q=node',
  1727. 'index.php?q=node&param=false',
  1728. 'login.php?do=login&style=%23#pagetop',
  1729. );
  1730. foreach (array('', '/') as $front) {
  1731. foreach ($valid_relative_urls as $url) {
  1732. $test_url = $front . $url;
  1733. $valid_url = valid_url($test_url);
  1734. $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
  1735. }
  1736. }
  1737. }
  1738. /**
  1739. * Test invalid relative URLs.
  1740. */
  1741. function testInvalidRelative() {
  1742. $invalid_relative_urls = array(
  1743. 'ex^mple',
  1744. 'example<>',
  1745. 'ex%ample',
  1746. );
  1747. foreach (array('', '/') as $front) {
  1748. foreach ($invalid_relative_urls as $url) {
  1749. $test_url = $front . $url;
  1750. $valid_url = valid_url($test_url);
  1751. $this->assertFALSE($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
  1752. }
  1753. }
  1754. }
  1755. }
  1756. /**
  1757. * Tests for CRUD API functions.
  1758. */
  1759. class DrupalDataApiTest extends DrupalWebTestCase {
  1760. public static function getInfo() {
  1761. return array(
  1762. 'name' => 'Data API functions',
  1763. 'description' => 'Tests the performance of CRUD APIs.',
  1764. 'group' => 'System',
  1765. );
  1766. }
  1767. function setUp() {
  1768. parent::setUp('database_test');
  1769. }
  1770. /**
  1771. * Test the drupal_write_record() API function.
  1772. */
  1773. function testDrupalWriteRecord() {
  1774. // Insert a record - no columns allow NULL values.
  1775. $person = new stdClass();
  1776. $person->name = 'John';
  1777. $person->unknown_column = 123;
  1778. $insert_result = drupal_write_record('test', $person);
  1779. $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.');
  1780. $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
  1781. $this->assertIdentical($person->age, 0, 'Age field set to default value.');
  1782. $this->assertIdentical($person->job, 'Undefined', 'Job field set to default value.');
  1783. // Verify that the record was inserted.
  1784. $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  1785. $this->assertIdentical($result->name, 'John', 'Name field set.');
  1786. $this->assertIdentical($result->age, '0', 'Age field set to default value.');
  1787. $this->assertIdentical($result->job, 'Undefined', 'Job field set to default value.');
  1788. $this->assertFalse(isset($result->unknown_column), 'Unknown column was ignored.');
  1789. // Update the newly created record.
  1790. $person->name = 'Peter';
  1791. $person->age = 27;
  1792. $person->job = NULL;
  1793. $update_result = drupal_write_record('test', $person, array('id'));
  1794. $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a record updated with drupal_write_record() for table with single-field primary key.');
  1795. // Verify that the record was updated.
  1796. $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  1797. $this->assertIdentical($result->name, 'Peter', 'Name field set.');
  1798. $this->assertIdentical($result->age, '27', 'Age field set.');
  1799. $this->assertIdentical($result->job, '', 'Job field set and cast to string.');
  1800. // Try to insert NULL in columns that does not allow this.
  1801. $person = new stdClass();
  1802. $person->name = 'Ringo';
  1803. $person->age = NULL;
  1804. $person->job = NULL;
  1805. $insert_result = drupal_write_record('test', $person);
  1806. $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
  1807. $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  1808. $this->assertIdentical($result->name, 'Ringo', 'Name field set.');
  1809. $this->assertIdentical($result->age, '0', 'Age field set.');
  1810. $this->assertIdentical($result->job, '', 'Job field set.');
  1811. // Insert a record - the "age" column allows NULL.
  1812. $person = new stdClass();
  1813. $person->name = 'Paul';
  1814. $person->age = NULL;
  1815. $insert_result = drupal_write_record('test_null', $person);
  1816. $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
  1817. $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  1818. $this->assertIdentical($result->name, 'Paul', 'Name field set.');
  1819. $this->assertIdentical($result->age, NULL, 'Age field set.');
  1820. // Insert a record - do not specify the value of a column that allows NULL.
  1821. $person = new stdClass();
  1822. $person->name = 'Meredith';
  1823. $insert_result = drupal_write_record('test_null', $person);
  1824. $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
  1825. $this->assertIdentical($person->age, 0, 'Age field set to default value.');
  1826. $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  1827. $this->assertIdentical($result->name, 'Meredith', 'Name field set.');
  1828. $this->assertIdentical($result->age, '0', 'Age field set to default value.');
  1829. // Update the newly created record.
  1830. $person->name = 'Mary';
  1831. $person->age = NULL;
  1832. $update_result = drupal_write_record('test_null', $person, array('id'));
  1833. $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  1834. $this->assertIdentical($result->name, 'Mary', 'Name field set.');
  1835. $this->assertIdentical($result->age, NULL, 'Age field set.');
  1836. // Insert a record - the "data" column should be serialized.
  1837. $person = new stdClass();
  1838. $person->name = 'Dave';
  1839. $update_result = drupal_write_record('test_serialized', $person);
  1840. $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  1841. $this->assertIdentical($result->name, 'Dave', 'Name field set.');
  1842. $this->assertIdentical($result->info, NULL, 'Info field set.');
  1843. $person->info = array();
  1844. $update_result = drupal_write_record('test_serialized', $person, array('id'));
  1845. $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  1846. $this->assertIdentical(unserialize($result->info), array(), 'Info field updated.');
  1847. // Update the serialized record.
  1848. $data = array('foo' => 'bar', 1 => 2, 'empty' => '', 'null' => NULL);
  1849. $person->info = $data;
  1850. $update_result = drupal_write_record('test_serialized', $person, array('id'));
  1851. $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
  1852. $this->assertIdentical(unserialize($result->info), $data, 'Info field updated.');
  1853. // Run an update query where no field values are changed. The database
  1854. // layer should return zero for number of affected rows, but
  1855. // db_write_record() should still return SAVED_UPDATED.
  1856. $update_result = drupal_write_record('test_null', $person, array('id'));
  1857. $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a valid update is run without changing any values.');
  1858. // Insert an object record for a table with a multi-field primary key.
  1859. $node_access = new stdClass();
  1860. $node_access->nid = mt_rand();
  1861. $node_access->gid = mt_rand();
  1862. $node_access->realm = $this->randomName();
  1863. $insert_result = drupal_write_record('node_access', $node_access);
  1864. $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.');
  1865. // Update the record.
  1866. $update_result = drupal_write_record('node_access', $node_access, array('nid', 'gid', 'realm'));
  1867. $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.');
  1868. }
  1869. }
  1870. /**
  1871. * Tests Simpletest error and exception collector.
  1872. */
  1873. class DrupalErrorCollectionUnitTest extends DrupalWebTestCase {
  1874. /**
  1875. * Errors triggered during the test.
  1876. *
  1877. * Errors are intercepted by the overriden implementation
  1878. * of DrupalWebTestCase::error below.
  1879. *
  1880. * @var Array
  1881. */
  1882. protected $collectedErrors = array();
  1883. public static function getInfo() {
  1884. return array(
  1885. 'name' => 'SimpleTest error collector',
  1886. 'description' => 'Performs tests on the Simpletest error and exception collector.',
  1887. 'group' => 'SimpleTest',
  1888. );
  1889. }
  1890. function setUp() {
  1891. parent::setUp('system_test', 'error_test');
  1892. }
  1893. /**
  1894. * Test that simpletest collects errors from the tested site.
  1895. */
  1896. function testErrorCollect() {
  1897. $this->collectedErrors = array();
  1898. $this->drupalGet('error-test/generate-warnings-with-report');
  1899. $this->assertEqual(count($this->collectedErrors), 3, 'Three errors were collected');
  1900. if (count($this->collectedErrors) == 3) {
  1901. $this->assertError($this->collectedErrors[0], 'Notice', 'error_test_generate_warnings()', 'error_test.module', 'Undefined variable: bananas');
  1902. $this->assertError($this->collectedErrors[1], 'Warning', 'error_test_generate_warnings()', 'error_test.module', 'Division by zero');
  1903. $this->assertError($this->collectedErrors[2], 'User warning', 'error_test_generate_warnings()', 'error_test.module', 'Drupal is awesome');
  1904. }
  1905. else {
  1906. // Give back the errors to the log report.
  1907. foreach ($this->collectedErrors as $error) {
  1908. parent::error($error['message'], $error['group'], $error['caller']);
  1909. }
  1910. }
  1911. }
  1912. /**
  1913. * Error handler that collects errors in an array.
  1914. *
  1915. * This test class is trying to verify that simpletest correctly sees errors
  1916. * and warnings. However, it can't generate errors and warnings that
  1917. * propagate up to the testing framework itself, or these tests would always
  1918. * fail. So, this special copy of error() doesn't propagate the errors up
  1919. * the class hierarchy. It just stuffs them into a protected collectedErrors
  1920. * array for various assertions to inspect.
  1921. */
  1922. protected function error($message = '', $group = 'Other', array $caller = NULL) {
  1923. // Due to a WTF elsewhere, simpletest treats debug() and verbose()
  1924. // messages as if they were an 'error'. But, we don't want to collect
  1925. // those here. This function just wants to collect the real errors (PHP
  1926. // notices, PHP fatal errors, etc.), and let all the 'errors' from the
  1927. // 'User notice' group bubble up to the parent classes to be handled (and
  1928. // eventually displayed) as normal.
  1929. if ($group == 'User notice') {
  1930. parent::error($message, $group, $caller);
  1931. }
  1932. // Everything else should be collected but not propagated.
  1933. else {
  1934. $this->collectedErrors[] = array(
  1935. 'message' => $message,
  1936. 'group' => $group,
  1937. 'caller' => $caller
  1938. );
  1939. }
  1940. }
  1941. /**
  1942. * Assert that a collected error matches what we are expecting.
  1943. */
  1944. function assertError($error, $group, $function, $file, $message = NULL) {
  1945. $this->assertEqual($error['group'], $group, format_string("Group was %group", array('%group' => $group)));
  1946. $this->assertEqual($error['caller']['function'], $function, format_string("Function was %function", array('%function' => $function)));
  1947. $this->assertEqual(drupal_basename($error['caller']['file']), $file, format_string("File was %file", array('%file' => $file)));
  1948. if (isset($message)) {
  1949. $this->assertEqual($error['message'], $message, format_string("Message was %message", array('%message' => $message)));
  1950. }
  1951. }
  1952. }
  1953. /**
  1954. * Test the drupal_parse_info_file() API function.
  1955. */
  1956. class ParseInfoFilesTestCase extends DrupalUnitTestCase {
  1957. public static function getInfo() {
  1958. return array(
  1959. 'name' => 'Parsing .info files',
  1960. 'description' => 'Tests parsing .info files.',
  1961. 'group' => 'System',
  1962. );
  1963. }
  1964. /**
  1965. * Parse an example .info file an verify the results.
  1966. */
  1967. function testParseInfoFile() {
  1968. $info_values = drupal_parse_info_file(drupal_get_path('module', 'simpletest') . '/tests/common_test_info.txt');
  1969. $this->assertEqual($info_values['simple_string'], 'A simple string', 'Simple string value was parsed correctly.', 'System');
  1970. $this->assertEqual($info_values['simple_constant'], WATCHDOG_INFO, 'Constant value was parsed correctly.', 'System');
  1971. $this->assertEqual($info_values['double_colon'], 'dummyClassName::', 'Value containing double-colon was parsed correctly.', 'System');
  1972. }
  1973. }
  1974. /**
  1975. * Tests for the drupal_system_listing() function.
  1976. */
  1977. class DrupalSystemListingTestCase extends DrupalWebTestCase {
  1978. /**
  1979. * Use the testing profile; this is needed for testDirectoryPrecedence().
  1980. */
  1981. protected $profile = 'testing';
  1982. public static function getInfo() {
  1983. return array(
  1984. 'name' => 'Drupal system listing',
  1985. 'description' => 'Tests the mechanism for scanning system directories in drupal_system_listing().',
  1986. 'group' => 'System',
  1987. );
  1988. }
  1989. /**
  1990. * Test that files in different directories take precedence as expected.
  1991. */
  1992. function testDirectoryPrecedence() {
  1993. // Define the module files we will search for, and the directory precedence
  1994. // we expect.
  1995. $expected_directories = array(
  1996. // When the copy of the module in the profile directory is incompatible
  1997. // with Drupal core, the copy in the core modules directory takes
  1998. // precedence.
  1999. 'drupal_system_listing_incompatible_test' => array(
  2000. 'modules/simpletest/tests',
  2001. 'profiles/testing/modules',
  2002. ),
  2003. // When both copies of the module are compatible with Drupal core, the
  2004. // copy in the profile directory takes precedence.
  2005. 'drupal_system_listing_compatible_test' => array(
  2006. 'profiles/testing/modules',
  2007. 'modules/simpletest/tests',
  2008. ),
  2009. );
  2010. // This test relies on two versions of the same module existing in
  2011. // different places in the filesystem. Without that, the test has no
  2012. // meaning, so assert their presence first.
  2013. foreach ($expected_directories as $module => $directories) {
  2014. foreach ($directories as $directory) {
  2015. $filename = "$directory/$module/$module.module";
  2016. $this->assertTrue(file_exists(DRUPAL_ROOT . '/' . $filename), format_string('@filename exists.', array('@filename' => $filename)));
  2017. }
  2018. }
  2019. // Now scan the directories and check that the files take precedence as
  2020. // expected.
  2021. $files = drupal_system_listing('/\.module$/', 'modules', 'name', 1);
  2022. foreach ($expected_directories as $module => $directories) {
  2023. $expected_directory = array_shift($directories);
  2024. $expected_filename = "$expected_directory/$module/$module.module";
  2025. $this->assertEqual($files[$module]->uri, $expected_filename, format_string('Module @module was found at @filename.', array('@module' => $module, '@filename' => $expected_filename)));
  2026. }
  2027. }
  2028. }
  2029. /**
  2030. * Tests for the format_date() function.
  2031. */
  2032. class FormatDateUnitTest extends DrupalWebTestCase {
  2033. /**
  2034. * Arbitrary langcode for a custom language.
  2035. */
  2036. const LANGCODE = 'xx';
  2037. public static function getInfo() {
  2038. return array(
  2039. 'name' => 'Format date',
  2040. 'description' => 'Test the format_date() function.',
  2041. 'group' => 'System',
  2042. );
  2043. }
  2044. function setUp() {
  2045. parent::setUp('locale');
  2046. variable_set('configurable_timezones', 1);
  2047. variable_set('date_format_long', 'l, j. F Y - G:i');
  2048. variable_set('date_format_medium', 'j. F Y - G:i');
  2049. variable_set('date_format_short', 'Y M j - g:ia');
  2050. variable_set('locale_custom_strings_' . self::LANGCODE, array(
  2051. '' => array('Sunday' => 'domingo'),
  2052. 'Long month name' => array('March' => 'marzo'),
  2053. ));
  2054. $this->refreshVariables();
  2055. }
  2056. /**
  2057. * Test admin-defined formats in format_date().
  2058. */
  2059. function testAdminDefinedFormatDate() {
  2060. // Create an admin user.
  2061. $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
  2062. $this->drupalLogin($this->admin_user);
  2063. // Add new date format.
  2064. $admin_date_format = 'j M y';
  2065. $edit = array('date_format' => $admin_date_format);
  2066. $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, 'Add format');
  2067. // Add a new date format which just differs in the case.
  2068. $admin_date_format_uppercase = 'j M Y';
  2069. $edit = array('date_format' => $admin_date_format_uppercase);
  2070. $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
  2071. $this->assertText(t('Custom date format added.'));
  2072. // Add new date type.
  2073. $edit = array(
  2074. 'date_type' => 'Example Style',
  2075. 'machine_name' => 'example_style',
  2076. 'date_format' => $admin_date_format,
  2077. );
  2078. $this->drupalPost('admin/config/regional/date-time/types/add', $edit, 'Add date type');
  2079. // Add a second date format with a different case than the first.
  2080. $edit = array(
  2081. 'machine_name' => 'example_style_uppercase',
  2082. 'date_type' => 'Example Style Uppercase',
  2083. 'date_format' => $admin_date_format_uppercase,
  2084. );
  2085. $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
  2086. $this->assertText(t('New date type added successfully.'));
  2087. $timestamp = strtotime('2007-03-10T00:00:00+00:00');
  2088. $this->assertIdentical(format_date($timestamp, 'example_style', '', 'America/Los_Angeles'), '9 Mar 07', 'Test format_date() using an admin-defined date type.');
  2089. $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.');
  2090. $this->assertIdentical(format_date($timestamp, 'undefined_style'), format_date($timestamp, 'medium'), 'Test format_date() defaulting to medium when $type not found.');
  2091. }
  2092. /**
  2093. * Tests for the format_date() function.
  2094. */
  2095. function testFormatDate() {
  2096. global $user, $language;
  2097. $timestamp = strtotime('2007-03-26T00:00:00+00:00');
  2098. $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.');
  2099. $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.');
  2100. $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.');
  2101. $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.');
  2102. $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.');
  2103. $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.');
  2104. // Create an admin user and add Spanish language.
  2105. $admin_user = $this->drupalCreateUser(array('administer languages'));
  2106. $this->drupalLogin($admin_user);
  2107. $edit = array(
  2108. 'langcode' => self::LANGCODE,
  2109. 'name' => self::LANGCODE,
  2110. 'native' => self::LANGCODE,
  2111. 'direction' => LANGUAGE_LTR,
  2112. 'prefix' => self::LANGCODE,
  2113. );
  2114. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  2115. // Create a test user to carry out the tests.
  2116. $test_user = $this->drupalCreateUser();
  2117. $this->drupalLogin($test_user);
  2118. $edit = array('language' => self::LANGCODE, 'mail' => $test_user->mail, 'timezone' => 'America/Los_Angeles');
  2119. $this->drupalPost('user/' . $test_user->uid . '/edit', $edit, t('Save'));
  2120. // Disable session saving as we are about to modify the global $user.
  2121. drupal_save_session(FALSE);
  2122. // Save the original user and language and then replace it with the test user and language.
  2123. $real_user = $user;
  2124. $user = user_load($test_user->uid, TRUE);
  2125. $real_language = $language->language;
  2126. $language->language = $user->language;
  2127. // Simulate a Drupal bootstrap with the logged-in user.
  2128. date_default_timezone_set(drupal_get_user_timezone());
  2129. $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.');
  2130. $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.');
  2131. $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.');
  2132. $this->assertIdentical(format_date($timestamp, 'long'), 'domingo, 25. marzo 2007 - 17:00', 'Test long date format.');
  2133. $this->assertIdentical(format_date($timestamp, 'medium'), '25. marzo 2007 - 17:00', 'Test medium date format.');
  2134. $this->assertIdentical(format_date($timestamp, 'short'), '2007 Mar 25 - 5:00pm', 'Test short date format.');
  2135. $this->assertIdentical(format_date($timestamp), '25. marzo 2007 - 17:00', 'Test default date format.');
  2136. // Restore the original user and language, and enable session saving.
  2137. $user = $real_user;
  2138. $language->language = $real_language;
  2139. // Restore default time zone.
  2140. date_default_timezone_set(drupal_get_user_timezone());
  2141. drupal_save_session(TRUE);
  2142. }
  2143. }
  2144. /**
  2145. * Tests for the format_date() function.
  2146. */
  2147. class DrupalAttributesUnitTest extends DrupalUnitTestCase {
  2148. public static function getInfo() {
  2149. return array(
  2150. 'name' => 'HTML Attributes',
  2151. 'description' => 'Perform unit tests on the drupal_attributes() function.',
  2152. 'group' => 'System',
  2153. );
  2154. }
  2155. /**
  2156. * Tests that drupal_html_class() cleans the class name properly.
  2157. */
  2158. function testDrupalAttributes() {
  2159. // Verify that special characters are HTML encoded.
  2160. $this->assertIdentical(drupal_attributes(array('title' => '&"\'<>')), ' title="&amp;&quot;&#039;&lt;&gt;"', 'HTML encode attribute values.');
  2161. // Verify multi-value attributes are concatenated with spaces.
  2162. $attributes = array('class' => array('first', 'last'));
  2163. $this->assertIdentical(drupal_attributes(array('class' => array('first', 'last'))), ' class="first last"', 'Concatenate multi-value attributes.');
  2164. // Verify empty attribute values are rendered.
  2165. $this->assertIdentical(drupal_attributes(array('alt' => '')), ' alt=""', 'Empty attribute value #1.');
  2166. $this->assertIdentical(drupal_attributes(array('alt' => NULL)), ' alt=""', 'Empty attribute value #2.');
  2167. // Verify multiple attributes are rendered.
  2168. $attributes = array(
  2169. 'id' => 'id-test',
  2170. 'class' => array('first', 'last'),
  2171. 'alt' => 'Alternate',
  2172. );
  2173. $this->assertIdentical(drupal_attributes($attributes), ' id="id-test" class="first last" alt="Alternate"', 'Multiple attributes.');
  2174. // Verify empty attributes array is rendered.
  2175. $this->assertIdentical(drupal_attributes(array()), '', 'Empty attributes array.');
  2176. }
  2177. }
  2178. /**
  2179. * Tests converting PHP variables to JSON strings and back.
  2180. */
  2181. class DrupalJSONTest extends DrupalUnitTestCase {
  2182. public static function getInfo() {
  2183. return array(
  2184. 'name' => 'JSON',
  2185. 'description' => 'Perform unit tests on the drupal_json_encode() and drupal_json_decode() functions.',
  2186. 'group' => 'System',
  2187. );
  2188. }
  2189. /**
  2190. * Tests converting PHP variables to JSON strings and back.
  2191. */
  2192. function testJSON() {
  2193. // Setup a string with the full ASCII table.
  2194. // @todo: Add tests for non-ASCII characters and Unicode.
  2195. $str = '';
  2196. for ($i=0; $i < 128; $i++) {
  2197. $str .= chr($i);
  2198. }
  2199. // Characters that must be escaped.
  2200. // We check for unescaped " separately.
  2201. $html_unsafe = array('<', '>', '\'', '&');
  2202. // The following are the encoded forms of: < > ' & "
  2203. $html_unsafe_escaped = array('\u003C', '\u003E', '\u0027', '\u0026', '\u0022');
  2204. // Verify there aren't character encoding problems with the source string.
  2205. $this->assertIdentical(strlen($str), 128, 'A string with the full ASCII table has the correct length.');
  2206. foreach ($html_unsafe as $char) {
  2207. $this->assertTrue(strpos($str, $char) > 0, format_string('A string with the full ASCII table includes @s.', array('@s' => $char)));
  2208. }
  2209. // Verify that JSON encoding produces a string with all of the characters.
  2210. $json = drupal_json_encode($str);
  2211. $this->assertTrue(strlen($json) > strlen($str), 'A JSON encoded string is larger than the source string.');
  2212. // The first and last characters should be ", and no others.
  2213. $this->assertTrue($json[0] == '"', 'A JSON encoded string begins with ".');
  2214. $this->assertTrue($json[strlen($json) - 1] == '"', 'A JSON encoded string ends with ".');
  2215. $this->assertTrue(substr_count($json, '"') == 2, 'A JSON encoded string contains exactly two ".');
  2216. // Verify that encoding/decoding is reversible.
  2217. $json_decoded = drupal_json_decode($json);
  2218. $this->assertIdentical($str, $json_decoded, 'Encoding a string to JSON and decoding back results in the original string.');
  2219. // Verify reversibility for structured data. Also verify that necessary
  2220. // characters are escaped.
  2221. $source = array(TRUE, FALSE, 0, 1, '0', '1', $str, array('key1' => $str, 'key2' => array('nested' => TRUE)));
  2222. $json = drupal_json_encode($source);
  2223. foreach ($html_unsafe as $char) {
  2224. $this->assertTrue(strpos($json, $char) === FALSE, format_string('A JSON encoded string does not contain @s.', array('@s' => $char)));
  2225. }
  2226. // Verify that JSON encoding escapes the HTML unsafe characters
  2227. foreach ($html_unsafe_escaped as $char) {
  2228. $this->assertTrue(strpos($json, $char) > 0, format_string('A JSON encoded string contains @s.', array('@s' => $char)));
  2229. }
  2230. $json_decoded = drupal_json_decode($json);
  2231. $this->assertNotIdentical($source, $json, 'An array encoded in JSON is not identical to the source.');
  2232. $this->assertIdentical($source, $json_decoded, 'Encoding structured data to JSON and decoding back results in the original data.');
  2233. }
  2234. }
  2235. /**
  2236. * Tests for RDF namespaces XML serialization.
  2237. */
  2238. class DrupalGetRdfNamespacesTestCase extends DrupalWebTestCase {
  2239. public static function getInfo() {
  2240. return array(
  2241. 'name' => 'RDF namespaces XML serialization tests',
  2242. 'description' => 'Confirm that the serialization of RDF namespaces via drupal_get_rdf_namespaces() is output and parsed correctly in the XHTML document.',
  2243. 'group' => 'System',
  2244. );
  2245. }
  2246. function setUp() {
  2247. parent::setUp('rdf', 'rdf_test');
  2248. }
  2249. /**
  2250. * Test RDF namespaces.
  2251. */
  2252. function testGetRdfNamespaces() {
  2253. // Fetches the front page and extracts XML namespaces.
  2254. $this->drupalGet('');
  2255. $xml = new SimpleXMLElement($this->content);
  2256. $ns = $xml->getDocNamespaces();
  2257. $this->assertEqual($ns['rdfs'], 'http://www.w3.org/2000/01/rdf-schema#', 'A prefix declared once is displayed.');
  2258. $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.');
  2259. $this->assertEqual($ns['foaf1'], 'http://xmlns.com/foaf/0.1/', 'Two prefixes can be assigned the same namespace.');
  2260. $this->assertTrue(!isset($ns['dc']), 'A prefix with conflicting namespaces is discarded.');
  2261. }
  2262. }
  2263. /**
  2264. * Basic tests for drupal_add_feed().
  2265. */
  2266. class DrupalAddFeedTestCase extends DrupalWebTestCase {
  2267. public static function getInfo() {
  2268. return array(
  2269. 'name' => 'drupal_add_feed() tests',
  2270. 'description' => 'Make sure that drupal_add_feed() works correctly with various constructs.',
  2271. 'group' => 'System',
  2272. );
  2273. }
  2274. /**
  2275. * Test drupal_add_feed() with paths, URLs, and titles.
  2276. */
  2277. function testBasicFeedAddNoTitle() {
  2278. $path = $this->randomName(12);
  2279. $external_url = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
  2280. $fully_qualified_local_url = url($this->randomName(12), array('absolute' => TRUE));
  2281. $path_for_title = $this->randomName(12);
  2282. $external_for_title = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
  2283. $fully_qualified_for_title = url($this->randomName(12), array('absolute' => TRUE));
  2284. // Possible permutations of drupal_add_feed() to test.
  2285. // - 'input_url': the path passed to drupal_add_feed(),
  2286. // - 'output_url': the expected URL to be found in the header.
  2287. // - 'title' == the title of the feed as passed into drupal_add_feed().
  2288. $urls = array(
  2289. 'path without title' => array(
  2290. 'input_url' => $path,
  2291. 'output_url' => url($path, array('absolute' => TRUE)),
  2292. 'title' => '',
  2293. ),
  2294. 'external URL without title' => array(
  2295. 'input_url' => $external_url,
  2296. 'output_url' => $external_url,
  2297. 'title' => '',
  2298. ),
  2299. 'local URL without title' => array(
  2300. 'input_url' => $fully_qualified_local_url,
  2301. 'output_url' => $fully_qualified_local_url,
  2302. 'title' => '',
  2303. ),
  2304. 'path with title' => array(
  2305. 'input_url' => $path_for_title,
  2306. 'output_url' => url($path_for_title, array('absolute' => TRUE)),
  2307. 'title' => $this->randomName(12),
  2308. ),
  2309. 'external URL with title' => array(
  2310. 'input_url' => $external_for_title,
  2311. 'output_url' => $external_for_title,
  2312. 'title' => $this->randomName(12),
  2313. ),
  2314. 'local URL with title' => array(
  2315. 'input_url' => $fully_qualified_for_title,
  2316. 'output_url' => $fully_qualified_for_title,
  2317. 'title' => $this->randomName(12),
  2318. ),
  2319. );
  2320. foreach ($urls as $description => $feed_info) {
  2321. drupal_add_feed($feed_info['input_url'], $feed_info['title']);
  2322. }
  2323. $this->drupalSetContent(drupal_get_html_head());
  2324. foreach ($urls as $description => $feed_info) {
  2325. $this->assertPattern($this->urlToRSSLinkPattern($feed_info['output_url'], $feed_info['title']), format_string('Found correct feed header for %description', array('%description' => $description)));
  2326. }
  2327. }
  2328. /**
  2329. * Create a pattern representing the RSS feed in the page.
  2330. */
  2331. function urlToRSSLinkPattern($url, $title = '') {
  2332. // Escape any regular expression characters in the URL ('?' is the worst).
  2333. $url = preg_replace('/([+?.*])/', '[$0]', $url);
  2334. $generated_pattern = '%<link +rel="alternate" +type="application/rss.xml" +title="' . $title . '" +href="' . $url . '" */>%';
  2335. return $generated_pattern;
  2336. }
  2337. }
  2338. /**
  2339. * Test for theme_feed_icon().
  2340. */
  2341. class FeedIconTest extends DrupalWebTestCase {
  2342. public static function getInfo() {
  2343. return array(
  2344. 'name' => 'Feed icon',
  2345. 'description' => 'Check escaping of theme_feed_icon()',
  2346. 'group' => 'System',
  2347. );
  2348. }
  2349. /**
  2350. * Check that special characters are correctly escaped. Test for issue #1211668.
  2351. */
  2352. function testFeedIconEscaping() {
  2353. $variables = array();
  2354. $variables['url'] = 'node';
  2355. $variables['title'] = '<>&"\'';
  2356. $text = theme_feed_icon($variables);
  2357. preg_match('/title="(.*?)"/', $text, $matches);
  2358. $this->assertEqual($matches[1], 'Subscribe to &amp;&quot;&#039;', 'theme_feed_icon() escapes reserved HTML characters.');
  2359. }
  2360. }
  2361. /**
  2362. * Test array diff functions.
  2363. */
  2364. class ArrayDiffUnitTest extends DrupalUnitTestCase {
  2365. /**
  2366. * Array to use for testing.
  2367. *
  2368. * @var array
  2369. */
  2370. protected $array1;
  2371. /**
  2372. * Array to use for testing.
  2373. *
  2374. * @var array
  2375. */
  2376. protected $array2;
  2377. public static function getInfo() {
  2378. return array(
  2379. 'name' => 'Array differences',
  2380. 'description' => 'Performs tests on drupal_array_diff_assoc_recursive().',
  2381. 'group' => 'System',
  2382. );
  2383. }
  2384. function setUp() {
  2385. parent::setUp();
  2386. $this->array1 = array(
  2387. 'same' => 'yes',
  2388. 'different' => 'no',
  2389. 'array_empty_diff' => array(),
  2390. 'null' => NULL,
  2391. 'int_diff' => 1,
  2392. 'array_diff' => array('same' => 'same', 'array' => array('same' => 'same')),
  2393. 'array_compared_to_string' => array('value'),
  2394. 'string_compared_to_array' => 'value',
  2395. 'new' => 'new',
  2396. );
  2397. $this->array2 = array(
  2398. 'same' => 'yes',
  2399. 'different' => 'yes',
  2400. 'array_empty_diff' => array(),
  2401. 'null' => NULL,
  2402. 'int_diff' => '1',
  2403. 'array_diff' => array('same' => 'different', 'array' => array('same' => 'same')),
  2404. 'array_compared_to_string' => 'value',
  2405. 'string_compared_to_array' => array('value'),
  2406. );
  2407. }
  2408. /**
  2409. * Tests drupal_array_diff_assoc_recursive().
  2410. */
  2411. public function testArrayDiffAssocRecursive() {
  2412. $expected = array(
  2413. 'different' => 'no',
  2414. 'int_diff' => 1,
  2415. // The 'array' key should not be returned, as it's the same.
  2416. 'array_diff' => array('same' => 'same'),
  2417. 'array_compared_to_string' => array('value'),
  2418. 'string_compared_to_array' => 'value',
  2419. 'new' => 'new',
  2420. );
  2421. $this->assertIdentical(drupal_array_diff_assoc_recursive($this->array1, $this->array2), $expected);
  2422. }
  2423. }