aggregator.test 37 KB

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