aggregator.test 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  1. <?php
  2. /**
  3. * @file
  4. * Tests for aggregator.module.
  5. */
  6. /**
  7. * Defines a base class for testing the Aggregator module.
  8. */
  9. class AggregatorTestCase extends DrupalWebTestCase {
  10. function setUp() {
  11. parent::setUp('aggregator', 'aggregator_test');
  12. $web_user = $this->drupalCreateUser(array('administer news feeds', 'access news feeds', 'create article content'));
  13. $this->drupalLogin($web_user);
  14. }
  15. /**
  16. * Creates an aggregator feed.
  17. *
  18. * This method simulates the form submission on path
  19. * admin/config/services/aggregator/add/feed.
  20. *
  21. * @param $feed_url
  22. * (optional) If given, feed will be created with this URL, otherwise
  23. * /rss.xml will be used. Defaults to NULL.
  24. *
  25. * @return $feed
  26. * Full feed object if possible.
  27. *
  28. * @see getFeedEditArray()
  29. */
  30. function createFeed($feed_url = NULL) {
  31. $edit = $this->getFeedEditArray($feed_url);
  32. $this->drupalPost('admin/config/services/aggregator/add/feed', $edit, t('Save'));
  33. $this->assertRaw(t('The feed %name has been added.', array('%name' => $edit['title'])), format_string('The feed !name has been added.', array('!name' => $edit['title'])));
  34. $feed = db_query("SELECT * FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $edit['title'], ':url' => $edit['url']))->fetch();
  35. $this->assertTrue(!empty($feed), 'The feed found in database.');
  36. return $feed;
  37. }
  38. /**
  39. * Deletes an aggregator feed.
  40. *
  41. * @param $feed
  42. * Feed object representing the feed.
  43. */
  44. function deleteFeed($feed) {
  45. $this->drupalPost('admin/config/services/aggregator/edit/feed/' . $feed->fid, array(), t('Delete'));
  46. $this->assertRaw(t('The feed %title has been deleted.', array('%title' => $feed->title)), 'Feed deleted successfully.');
  47. }
  48. /**
  49. * Returns a randomly generated feed edit array.
  50. *
  51. * @param $feed_url
  52. * (optional) If given, feed will be created with this URL, otherwise
  53. * /rss.xml will be used. Defaults to NULL.
  54. * @return
  55. * A feed array.
  56. */
  57. function getFeedEditArray($feed_url = NULL) {
  58. $feed_name = $this->randomName(10);
  59. if (!$feed_url) {
  60. $feed_url = url('rss.xml', array(
  61. 'query' => array('feed' => $feed_name),
  62. 'absolute' => TRUE,
  63. ));
  64. }
  65. $edit = array(
  66. 'title' => $feed_name,
  67. 'url' => $feed_url,
  68. 'refresh' => '900',
  69. );
  70. return $edit;
  71. }
  72. /**
  73. * Returns the count of the randomly created feed array.
  74. *
  75. * @return
  76. * Number of feed items on default feed created by createFeed().
  77. */
  78. function getDefaultFeedItemCount() {
  79. // Our tests are based off of rss.xml, so let's find out how many elements should be related.
  80. $feed_count = db_query_range('SELECT COUNT(*) FROM {node} n WHERE n.promote = 1 AND n.status = 1', 0, variable_get('feed_default_items', 10))->fetchField();
  81. return $feed_count > 10 ? 10 : $feed_count;
  82. }
  83. /**
  84. * Updates the feed items.
  85. *
  86. * This method simulates a click to
  87. * admin/config/services/aggregator/update/$fid.
  88. *
  89. * @param $feed
  90. * Feed object representing the feed, passed by reference.
  91. * @param $expected_count
  92. * Expected number of feed items.
  93. */
  94. function updateFeedItems(&$feed, $expected_count) {
  95. // First, let's ensure we can get to the rss xml.
  96. $this->drupalGet($feed->url);
  97. $this->assertResponse(200, format_string('!url is reachable.', array('!url' => $feed->url)));
  98. // Attempt to access the update link directly without an access token.
  99. $this->drupalGet('admin/config/services/aggregator/update/' . $feed->fid);
  100. $this->assertResponse(403);
  101. // Refresh the feed (simulated link click).
  102. $this->drupalGet('admin/config/services/aggregator');
  103. $this->clickLink('update items');
  104. // Ensure we have the right number of items.
  105. $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid));
  106. $items = array();
  107. $feed->items = array();
  108. foreach ($result as $item) {
  109. $feed->items[] = $item->iid;
  110. }
  111. $feed->item_count = count($feed->items);
  112. $this->assertEqual($expected_count, $feed->item_count, format_string('Total items in feed equal to the total items in database (!val1 != !val2)', array('!val1' => $expected_count, '!val2' => $feed->item_count)));
  113. }
  114. /**
  115. * Confirms an item removal from a feed.
  116. *
  117. * @param $feed
  118. * Feed object representing the feed.
  119. */
  120. function removeFeedItems($feed) {
  121. $this->drupalPost('admin/config/services/aggregator/remove/' . $feed->fid, array(), t('Remove items'));
  122. $this->assertRaw(t('The news items from %title have been removed.', array('%title' => $feed->title)), 'Feed items removed.');
  123. }
  124. /**
  125. * Adds and removes feed items and ensure that the count is zero.
  126. *
  127. * @param $feed
  128. * Feed object representing the feed.
  129. * @param $expected_count
  130. * Expected number of feed items.
  131. */
  132. function updateAndRemove($feed, $expected_count) {
  133. $this->updateFeedItems($feed, $expected_count);
  134. $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField();
  135. $this->assertTrue($count);
  136. $this->removeFeedItems($feed);
  137. $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField();
  138. $this->assertTrue($count == 0);
  139. }
  140. /**
  141. * Pulls feed categories from {aggregator_category_feed} table.
  142. *
  143. * @param $feed
  144. * Feed object representing the feed.
  145. */
  146. function getFeedCategories($feed) {
  147. // add the categories to the feed so we can use them
  148. $result = db_query('SELECT cid FROM {aggregator_category_feed} WHERE fid = :fid', array(':fid' => $feed->fid));
  149. foreach ($result as $category) {
  150. $feed->categories[] = $category->cid;
  151. }
  152. }
  153. /**
  154. * Pulls categories from {aggregator_category} table.
  155. *
  156. * @return
  157. * An associative array keyed by category ID and values are set to the
  158. * category names.
  159. */
  160. function getCategories() {
  161. $categories = array();
  162. $result = db_query('SELECT * FROM {aggregator_category}');
  163. foreach ($result as $category) {
  164. $categories[$category->cid] = $category;
  165. }
  166. return $categories;
  167. }
  168. /**
  169. * Checks whether the feed name and URL are unique.
  170. *
  171. * @param $feed_name
  172. * String containing the feed name to check.
  173. * @param $feed_url
  174. * String containing the feed URL to check.
  175. *
  176. * @return
  177. * TRUE if feed is unique.
  178. */
  179. function uniqueFeed($feed_name, $feed_url) {
  180. $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $feed_name, ':url' => $feed_url))->fetchField();
  181. return (1 == $result);
  182. }
  183. /**
  184. * Creates a valid OPML file from an array of feeds.
  185. *
  186. * @param $feeds
  187. * An array of feeds.
  188. *
  189. * @return
  190. * Path to valid OPML file.
  191. */
  192. function getValidOpml($feeds) {
  193. // Properly escape URLs so that XML parsers don't choke on them.
  194. foreach ($feeds as &$feed) {
  195. $feed['url'] = htmlspecialchars($feed['url']);
  196. }
  197. /**
  198. * Does not have an XML declaration, must pass the parser.
  199. */
  200. $opml = <<<EOF
  201. <opml version="1.0">
  202. <head></head>
  203. <body>
  204. <!-- First feed to be imported. -->
  205. <outline text="{$feeds[0]['title']}" xmlurl="{$feeds[0]['url']}" />
  206. <!-- Second feed. Test string delimitation and attribute order. -->
  207. <outline xmlurl='{$feeds[1]['url']}' text='{$feeds[1]['title']}'/>
  208. <!-- Test for duplicate URL and title. -->
  209. <outline xmlurl="{$feeds[0]['url']}" text="Duplicate URL"/>
  210. <outline xmlurl="http://duplicate.title" text="{$feeds[1]['title']}"/>
  211. <!-- Test that feeds are only added with required attributes. -->
  212. <outline text="{$feeds[2]['title']}" />
  213. <outline xmlurl="{$feeds[2]['url']}" />
  214. </body>
  215. </opml>
  216. EOF;
  217. $path = 'public://valid-opml.xml';
  218. return file_unmanaged_save_data($opml, $path);
  219. }
  220. /**
  221. * Creates an invalid OPML file.
  222. *
  223. * @return
  224. * Path to invalid OPML file.
  225. */
  226. function getInvalidOpml() {
  227. $opml = <<<EOF
  228. <opml>
  229. <invalid>
  230. </opml>
  231. EOF;
  232. $path = 'public://invalid-opml.xml';
  233. return file_unmanaged_save_data($opml, $path);
  234. }
  235. /**
  236. * Creates a valid but empty OPML file.
  237. *
  238. * @return
  239. * Path to empty OPML file.
  240. */
  241. function getEmptyOpml() {
  242. $opml = <<<EOF
  243. <?xml version="1.0" encoding="utf-8"?>
  244. <opml version="1.0">
  245. <head></head>
  246. <body>
  247. <outline text="Sample text" />
  248. <outline text="Sample text" url="Sample URL" />
  249. </body>
  250. </opml>
  251. EOF;
  252. $path = 'public://empty-opml.xml';
  253. return file_unmanaged_save_data($opml, $path);
  254. }
  255. function getRSS091Sample() {
  256. return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/aggregator_test_rss091.xml';
  257. }
  258. function getAtomSample() {
  259. // The content of this sample ATOM feed is based directly off of the
  260. // example provided in RFC 4287.
  261. return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/aggregator_test_atom.xml';
  262. }
  263. function getHtmlEntitiesSample() {
  264. return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/aggregator_test_title_entities.xml';
  265. }
  266. /**
  267. * Creates sample article nodes.
  268. *
  269. * @param $count
  270. * (optional) The number of nodes to generate. Defaults to five.
  271. */
  272. function createSampleNodes($count = 5) {
  273. $langcode = LANGUAGE_NONE;
  274. // Post $count article nodes.
  275. for ($i = 0; $i < $count; $i++) {
  276. $edit = array();
  277. $edit['title'] = $this->randomName();
  278. $edit["body[$langcode][0][value]"] = $this->randomName();
  279. $this->drupalPost('node/add/article', $edit, t('Save'));
  280. }
  281. }
  282. }
  283. /**
  284. * Tests functionality of the configuration settings in the Aggregator module.
  285. */
  286. class AggregatorConfigurationTestCase extends AggregatorTestCase {
  287. public static function getInfo() {
  288. return array(
  289. 'name' => 'Aggregator configuration',
  290. 'description' => 'Test aggregator settings page.',
  291. 'group' => 'Aggregator',
  292. );
  293. }
  294. /**
  295. * Tests the settings form to ensure the correct default values are used.
  296. */
  297. function testSettingsPage() {
  298. $edit = array(
  299. 'aggregator_allowed_html_tags' => '<a>',
  300. 'aggregator_summary_items' => 10,
  301. 'aggregator_clear' => 3600,
  302. 'aggregator_category_selector' => 'select',
  303. 'aggregator_teaser_length' => 200,
  304. );
  305. $this->drupalPost('admin/config/services/aggregator/settings', $edit, t('Save configuration'));
  306. $this->assertText(t('The configuration options have been saved.'));
  307. foreach ($edit as $name => $value) {
  308. $this->assertFieldByName($name, $value, format_string('"@name" has correct default value.', array('@name' => $name)));
  309. }
  310. }
  311. }
  312. /**
  313. * Tests adding aggregator feeds.
  314. */
  315. class AddFeedTestCase extends AggregatorTestCase {
  316. public static function getInfo() {
  317. return array(
  318. 'name' => 'Add feed functionality',
  319. 'description' => 'Add feed test.',
  320. 'group' => 'Aggregator'
  321. );
  322. }
  323. /**
  324. * Creates and ensures that a feed is unique, checks source, and deletes feed.
  325. */
  326. function testAddFeed() {
  327. $feed = $this->createFeed();
  328. // Check feed data.
  329. $this->assertEqual($this->getUrl(), url('admin/config/services/aggregator/add/feed', array('absolute' => TRUE)), 'Directed to correct url.');
  330. $this->assertTrue($this->uniqueFeed($feed->title, $feed->url), 'The feed is unique.');
  331. // Check feed source.
  332. $this->drupalGet('aggregator/sources/' . $feed->fid);
  333. $this->assertResponse(200, 'Feed source exists.');
  334. $this->assertText($feed->title, 'Page title');
  335. $this->drupalGet('aggregator/sources/' . $feed->fid . '/categorize');
  336. $this->assertResponse(200, 'Feed categorization page exists.');
  337. // Delete feed.
  338. $this->deleteFeed($feed);
  339. }
  340. /**
  341. * Tests feeds with very long URLs.
  342. */
  343. function testAddLongFeed() {
  344. // Create a feed with a URL of > 255 characters.
  345. $long_url = "https://www.google.com/search?ix=heb&sourceid=chrome&ie=UTF-8&q=angie+byron#sclient=psy-ab&hl=en&safe=off&source=hp&q=angie+byron&pbx=1&oq=angie+byron&aq=f&aqi=&aql=&gs_sm=3&gs_upl=0l0l0l10534l0l0l0l0l0l0l0l0ll0l0&bav=on.2,or.r_gc.r_pw.r_cp.,cf.osb&fp=a70b6b1f0abe28d8&biw=1629&bih=889&ix=heb";
  346. $feed = $this->createFeed($long_url);
  347. // Create a second feed of > 255 characters, where the only difference is
  348. // after the 255th character.
  349. $long_url_2 = "https://www.google.com/search?ix=heb&sourceid=chrome&ie=UTF-8&q=angie+byron#sclient=psy-ab&hl=en&safe=off&source=hp&q=angie+byron&pbx=1&oq=angie+byron&aq=f&aqi=&aql=&gs_sm=3&gs_upl=0l0l0l10534l0l0l0l0l0l0l0l0ll0l0&bav=on.2,or.r_gc.r_pw.r_cp.,cf.osb&fp=a70b6b1f0abe28d8&biw=1629&bih=889";
  350. $feed_2 = $this->createFeed($long_url_2);
  351. // Check feed data.
  352. $this->assertTrue($this->uniqueFeed($feed->title, $feed->url), 'The first long URL feed is unique.');
  353. $this->assertTrue($this->uniqueFeed($feed_2->title, $feed_2->url), 'The second long URL feed is unique.');
  354. // Check feed source.
  355. $this->drupalGet('aggregator/sources/' . $feed->fid);
  356. $this->assertResponse(200, 'Long URL feed source exists.');
  357. $this->assertText($feed->title, 'Page title');
  358. $this->drupalGet('aggregator/sources/' . $feed->fid . '/categorize');
  359. $this->assertResponse(200, 'Long URL feed categorization page exists.');
  360. // Delete feeds.
  361. $this->deleteFeed($feed);
  362. $this->deleteFeed($feed_2);
  363. }
  364. }
  365. /**
  366. * Tests the categorize feed functionality in the Aggregator module.
  367. */
  368. class CategorizeFeedTestCase extends AggregatorTestCase {
  369. public static function getInfo() {
  370. return array(
  371. 'name' => 'Categorize feed functionality',
  372. 'description' => 'Categorize feed test.',
  373. 'group' => 'Aggregator'
  374. );
  375. }
  376. /**
  377. * Creates a feed and makes sure you can add/delete categories to it.
  378. */
  379. function testCategorizeFeed() {
  380. // Create 2 categories.
  381. $category_1 = array('title' => $this->randomName(10), 'description' => '');
  382. $this->drupalPost('admin/config/services/aggregator/add/category', $category_1, t('Save'));
  383. $this->assertRaw(t('The category %title has been added.', array('%title' => $category_1['title'])), format_string('The category %title has been added.', array('%title' => $category_1['title'])));
  384. $category_2 = array('title' => $this->randomName(10), 'description' => '');
  385. $this->drupalPost('admin/config/services/aggregator/add/category', $category_2, t('Save'));
  386. $this->assertRaw(t('The category %title has been added.', array('%title' => $category_2['title'])), format_string('The category %title has been added.', array('%title' => $category_2['title'])));
  387. // Get categories from database.
  388. $categories = $this->getCategories();
  389. // Create a feed and assign 2 categories to it.
  390. $feed = $this->getFeedEditArray();
  391. $feed['block'] = 5;
  392. foreach ($categories as $cid => $category) {
  393. $feed['category'][$cid] = $cid;
  394. }
  395. // Use aggregator_save_feed() function to save the feed.
  396. aggregator_save_feed($feed);
  397. $db_feed = db_query("SELECT * FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $feed['title'], ':url' => $feed['url']))->fetch();
  398. // Assert the feed has two categories.
  399. $this->getFeedCategories($db_feed);
  400. $this->assertEqual(count($db_feed->categories), 2, 'Feed has 2 categories');
  401. // Use aggregator_save_feed() to delete a category.
  402. $category = reset($categories);
  403. aggregator_save_category(array('cid' => $category->cid));
  404. // Assert that category is deleted.
  405. $db_category = db_query("SELECT COUNT(*) FROM {aggregator_category} WHERE cid = :cid", array(':cid' => $category->cid))->fetchField();
  406. $this->assertFalse($db_category, format_string('The category %title has been deleted.', array('%title' => $category->title)));
  407. // Assert that category has been removed from feed.
  408. $categorized_feeds = db_query("SELECT COUNT(*) FROM {aggregator_category_feed} WHERE cid = :cid", array(':cid' => $category->cid))->fetchField();
  409. $this->assertFalse($categorized_feeds, format_string('The category %title has been removed from feed %feed_title.', array('%title' => $category->title, '%feed_title' => $feed['title'])));
  410. // Assert that no broken links (associated with the deleted category)
  411. // appear on one of the other category pages.
  412. $this->createSampleNodes();
  413. $this->drupalGet('admin/config/services/aggregator');
  414. $this->clickLink('update items');
  415. $categories = $this->getCategories();
  416. $category = reset($categories);
  417. $this->drupalGet('aggregator/categories/' . $category->cid);
  418. global $base_path;
  419. $this->assertNoRaw('<a href="' . $base_path . 'aggregator/categories/"></a>,');
  420. }
  421. }
  422. /**
  423. * Tests functionality of updating the feed in the Aggregator module.
  424. */
  425. class UpdateFeedTestCase extends AggregatorTestCase {
  426. public static function getInfo() {
  427. return array(
  428. 'name' => 'Update feed functionality',
  429. 'description' => 'Update feed test.',
  430. 'group' => 'Aggregator'
  431. );
  432. }
  433. /**
  434. * Creates a feed and attempts to update it.
  435. */
  436. function testUpdateFeed() {
  437. $remamining_fields = array('title', 'url', '');
  438. foreach ($remamining_fields as $same_field) {
  439. $feed = $this->createFeed();
  440. // Get new feed data array and modify newly created feed.
  441. $edit = $this->getFeedEditArray();
  442. $edit['refresh'] = 1800; // Change refresh value.
  443. if (isset($feed->{$same_field})) {
  444. $edit[$same_field] = $feed->{$same_field};
  445. }
  446. $this->drupalPost('admin/config/services/aggregator/edit/feed/' . $feed->fid, $edit, t('Save'));
  447. $this->assertRaw(t('The feed %name has been updated.', array('%name' => $edit['title'])), format_string('The feed %name has been updated.', array('%name' => $edit['title'])));
  448. // Check feed data.
  449. $this->assertEqual($this->getUrl(), url('admin/config/services/aggregator/', array('absolute' => TRUE)));
  450. $this->assertTrue($this->uniqueFeed($edit['title'], $edit['url']), 'The feed is unique.');
  451. // Check feed source.
  452. $this->drupalGet('aggregator/sources/' . $feed->fid);
  453. $this->assertResponse(200, 'Feed source exists.');
  454. $this->assertText($edit['title'], 'Page title');
  455. // Delete feed.
  456. $feed->title = $edit['title']; // Set correct title so deleteFeed() will work.
  457. $this->deleteFeed($feed);
  458. }
  459. }
  460. }
  461. /**
  462. * Tests functionality for removing feeds in the Aggregator module.
  463. */
  464. class RemoveFeedTestCase extends AggregatorTestCase {
  465. public static function getInfo() {
  466. return array(
  467. 'name' => 'Remove feed functionality',
  468. 'description' => 'Remove feed test.',
  469. 'group' => 'Aggregator'
  470. );
  471. }
  472. /**
  473. * Removes a feed and ensures that all of its services are removed.
  474. */
  475. function testRemoveFeed() {
  476. $feed = $this->createFeed();
  477. // Delete feed.
  478. $this->deleteFeed($feed);
  479. // Check feed source.
  480. $this->drupalGet('aggregator/sources/' . $feed->fid);
  481. $this->assertResponse(404, 'Deleted feed source does not exists.');
  482. // Check database for feed.
  483. $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $feed->title, ':url' => $feed->url))->fetchField();
  484. $this->assertFalse($result, 'Feed not found in database');
  485. }
  486. }
  487. /**
  488. * Tests functionality of updating a feed item in the Aggregator module.
  489. */
  490. class UpdateFeedItemTestCase extends AggregatorTestCase {
  491. public static function getInfo() {
  492. return array(
  493. 'name' => 'Update feed item functionality',
  494. 'description' => 'Update feed items from a feed.',
  495. 'group' => 'Aggregator'
  496. );
  497. }
  498. /**
  499. * Tests running "update items" from 'admin/config/services/aggregator' page.
  500. */
  501. function testUpdateFeedItem() {
  502. $this->createSampleNodes();
  503. // Create a feed and test updating feed items if possible.
  504. $feed = $this->createFeed();
  505. if (!empty($feed)) {
  506. $this->updateFeedItems($feed, $this->getDefaultFeedItemCount());
  507. $this->removeFeedItems($feed);
  508. }
  509. // Delete feed.
  510. $this->deleteFeed($feed);
  511. // Test updating feed items without valid timestamp information.
  512. $edit = array(
  513. 'title' => "Feed without publish timestamp",
  514. 'url' => $this->getRSS091Sample(),
  515. );
  516. $this->drupalGet($edit['url']);
  517. $this->assertResponse(array(200), format_string('URL !url is accessible', array('!url' => $edit['url'])));
  518. $this->drupalPost('admin/config/services/aggregator/add/feed', $edit, t('Save'));
  519. $this->assertRaw(t('The feed %name has been added.', array('%name' => $edit['title'])), format_string('The feed !name has been added.', array('!name' => $edit['title'])));
  520. $feed = db_query("SELECT * FROM {aggregator_feed} WHERE url = :url", array(':url' => $edit['url']))->fetchObject();
  521. aggregator_refresh($feed);
  522. $before = db_query('SELECT timestamp FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField();
  523. // Sleep for 3 second.
  524. sleep(3);
  525. db_update('aggregator_feed')
  526. ->condition('fid', $feed->fid)
  527. ->fields(array(
  528. 'checked' => 0,
  529. 'hash' => '',
  530. 'etag' => '',
  531. 'modified' => 0,
  532. ))
  533. ->execute();
  534. aggregator_refresh($feed);
  535. $after = db_query('SELECT timestamp FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField();
  536. $this->assertTrue($before === $after, format_string('Publish timestamp of feed item was not updated (!before === !after)', array('!before' => $before, '!after' => $after)));
  537. }
  538. }
  539. class RemoveFeedItemTestCase extends AggregatorTestCase {
  540. public static function getInfo() {
  541. return array(
  542. 'name' => 'Remove feed item functionality',
  543. 'description' => 'Remove feed items from a feed.',
  544. 'group' => 'Aggregator'
  545. );
  546. }
  547. /**
  548. * Tests running "remove items" from 'admin/config/services/aggregator' page.
  549. */
  550. function testRemoveFeedItem() {
  551. // Create a bunch of test feeds.
  552. $feed_urls = array();
  553. // No last-modified, no etag.
  554. $feed_urls[] = url('aggregator/test-feed', array('absolute' => TRUE));
  555. // Last-modified, but no etag.
  556. $feed_urls[] = url('aggregator/test-feed/1', array('absolute' => TRUE));
  557. // No Last-modified, but etag.
  558. $feed_urls[] = url('aggregator/test-feed/0/1', array('absolute' => TRUE));
  559. // Last-modified and etag.
  560. $feed_urls[] = url('aggregator/test-feed/1/1', array('absolute' => TRUE));
  561. foreach ($feed_urls as $feed_url) {
  562. $feed = $this->createFeed($feed_url);
  563. // Update and remove items two times in a row to make sure that removal
  564. // resets all 'modified' information (modified, etag, hash) and allows for
  565. // immediate update.
  566. $this->updateAndRemove($feed, 4);
  567. $this->updateAndRemove($feed, 4);
  568. $this->updateAndRemove($feed, 4);
  569. // Delete feed.
  570. $this->deleteFeed($feed);
  571. }
  572. }
  573. }
  574. /**
  575. * Tests categorization functionality in the Aggregator module.
  576. */
  577. class CategorizeFeedItemTestCase extends AggregatorTestCase {
  578. public static function getInfo() {
  579. return array(
  580. 'name' => 'Categorize feed item functionality',
  581. 'description' => 'Test feed item categorization.',
  582. 'group' => 'Aggregator'
  583. );
  584. }
  585. /**
  586. * Checks that children of a feed inherit a defined category.
  587. *
  588. * If a feed has a category, make sure that the children inherit that
  589. * categorization.
  590. */
  591. function testCategorizeFeedItem() {
  592. $this->createSampleNodes();
  593. // Simulate form submission on "admin/config/services/aggregator/add/category".
  594. $edit = array('title' => $this->randomName(10), 'description' => '');
  595. $this->drupalPost('admin/config/services/aggregator/add/category', $edit, t('Save'));
  596. $this->assertRaw(t('The category %title has been added.', array('%title' => $edit['title'])), format_string('The category %title has been added.', array('%title' => $edit['title'])));
  597. $category = db_query("SELECT * FROM {aggregator_category} WHERE title = :title", array(':title' => $edit['title']))->fetch();
  598. $this->assertTrue(!empty($category), 'The category found in database.');
  599. $link_path = 'aggregator/categories/' . $category->cid;
  600. $menu_link = db_query("SELECT * FROM {menu_links} WHERE link_path = :link_path", array(':link_path' => $link_path))->fetch();
  601. $this->assertTrue(!empty($menu_link), 'The menu link associated with the category found in database.');
  602. $feed = $this->createFeed();
  603. db_insert('aggregator_category_feed')
  604. ->fields(array(
  605. 'cid' => $category->cid,
  606. 'fid' => $feed->fid,
  607. ))
  608. ->execute();
  609. $this->updateFeedItems($feed, $this->getDefaultFeedItemCount());
  610. $this->getFeedCategories($feed);
  611. $this->assertTrue(!empty($feed->categories), 'The category found in the feed.');
  612. // For each category of a feed, ensure feed items have that category, too.
  613. if (!empty($feed->categories) && !empty($feed->items)) {
  614. foreach ($feed->categories as $category) {
  615. $categorized_count = db_select('aggregator_category_item')
  616. ->condition('iid', $feed->items, 'IN')
  617. ->countQuery()
  618. ->execute()
  619. ->fetchField();
  620. $this->assertEqual($feed->item_count, $categorized_count, 'Total items in feed equal to the total categorized feed items in database');
  621. }
  622. }
  623. // Delete category from feed items when category is deleted.
  624. $cid = reset($feed->categories);
  625. $categories = $this->getCategories();
  626. $category_title = $categories[$cid]->title;
  627. // Delete category.
  628. aggregator_save_category(array('cid' => $cid));
  629. // Assert category has been removed from feed items.
  630. $categorized_count = db_query("SELECT COUNT(*) FROM {aggregator_category_item} WHERE cid = :cid", array(':cid' => $cid))->fetchField();
  631. $this->assertFalse($categorized_count, format_string('The category %title has been removed from feed items.', array('%title' => $category_title)));
  632. // Delete feed.
  633. $this->deleteFeed($feed);
  634. }
  635. }
  636. /**
  637. * Tests importing feeds from OPML functionality for the Aggregator module.
  638. */
  639. class ImportOPMLTestCase extends AggregatorTestCase {
  640. public static function getInfo() {
  641. return array(
  642. 'name' => 'Import feeds from OPML functionality',
  643. 'description' => 'Test OPML import.',
  644. 'group' => 'Aggregator',
  645. );
  646. }
  647. /**
  648. * Opens OPML import form.
  649. */
  650. function openImportForm() {
  651. db_delete('aggregator_category')->execute();
  652. $category = $this->randomName(10);
  653. $cid = db_insert('aggregator_category')
  654. ->fields(array(
  655. 'title' => $category,
  656. 'description' => '',
  657. ))
  658. ->execute();
  659. $this->drupalGet('admin/config/services/aggregator/add/opml');
  660. $this->assertText('A single OPML document may contain a collection of many feeds.', 'Found OPML help text.');
  661. $this->assertField('files[upload]', 'Found file upload field.');
  662. $this->assertField('remote', 'Found Remote URL field.');
  663. $this->assertField('refresh', 'Found Refresh field.');
  664. $this->assertFieldByName("category[$cid]", $cid, 'Found category field.');
  665. }
  666. /**
  667. * Submits form filled with invalid fields.
  668. */
  669. function validateImportFormFields() {
  670. $before = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
  671. $edit = array();
  672. $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
  673. $this->assertRaw(t('You must <em>either</em> upload a file or enter a URL.'), 'Error if no fields are filled.');
  674. $path = $this->getEmptyOpml();
  675. $edit = array(
  676. 'files[upload]' => $path,
  677. 'remote' => file_create_url($path),
  678. );
  679. $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
  680. $this->assertRaw(t('You must <em>either</em> upload a file or enter a URL.'), 'Error if both fields are filled.');
  681. $edit = array('remote' => 'invalidUrl://empty');
  682. $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
  683. $this->assertText(t('This URL is not valid.'), 'Error if the URL is invalid.');
  684. $after = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
  685. $this->assertEqual($before, $after, 'No feeds were added during the three last form submissions.');
  686. }
  687. /**
  688. * Submits form with invalid, empty, and valid OPML files.
  689. */
  690. function submitImportForm() {
  691. $before = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
  692. $form['files[upload]'] = $this->getInvalidOpml();
  693. $this->drupalPost('admin/config/services/aggregator/add/opml', $form, t('Import'));
  694. $this->assertText(t('No new feed has been added.'), 'Attempting to upload invalid XML.');
  695. $edit = array('remote' => file_create_url($this->getEmptyOpml()));
  696. $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
  697. $this->assertText(t('No new feed has been added.'), 'Attempting to load empty OPML from remote URL.');
  698. $after = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
  699. $this->assertEqual($before, $after, 'No feeds were added during the two last form submissions.');
  700. db_delete('aggregator_feed')->execute();
  701. db_delete('aggregator_category')->execute();
  702. db_delete('aggregator_category_feed')->execute();
  703. $category = $this->randomName(10);
  704. db_insert('aggregator_category')
  705. ->fields(array(
  706. 'cid' => 1,
  707. 'title' => $category,
  708. 'description' => '',
  709. ))
  710. ->execute();
  711. $feeds[0] = $this->getFeedEditArray();
  712. $feeds[1] = $this->getFeedEditArray();
  713. $feeds[2] = $this->getFeedEditArray();
  714. $edit = array(
  715. 'files[upload]' => $this->getValidOpml($feeds),
  716. 'refresh' => '900',
  717. 'category[1]' => $category,
  718. );
  719. $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
  720. $this->assertRaw(t('A feed with the URL %url already exists.', array('%url' => $feeds[0]['url'])), 'Verifying that a duplicate URL was identified');
  721. $this->assertRaw(t('A feed named %title already exists.', array('%title' => $feeds[1]['title'])), 'Verifying that a duplicate title was identified');
  722. $after = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
  723. $this->assertEqual($after, 2, 'Verifying that two distinct feeds were added.');
  724. $feeds_from_db = db_query("SELECT f.title, f.url, f.refresh, cf.cid FROM {aggregator_feed} f LEFT JOIN {aggregator_category_feed} cf ON f.fid = cf.fid");
  725. $refresh = $category = TRUE;
  726. foreach ($feeds_from_db as $feed) {
  727. $title[$feed->url] = $feed->title;
  728. $url[$feed->title] = $feed->url;
  729. $category = $category && $feed->cid == 1;
  730. $refresh = $refresh && $feed->refresh == 900;
  731. }
  732. $this->assertEqual($title[$feeds[0]['url']], $feeds[0]['title'], 'First feed was added correctly.');
  733. $this->assertEqual($url[$feeds[1]['title']], $feeds[1]['url'], 'Second feed was added correctly.');
  734. $this->assertTrue($refresh, 'Refresh times are correct.');
  735. $this->assertTrue($category, 'Categories are correct.');
  736. }
  737. /**
  738. * Tests the import of an OPML file.
  739. */
  740. function testOPMLImport() {
  741. $this->openImportForm();
  742. $this->validateImportFormFields();
  743. $this->submitImportForm();
  744. }
  745. }
  746. /**
  747. * Tests functionality of the cron process in the Aggregator module.
  748. */
  749. class AggregatorCronTestCase extends AggregatorTestCase {
  750. public static function getInfo() {
  751. return array(
  752. 'name' => 'Update on cron functionality',
  753. 'description' => 'Update feeds on cron.',
  754. 'group' => 'Aggregator'
  755. );
  756. }
  757. /**
  758. * Adds feeds and updates them via cron process.
  759. */
  760. public function testCron() {
  761. // Create feed and test basic updating on cron.
  762. global $base_url;
  763. $key = variable_get('cron_key', 'drupal');
  764. $this->createSampleNodes();
  765. $feed = $this->createFeed();
  766. $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
  767. $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
  768. $this->removeFeedItems($feed);
  769. $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
  770. $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
  771. $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
  772. // Test feed locking when queued for update.
  773. $this->removeFeedItems($feed);
  774. db_update('aggregator_feed')
  775. ->condition('fid', $feed->fid)
  776. ->fields(array(
  777. 'queued' => REQUEST_TIME,
  778. ))
  779. ->execute();
  780. $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
  781. $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
  782. db_update('aggregator_feed')
  783. ->condition('fid', $feed->fid)
  784. ->fields(array(
  785. 'queued' => 0,
  786. ))
  787. ->execute();
  788. $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
  789. $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
  790. }
  791. }
  792. /**
  793. * Tests rendering functionality in the Aggregator module.
  794. */
  795. class AggregatorRenderingTestCase extends AggregatorTestCase {
  796. public static function getInfo() {
  797. return array(
  798. 'name' => 'Checks display of aggregator items',
  799. 'description' => 'Checks display of aggregator items on the page.',
  800. 'group' => 'Aggregator'
  801. );
  802. }
  803. /**
  804. * Adds a feed block to the page and checks its links.
  805. *
  806. * @todo Test the category block as well.
  807. */
  808. public function testBlockLinks() {
  809. // Create feed.
  810. $this->createSampleNodes();
  811. $feed = $this->createFeed();
  812. $this->updateFeedItems($feed, $this->getDefaultFeedItemCount());
  813. // Place block on page (@see block.test:moveBlockToRegion())
  814. // Need admin user to be able to access block admin.
  815. $this->admin_user = $this->drupalCreateUser(array(
  816. 'administer blocks',
  817. 'access administration pages',
  818. 'administer news feeds',
  819. 'access news feeds',
  820. ));
  821. $this->drupalLogin($this->admin_user);
  822. // Prepare to use the block admin form.
  823. $block = array(
  824. 'module' => 'aggregator',
  825. 'delta' => 'feed-' . $feed->fid,
  826. 'title' => $feed->title,
  827. );
  828. $region = 'footer';
  829. $edit = array();
  830. $edit['blocks[' . $block['module'] . '_' . $block['delta'] . '][region]'] = $region;
  831. // Check the feed block is available in the block list form.
  832. $this->drupalGet('admin/structure/block');
  833. $this->assertFieldByName('blocks[' . $block['module'] . '_' . $block['delta'] . '][region]', '', 'Aggregator feed block is available for positioning.');
  834. // Position it.
  835. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  836. $this->assertText(t('The block settings have been updated.'), format_string('Block successfully moved to %region_name region.', array( '%region_name' => $region)));
  837. // Confirm that the block is now being displayed on pages.
  838. $this->drupalGet('node');
  839. $this->assertText(t($block['title']), 'Feed block is displayed on the page.');
  840. // Find the expected read_more link.
  841. $href = 'aggregator/sources/' . $feed->fid;
  842. $links = $this->xpath('//a[@href = :href]', array(':href' => url($href)));
  843. $this->assert(isset($links[0]), format_string('Link to href %href found.', array('%href' => $href)));
  844. // Visit that page.
  845. $this->drupalGet($href);
  846. $correct_titles = $this->xpath('//h1[normalize-space(text())=:title]', array(':title' => $feed->title));
  847. $this->assertFalse(empty($correct_titles), 'Aggregator feed page is available and has the correct title.');
  848. // Set the number of news items to 0 to test that the block does not show
  849. // up.
  850. $feed->block = 0;
  851. aggregator_save_feed((array) $feed);
  852. // It is necessary to flush the cache after saving the number of items.
  853. drupal_flush_all_caches();
  854. // Check that the block is no longer displayed.
  855. $this->drupalGet('node');
  856. $this->assertNoText(t($block['title']), 'Feed block is not displayed on the page when number of items is set to 0.');
  857. }
  858. /**
  859. * Creates a feed and checks that feed's page.
  860. */
  861. public function testFeedPage() {
  862. // Increase the number of items published in the rss.xml feed so we have
  863. // enough articles to test paging.
  864. variable_set('feed_default_items', 30);
  865. // Create a feed with 30 items.
  866. $this->createSampleNodes(30);
  867. $feed = $this->createFeed();
  868. $this->updateFeedItems($feed, 30);
  869. // Check for the presence of a pager.
  870. $this->drupalGet('aggregator/sources/' . $feed->fid);
  871. $elements = $this->xpath("//ul[@class=:class]", array(':class' => 'pager'));
  872. $this->assertTrue(!empty($elements), 'Individual source page contains a pager.');
  873. // Reset the number of items in rss.xml to the default value.
  874. variable_set('feed_default_items', 10);
  875. }
  876. }
  877. /**
  878. * Tests feed parsing in the Aggregator module.
  879. */
  880. class FeedParserTestCase extends AggregatorTestCase {
  881. public static function getInfo() {
  882. return array(
  883. 'name' => 'Feed parser functionality',
  884. 'description' => 'Test the built-in feed parser with valid feed samples.',
  885. 'group' => 'Aggregator',
  886. );
  887. }
  888. function setUp() {
  889. parent::setUp();
  890. // Do not remove old aggregator items during these tests, since our sample
  891. // feeds have hardcoded dates in them (which may be expired when this test
  892. // is run).
  893. variable_set('aggregator_clear', AGGREGATOR_CLEAR_NEVER);
  894. }
  895. /**
  896. * Tests a feed that uses the RSS 0.91 format.
  897. */
  898. function testRSS091Sample() {
  899. $feed = $this->createFeed($this->getRSS091Sample());
  900. aggregator_refresh($feed);
  901. $this->drupalGet('aggregator/sources/' . $feed->fid);
  902. $this->assertResponse(200, format_string('Feed %name exists.', array('%name' => $feed->title)));
  903. $this->assertText('First example feed item title');
  904. $this->assertLinkByHref('http://example.com/example-turns-one');
  905. $this->assertText('First example feed item description.');
  906. // Several additional items that include elements over 255 characters.
  907. $this->assertRaw("Second example feed item title.");
  908. $this->assertText('Long link feed item title');
  909. $this->assertText('Long link feed item description');
  910. $this->assertLinkByHref('http://example.com/tomorrow/and/tomorrow/and/tomorrow/creeps/in/this/petty/pace/from/day/to/day/to/the/last/syllable/of/recorded/time/and/all/our/yesterdays/have/lighted/fools/the/way/to/dusty/death/out/out/brief/candle/life/is/but/a/walking/shadow/a/poor/player/that/struts/and/frets/his/hour/upon/the/stage/and/is/heard/no/more/it/is/a/tale/told/by/an/idiot/full/of/sound/and/fury/signifying/nothing');
  911. $this->assertText('Long author feed item title');
  912. $this->assertText('Long author feed item description');
  913. $this->assertLinkByHref('http://example.com/long/author');
  914. }
  915. /**
  916. * Tests a feed that uses the Atom format.
  917. */
  918. function testAtomSample() {
  919. $feed = $this->createFeed($this->getAtomSample());
  920. aggregator_refresh($feed);
  921. $this->drupalGet('aggregator/sources/' . $feed->fid);
  922. $this->assertResponse(200, format_string('Feed %name exists.', array('%name' => $feed->title)));
  923. $this->assertText('Atom-Powered Robots Run Amok');
  924. $this->assertLinkByHref('http://example.org/2003/12/13/atom03');
  925. $this->assertText('Some text.');
  926. $this->assertEqual('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a', db_query('SELECT guid FROM {aggregator_item} WHERE link = :link', array(':link' => 'http://example.org/2003/12/13/atom03'))->fetchField(), 'Atom entry id element is parsed correctly.');
  927. }
  928. /**
  929. * Tests a feed that uses HTML entities in item titles.
  930. */
  931. function testHtmlEntitiesSample() {
  932. $feed = $this->createFeed($this->getHtmlEntitiesSample());
  933. aggregator_refresh($feed);
  934. $this->drupalGet('aggregator/sources/' . $feed->fid);
  935. $this->assertResponse(200, format_string('Feed %name exists.', array('%name' => $feed->title)));
  936. $this->assertRaw("Quote&quot; Amp&amp;");
  937. }
  938. }