aggregator.test

Tests for aggregator.module.

Classes

Namesort descending Description
AddFeedTestCase Tests adding aggregator feeds.
AggregatorConfigurationTestCase Tests functionality of the configuration settings in the Aggregator module.
AggregatorCronTestCase Tests functionality of the cron process in the Aggregator module.
AggregatorRenderingTestCase Tests rendering functionality in the Aggregator module.
AggregatorTestCase Defines a base class for testing the Aggregator module.
CategorizeFeedItemTestCase Tests categorization functionality in the Aggregator module.
CategorizeFeedTestCase Tests the categorize feed functionality in the Aggregator module.
FeedParserTestCase Tests feed parsing in the Aggregator module.
ImportOPMLTestCase Tests importing feeds from OPML functionality for the Aggregator module.
RemoveFeedItemTestCase
RemoveFeedTestCase Tests functionality for removing feeds in the Aggregator module.
UpdateFeedItemTestCase Tests functionality of updating a feed item in the Aggregator module.
UpdateFeedTestCase Tests functionality of updating the feed in the Aggregator module.

File

drupal/modules/aggregator/aggregator.test
View source
  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 more than one category 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. }
  402. }
  403. /**
  404. * Tests functionality of updating the feed in the Aggregator module.
  405. */
  406. class UpdateFeedTestCase extends AggregatorTestCase {
  407. public static function getInfo() {
  408. return array(
  409. 'name' => 'Update feed functionality',
  410. 'description' => 'Update feed test.',
  411. 'group' => 'Aggregator'
  412. );
  413. }
  414. /**
  415. * Creates a feed and attempts to update it.
  416. */
  417. function testUpdateFeed() {
  418. $remamining_fields = array('title', 'url', '');
  419. foreach ($remamining_fields as $same_field) {
  420. $feed = $this->createFeed();
  421. // Get new feed data array and modify newly created feed.
  422. $edit = $this->getFeedEditArray();
  423. $edit['refresh'] = 1800; // Change refresh value.
  424. if (isset($feed->{$same_field})) {
  425. $edit[$same_field] = $feed->{$same_field};
  426. }
  427. $this->drupalPost('admin/config/services/aggregator/edit/feed/' . $feed->fid, $edit, t('Save'));
  428. $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'])));
  429. // Check feed data.
  430. $this->assertEqual($this->getUrl(), url('admin/config/services/aggregator/', array('absolute' => TRUE)));
  431. $this->assertTrue($this->uniqueFeed($edit['title'], $edit['url']), 'The feed is unique.');
  432. // Check feed source.
  433. $this->drupalGet('aggregator/sources/' . $feed->fid);
  434. $this->assertResponse(200, 'Feed source exists.');
  435. $this->assertText($edit['title'], 'Page title');
  436. // Delete feed.
  437. $feed->title = $edit['title']; // Set correct title so deleteFeed() will work.
  438. $this->deleteFeed($feed);
  439. }
  440. }
  441. }
  442. /**
  443. * Tests functionality for removing feeds in the Aggregator module.
  444. */
  445. class RemoveFeedTestCase extends AggregatorTestCase {
  446. public static function getInfo() {
  447. return array(
  448. 'name' => 'Remove feed functionality',
  449. 'description' => 'Remove feed test.',
  450. 'group' => 'Aggregator'
  451. );
  452. }
  453. /**
  454. * Removes a feed and ensures that all of its services are removed.
  455. */
  456. function testRemoveFeed() {
  457. $feed = $this->createFeed();
  458. // Delete feed.
  459. $this->deleteFeed($feed);
  460. // Check feed source.
  461. $this->drupalGet('aggregator/sources/' . $feed->fid);
  462. $this->assertResponse(404, 'Deleted feed source does not exists.');
  463. // Check database for feed.
  464. $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $feed->title, ':url' => $feed->url))->fetchField();
  465. $this->assertFalse($result, 'Feed not found in database');
  466. }
  467. }
  468. /**
  469. * Tests functionality of updating a feed item in the Aggregator module.
  470. */
  471. class UpdateFeedItemTestCase extends AggregatorTestCase {
  472. public static function getInfo() {
  473. return array(
  474. 'name' => 'Update feed item functionality',
  475. 'description' => 'Update feed items from a feed.',
  476. 'group' => 'Aggregator'
  477. );
  478. }
  479. /**
  480. * Tests running "update items" from 'admin/config/services/aggregator' page.
  481. */
  482. function testUpdateFeedItem() {
  483. $this->createSampleNodes();
  484. // Create a feed and test updating feed items if possible.
  485. $feed = $this->createFeed();
  486. if (!empty($feed)) {
  487. $this->updateFeedItems($feed, $this->getDefaultFeedItemCount());
  488. $this->removeFeedItems($feed);
  489. }
  490. // Delete feed.
  491. $this->deleteFeed($feed);
  492. // Test updating feed items without valid timestamp information.
  493. $edit = array(
  494. 'title' => "Feed without publish timestamp",
  495. 'url' => $this->getRSS091Sample(),
  496. );
  497. $this->drupalGet($edit['url']);
  498. $this->assertResponse(array(200), format_string('URL !url is accessible', array('!url' => $edit['url'])));
  499. $this->drupalPost('admin/config/services/aggregator/add/feed', $edit, t('Save'));
  500. $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'])));
  501. $feed = db_query("SELECT * FROM {aggregator_feed} WHERE url = :url", array(':url' => $edit['url']))->fetchObject();
  502. aggregator_refresh($feed);
  503. $before = db_query('SELECT timestamp FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField();
  504. // Sleep for 3 second.
  505. sleep(3);
  506. db_update('aggregator_feed')
  507. ->condition('fid', $feed->fid)
  508. ->fields(array(
  509. 'checked' => 0,
  510. 'hash' => '',
  511. 'etag' => '',
  512. 'modified' => 0,
  513. ))
  514. ->execute();
  515. aggregator_refresh($feed);
  516. $after = db_query('SELECT timestamp FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField();
  517. $this->assertTrue($before === $after, format_string('Publish timestamp of feed item was not updated (!before === !after)', array('!before' => $before, '!after' => $after)));
  518. }
  519. }
  520. class RemoveFeedItemTestCase extends AggregatorTestCase {
  521. public static function getInfo() {
  522. return array(
  523. 'name' => 'Remove feed item functionality',
  524. 'description' => 'Remove feed items from a feed.',
  525. 'group' => 'Aggregator'
  526. );
  527. }
  528. /**
  529. * Tests running "remove items" from 'admin/config/services/aggregator' page.
  530. */
  531. function testRemoveFeedItem() {
  532. // Create a bunch of test feeds.
  533. $feed_urls = array();
  534. // No last-modified, no etag.
  535. $feed_urls[] = url('aggregator/test-feed', array('absolute' => TRUE));
  536. // Last-modified, but no etag.
  537. $feed_urls[] = url('aggregator/test-feed/1', array('absolute' => TRUE));
  538. // No Last-modified, but etag.
  539. $feed_urls[] = url('aggregator/test-feed/0/1', array('absolute' => TRUE));
  540. // Last-modified and etag.
  541. $feed_urls[] = url('aggregator/test-feed/1/1', array('absolute' => TRUE));
  542. foreach ($feed_urls as $feed_url) {
  543. $feed = $this->createFeed($feed_url);
  544. // Update and remove items two times in a row to make sure that removal
  545. // resets all 'modified' information (modified, etag, hash) and allows for
  546. // immediate update.
  547. $this->updateAndRemove($feed, 4);
  548. $this->updateAndRemove($feed, 4);
  549. $this->updateAndRemove($feed, 4);
  550. // Delete feed.
  551. $this->deleteFeed($feed);
  552. }
  553. }
  554. }
  555. /**
  556. * Tests categorization functionality in the Aggregator module.
  557. */
  558. class CategorizeFeedItemTestCase extends AggregatorTestCase {
  559. public static function getInfo() {
  560. return array(
  561. 'name' => 'Categorize feed item functionality',
  562. 'description' => 'Test feed item categorization.',
  563. 'group' => 'Aggregator'
  564. );
  565. }
  566. /**
  567. * Checks that children of a feed inherit a defined category.
  568. *
  569. * If a feed has a category, make sure that the children inherit that
  570. * categorization.
  571. */
  572. function testCategorizeFeedItem() {
  573. $this->createSampleNodes();
  574. // Simulate form submission on "admin/config/services/aggregator/add/category".
  575. $edit = array('title' => $this->randomName(10), 'description' => '');
  576. $this->drupalPost('admin/config/services/aggregator/add/category', $edit, t('Save'));
  577. $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'])));
  578. $category = db_query("SELECT * FROM {aggregator_category} WHERE title = :title", array(':title' => $edit['title']))->fetch();
  579. $this->assertTrue(!empty($category), 'The category found in database.');
  580. $link_path = 'aggregator/categories/' . $category->cid;
  581. $menu_link = db_query("SELECT * FROM {menu_links} WHERE link_path = :link_path", array(':link_path' => $link_path))->fetch();
  582. $this->assertTrue(!empty($menu_link), 'The menu link associated with the category found in database.');
  583. $feed = $this->createFeed();
  584. db_insert('aggregator_category_feed')
  585. ->fields(array(
  586. 'cid' => $category->cid,
  587. 'fid' => $feed->fid,
  588. ))
  589. ->execute();
  590. $this->updateFeedItems($feed, $this->getDefaultFeedItemCount());
  591. $this->getFeedCategories($feed);
  592. $this->assertTrue(!empty($feed->categories), 'The category found in the feed.');
  593. // For each category of a feed, ensure feed items have that category, too.
  594. if (!empty($feed->categories) && !empty($feed->items)) {
  595. foreach ($feed->categories as $category) {
  596. $categorized_count = db_select('aggregator_category_item')
  597. ->condition('iid', $feed->items, 'IN')
  598. ->countQuery()
  599. ->execute()
  600. ->fetchField();
  601. $this->assertEqual($feed->item_count, $categorized_count, 'Total items in feed equal to the total categorized feed items in database');
  602. }
  603. }
  604. // Delete feed.
  605. $this->deleteFeed($feed);
  606. }
  607. }
  608. /**
  609. * Tests importing feeds from OPML functionality for the Aggregator module.
  610. */
  611. class ImportOPMLTestCase extends AggregatorTestCase {
  612. public static function getInfo() {
  613. return array(
  614. 'name' => 'Import feeds from OPML functionality',
  615. 'description' => 'Test OPML import.',
  616. 'group' => 'Aggregator',
  617. );
  618. }
  619. /**
  620. * Opens OPML import form.
  621. */
  622. function openImportForm() {
  623. db_delete('aggregator_category')->execute();
  624. $category = $this->randomName(10);
  625. $cid = db_insert('aggregator_category')
  626. ->fields(array(
  627. 'title' => $category,
  628. 'description' => '',
  629. ))
  630. ->execute();
  631. $this->drupalGet('admin/config/services/aggregator/add/opml');
  632. $this->assertText('A single OPML document may contain a collection of many feeds.', 'Found OPML help text.');
  633. $this->assertField('files[upload]', 'Found file upload field.');
  634. $this->assertField('remote', 'Found Remote URL field.');
  635. $this->assertField('refresh', 'Found Refresh field.');
  636. $this->assertFieldByName("category[$cid]", $cid, 'Found category field.');
  637. }
  638. /**
  639. * Submits form filled with invalid fields.
  640. */
  641. function validateImportFormFields() {
  642. $before = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
  643. $edit = array();
  644. $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
  645. $this->assertRaw(t('You must <em>either</em> upload a file or enter a URL.'), 'Error if no fields are filled.');
  646. $path = $this->getEmptyOpml();
  647. $edit = array(
  648. 'files[upload]' => $path,
  649. 'remote' => file_create_url($path),
  650. );
  651. $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
  652. $this->assertRaw(t('You must <em>either</em> upload a file or enter a URL.'), 'Error if both fields are filled.');
  653. $edit = array('remote' => 'invalidUrl://empty');
  654. $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
  655. $this->assertText(t('This URL is not valid.'), 'Error if the URL is invalid.');
  656. $after = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
  657. $this->assertEqual($before, $after, 'No feeds were added during the three last form submissions.');
  658. }
  659. /**
  660. * Submits form with invalid, empty, and valid OPML files.
  661. */
  662. function submitImportForm() {
  663. $before = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
  664. $form['files[upload]'] = $this->getInvalidOpml();
  665. $this->drupalPost('admin/config/services/aggregator/add/opml', $form, t('Import'));
  666. $this->assertText(t('No new feed has been added.'), 'Attempting to upload invalid XML.');
  667. $edit = array('remote' => file_create_url($this->getEmptyOpml()));
  668. $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
  669. $this->assertText(t('No new feed has been added.'), 'Attempting to load empty OPML from remote URL.');
  670. $after = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
  671. $this->assertEqual($before, $after, 'No feeds were added during the two last form submissions.');
  672. db_delete('aggregator_feed')->execute();
  673. db_delete('aggregator_category')->execute();
  674. db_delete('aggregator_category_feed')->execute();
  675. $category = $this->randomName(10);
  676. db_insert('aggregator_category')
  677. ->fields(array(
  678. 'cid' => 1,
  679. 'title' => $category,
  680. 'description' => '',
  681. ))
  682. ->execute();
  683. $feeds[0] = $this->getFeedEditArray();
  684. $feeds[1] = $this->getFeedEditArray();
  685. $feeds[2] = $this->getFeedEditArray();
  686. $edit = array(
  687. 'files[upload]' => $this->getValidOpml($feeds),
  688. 'refresh' => '900',
  689. 'category[1]' => $category,
  690. );
  691. $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
  692. $this->assertRaw(t('A feed with the URL %url already exists.', array('%url' => $feeds[0]['url'])), 'Verifying that a duplicate URL was identified');
  693. $this->assertRaw(t('A feed named %title already exists.', array('%title' => $feeds[1]['title'])), 'Verifying that a duplicate title was identified');
  694. $after = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
  695. $this->assertEqual($after, 2, 'Verifying that two distinct feeds were added.');
  696. $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");
  697. $refresh = $category = TRUE;
  698. foreach ($feeds_from_db as $feed) {
  699. $title[$feed->url] = $feed->title;
  700. $url[$feed->title] = $feed->url;
  701. $category = $category && $feed->cid == 1;
  702. $refresh = $refresh && $feed->refresh == 900;
  703. }
  704. $this->assertEqual($title[$feeds[0]['url']], $feeds[0]['title'], 'First feed was added correctly.');
  705. $this->assertEqual($url[$feeds[1]['title']], $feeds[1]['url'], 'Second feed was added correctly.');
  706. $this->assertTrue($refresh, 'Refresh times are correct.');
  707. $this->assertTrue($category, 'Categories are correct.');
  708. }
  709. /**
  710. * Tests the import of an OPML file.
  711. */
  712. function testOPMLImport() {
  713. $this->openImportForm();
  714. $this->validateImportFormFields();
  715. $this->submitImportForm();
  716. }
  717. }
  718. /**
  719. * Tests functionality of the cron process in the Aggregator module.
  720. */
  721. class AggregatorCronTestCase extends AggregatorTestCase {
  722. public static function getInfo() {
  723. return array(
  724. 'name' => 'Update on cron functionality',
  725. 'description' => 'Update feeds on cron.',
  726. 'group' => 'Aggregator'
  727. );
  728. }
  729. /**
  730. * Adds feeds and updates them via cron process.
  731. */
  732. public function testCron() {
  733. // Create feed and test basic updating on cron.
  734. global $base_url;
  735. $key = variable_get('cron_key', 'drupal');
  736. $this->createSampleNodes();
  737. $feed = $this->createFeed();
  738. $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
  739. $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
  740. $this->removeFeedItems($feed);
  741. $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
  742. $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
  743. $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
  744. // Test feed locking when queued for update.
  745. $this->removeFeedItems($feed);
  746. db_update('aggregator_feed')
  747. ->condition('fid', $feed->fid)
  748. ->fields(array(
  749. 'queued' => REQUEST_TIME,
  750. ))
  751. ->execute();
  752. $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
  753. $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
  754. db_update('aggregator_feed')
  755. ->condition('fid', $feed->fid)
  756. ->fields(array(
  757. 'queued' => 0,
  758. ))
  759. ->execute();
  760. $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
  761. $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
  762. }
  763. }
  764. /**
  765. * Tests rendering functionality in the Aggregator module.
  766. */
  767. class AggregatorRenderingTestCase extends AggregatorTestCase {
  768. public static function getInfo() {
  769. return array(
  770. 'name' => 'Checks display of aggregator items',
  771. 'description' => 'Checks display of aggregator items on the page.',
  772. 'group' => 'Aggregator'
  773. );
  774. }
  775. /**
  776. * Adds a feed block to the page and checks its links.
  777. *
  778. * @todo Test the category block as well.
  779. */
  780. public function testBlockLinks() {
  781. // Create feed.
  782. $this->createSampleNodes();
  783. $feed = $this->createFeed();
  784. $this->updateFeedItems($feed, $this->getDefaultFeedItemCount());
  785. // Place block on page (@see block.test:moveBlockToRegion())
  786. // Need admin user to be able to access block admin.
  787. $this->admin_user = $this->drupalCreateUser(array(
  788. 'administer blocks',
  789. 'access administration pages',
  790. 'administer news feeds',
  791. 'access news feeds',
  792. ));
  793. $this->drupalLogin($this->admin_user);
  794. // Prepare to use the block admin form.
  795. $block = array(
  796. 'module' => 'aggregator',
  797. 'delta' => 'feed-' . $feed->fid,
  798. 'title' => $feed->title,
  799. );
  800. $region = 'footer';
  801. $edit = array();
  802. $edit['blocks[' . $block['module'] . '_' . $block['delta'] . '][region]'] = $region;
  803. // Check the feed block is available in the block list form.
  804. $this->drupalGet('admin/structure/block');
  805. $this->assertFieldByName('blocks[' . $block['module'] . '_' . $block['delta'] . '][region]', '', 'Aggregator feed block is available for positioning.');
  806. // Position it.
  807. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  808. $this->assertText(t('The block settings have been updated.'), format_string('Block successfully moved to %region_name region.', array( '%region_name' => $region)));
  809. // Confirm that the block is now being displayed on pages.
  810. $this->drupalGet('node');
  811. $this->assertText(t($block['title']), 'Feed block is displayed on the page.');
  812. // Find the expected read_more link.
  813. $href = 'aggregator/sources/' . $feed->fid;
  814. $links = $this->xpath('//a[@href = :href]', array(':href' => url($href)));
  815. $this->assert(isset($links[0]), format_string('Link to href %href found.', array('%href' => $href)));
  816. // Visit that page.
  817. $this->drupalGet($href);
  818. $correct_titles = $this->xpath('//h1[normalize-space(text())=:title]', array(':title' => $feed->title));
  819. $this->assertFalse(empty($correct_titles), 'Aggregator feed page is available and has the correct title.');
  820. // Set the number of news items to 0 to test that the block does not show
  821. // up.
  822. $feed->block = 0;
  823. aggregator_save_feed((array) $feed);
  824. // It is necessary to flush the cache after saving the number of items.
  825. drupal_flush_all_caches();
  826. // Check that the block is no longer displayed.
  827. $this->drupalGet('node');
  828. $this->assertNoText(t($block['title']), 'Feed block is not displayed on the page when number of items is set to 0.');
  829. }
  830. /**
  831. * Creates a feed and checks that feed's page.
  832. */
  833. public function testFeedPage() {
  834. // Increase the number of items published in the rss.xml feed so we have
  835. // enough articles to test paging.
  836. variable_set('feed_default_items', 30);
  837. // Create a feed with 30 items.
  838. $this->createSampleNodes(30);
  839. $feed = $this->createFeed();
  840. $this->updateFeedItems($feed, 30);
  841. // Check for the presence of a pager.
  842. $this->drupalGet('aggregator/sources/' . $feed->fid);
  843. $elements = $this->xpath("//ul[@class=:class]", array(':class' => 'pager'));
  844. $this->assertTrue(!empty($elements), 'Individual source page contains a pager.');
  845. // Reset the number of items in rss.xml to the default value.
  846. variable_set('feed_default_items', 10);
  847. }
  848. }
  849. /**
  850. * Tests feed parsing in the Aggregator module.
  851. */
  852. class FeedParserTestCase extends AggregatorTestCase {
  853. public static function getInfo() {
  854. return array(
  855. 'name' => 'Feed parser functionality',
  856. 'description' => 'Test the built-in feed parser with valid feed samples.',
  857. 'group' => 'Aggregator',
  858. );
  859. }
  860. function setUp() {
  861. parent::setUp();
  862. // Do not remove old aggregator items during these tests, since our sample
  863. // feeds have hardcoded dates in them (which may be expired when this test
  864. // is run).
  865. variable_set('aggregator_clear', AGGREGATOR_CLEAR_NEVER);
  866. }
  867. /**
  868. * Tests a feed that uses the RSS 0.91 format.
  869. */
  870. function testRSS091Sample() {
  871. $feed = $this->createFeed($this->getRSS091Sample());
  872. aggregator_refresh($feed);
  873. $this->drupalGet('aggregator/sources/' . $feed->fid);
  874. $this->assertResponse(200, format_string('Feed %name exists.', array('%name' => $feed->title)));
  875. $this->assertText('First example feed item title');
  876. $this->assertLinkByHref('http://example.com/example-turns-one');
  877. $this->assertText('First example feed item description.');
  878. // Several additional items that include elements over 255 characters.
  879. $this->assertRaw("Second example feed item title.");
  880. $this->assertText('Long link feed item title');
  881. $this->assertText('Long link feed item description');
  882. $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');
  883. $this->assertText('Long author feed item title');
  884. $this->assertText('Long author feed item description');
  885. $this->assertLinkByHref('http://example.com/long/author');
  886. }
  887. /**
  888. * Tests a feed that uses the Atom format.
  889. */
  890. function testAtomSample() {
  891. $feed = $this->createFeed($this->getAtomSample());
  892. aggregator_refresh($feed);
  893. $this->drupalGet('aggregator/sources/' . $feed->fid);
  894. $this->assertResponse(200, format_string('Feed %name exists.', array('%name' => $feed->title)));
  895. $this->assertText('Atom-Powered Robots Run Amok');
  896. $this->assertLinkByHref('http://example.org/2003/12/13/atom03');
  897. $this->assertText('Some text.');
  898. $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.');
  899. }
  900. /**
  901. * Tests a feed that uses HTML entities in item titles.
  902. */
  903. function testHtmlEntitiesSample() {
  904. $feed = $this->createFeed($this->getHtmlEntitiesSample());
  905. aggregator_refresh($feed);
  906. $this->drupalGet('aggregator/sources/' . $feed->fid);
  907. $this->assertResponse(200, format_string('Feed %name exists.', array('%name' => $feed->title)));
  908. $this->assertRaw("Quote&quot; Amp&amp;");
  909. }
  910. }