Skip to content
aggregator.test 16.9 KiB
Newer Older
<?php
// $Id$

class AggregatorTestCase extends DrupalWebTestCase {
  private static $prefix = 'simpletest_aggregator_';

  /**
   * Implementation of setUp().
   */
  function setUp() {
    parent::setUp('aggregator');
    $web_user = $this->drupalCreateUser(array('administer news feeds', 'access news feeds'));
    $this->drupalLogin($web_user);
  }

  /**
   * Create an aggregator feed (simulate form submission on admin/content/aggregator/add/feed).
   *
   * @return $feed Full feed object if possible.
   */
  function createFeed() {
    $edit = $this->getFeedEditArray();
    $this->drupalPost('admin/content/aggregator/add/feed', $edit, t('Save'));
    $this->assertRaw(t('The feed %name has been added.', array('%name' => $edit['title'])), t('The feed !name has been added.', array('!name' => $edit['title'])));

    $feed = db_fetch_object(db_query("SELECT *  FROM {aggregator_feed} WHERE title = '%s' AND url='%s'", $edit['title'], $edit['url']));
    $this->assertTrue(!empty($feed), t('The feed found in database.'));
    return $feed;
  }

  /**
   * Delete an aggregator feed.
   *
   * @param object $feed Feed object representing the feed.
   */
  function deleteFeed($feed) {
    $this->drupalPost('admin/content/aggregator/edit/feed/' . $feed->fid, array(), t('Delete'));
    $this->assertRaw(t('The feed %title has been deleted.', array('%title' => $feed->title)), t('Feed deleted successfully.'));
  }

  /**
   * Return a randomly generated feed edit array.
   *
   * @return array Feed array.
   */
  function getFeedEditArray() {
    $feed_name = $this->randomName(10, self::$prefix);
    $feed_url = url(NULL, array('absolute' => TRUE)) . 'rss.xml?feed=' . $feed_name;
    $edit = array(
      'title' => $feed_name,
      'url' => $feed_url,
      'refresh' => '900',
    );
    return $edit;
  }

  /**
   * Update feed items (simulate click to admin/content/aggregator/update/$fid).
   *
   * @param object $feed Feed object representing the feed.
   */
  function updateFeedItems(&$feed) {
    // First, let's ensure we can get to the rss xml.
    $this->drupalGet('rss.xml');
    $this->assertResponse(200, t('rss.xml is reachable.'));

    // Our tests are based off of rss.xml, so let's find out how many elements should be related.
    $feed_count = db_result(db_query_range(db_rewrite_sql('SELECT COUNT(*) FROM {node} n WHERE n.promote = 1 AND n.status = 1'), 0, variable_get('feed_default_items', 10)));
    $feed_count = $feed_count > 10 ? 10 : $feed_count;

    // Refresh the feed (simulated link click).
    $this->drupalGet('admin/content/aggregator/update/' . $feed->fid);
    // Ensure we have the right number of items.
    $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = %d', $feed->fid);
    $items = array();
    $feed->items = array();
    while ($item = db_fetch_object($result)) {
      $feed->items[] = $item->iid;
    }
    $feed->item_count = count($feed->items);
    $this->assertEqual($feed_count, $feed->item_count, t('Total items in feed equal to the total items in database (!val1 != !val2)', array('!val1' => $feed_count, '!val2' => $feed->item_count)));
  }

  /**
   * Confirm item removal from a feed.
   *
   * @param object $feed Feed object representing the feed.
   */
  function removeFeedItems($feed) {
    $this->drupalPost('admin/content/aggregator/remove/' . $feed->fid, array(), t('Remove items'));
    $this->assertRaw(t('The news items from %title have been removed.', array('%title' => $feed->title)), t('Feed items removed.'));
  }

  /**
   * Pull feed categories from aggregator_category_feed table.
   *
   * @param object $feed Feed object representing the feed.
   */
  function getFeedCategories($feed) {
    // add the categories to the feed so we can use them
    $result = db_query('SELECT cid FROM {aggregator_category_feed} WHERE fid = %d', $feed->fid);
    while ($category = db_fetch_object($result)) {
      $feed->categories[] = $category->cid;
    }
  }

  /**
   * Check if the feed name and url is unique.
   *
   * @param string $feed_name Feed name to check.
   * @param string $feed_url Feed url to check.
   * @return boolean Feed is unique.
   */
  function uniqueFeed($feed_name, $feed_url) {
    $result = db_result(db_query("SELECT count(*) FROM {aggregator_feed} WHERE title = '%s' AND url='%s'", $feed_name, $feed_url));
    return (1 == $result);
  }

  /**
   * Create a valid OPML file from an array of feeds.
   *
   * @param $feeds
   *   An array of feeds.
   * @return
   *   Path to valid OPML file.
   */
  function getValidOpml($feeds) {
    /**
     * Does not have an XML declaration, must pass the parser.
     */
    $opml = <<<EOF
<opml version="1.0">
  <head></head>
  <body>
    <!-- First feed to be imported. -->
    <outline text="{$feeds[0]['title']}" xmlurl="{$feeds[0]['url']}" />

    <!-- Second feed. Test string delimitation and attribute order. -->
    <outline xmlurl='{$feeds[1]['url']}' text='{$feeds[1]['title']}'/>

    <!-- Test for duplicate URL and title. -->
    <outline xmlurl="{$feeds[0]['url']}" text="Duplicate URL"/>
    <outline xmlurl="http://duplicate.title" text="{$feeds[1]['title']}"/>

    <!-- Test that feeds are only added with required attributes. -->
    <outline text="{$feeds[2]['title']}" />
    <outline xmlurl="{$feeds[2]['url']}" />
  </body>
</opml>
EOF;

    $path = file_directory_path() . '/valid-opml.xml';
    file_save_data($opml, $path);
    return $path;
  }

  /**
   * Create an invalid OPML file.
   *
   * @return
   *   Path to invalid OPML file.
   */
  function getInvalidOpml() {
    $opml = <<<EOF
<opml>
  <invalid>
</opml>
EOF;

    $path = file_directory_path() . '/invalid-opml.xml';
    file_save_data($opml, $path);
    return $path;
  }

  /**
   * Create a valid but empty OPML file.
   *
   * @return
   *   Path to empty OPML file.
   */
  function getEmptyOpml() {
    $opml = <<<EOF
<?xml version="1.0" encoding="utf-8"?>
<opml version="1.0">
  <head></head>
  <body>
    <outline text="Sample text" />
    <outline text="Sample text" url="Sample URL" />
  </body>
</opml>
EOF;

    $path = file_directory_path() . '/empty-opml.xml';
    file_save_data($opml, $path);
    return $path;
  }
}

class AddFeedTestCase extends AggregatorTestCase {
  /**
   * Implementation of getInfo().
   */
  function getInfo() {
    return array(
      'name' => t('Add feed functionality'),
      'description' => t('Add feed test.'),
      'group' => t('Aggregator')
    );
  }

  /**
   * Create a feed, ensure that it is unique, check the source, and delete the feed.
   */
  function testAddFeed() {
    $feed = $this->createFeed();

    // Check feed data.
    $this->assertEqual($this->getUrl(), url('admin/content/aggregator/add/feed', array('absolute' => TRUE)), t('Directed to correct url.'));
    $this->assertTrue($this->uniqueFeed($feed->title, $feed->url), t('The feed is unique.'));

    // Check feed source.
    $this->drupalGet('aggregator/sources/' . $feed->fid);
    $this->assertResponse(200, t('Feed source exists.'));
    $this->assertText($feed->title, t('Page title'));

    // Delete feed.
    $this->deleteFeed($feed);
  }
}

class UpdateFeedTestCase extends AggregatorTestCase {
  /**
   * Implementation of getInfo().
   */
  function getInfo() {
    return array(
      'name' => t('Update feed functionality'),
      'description' => t('Update feed test.'),
      'group' => t('Aggregator')
    );
  }

  /**
   * Create a feed and attempt to update it.
   */
  function testUpdateFeed() {
    $feed = $this->createFeed();

    // Get new feed data array and modify newly created feed.
    $edit = $this->getFeedEditArray();
    $edit['refresh'] =  1800; // Change refresh value.
    $this->drupalPost('admin/content/aggregator/edit/feed/' . $feed->fid, $edit, t('Save'));
    $this->assertRaw(t('The feed %name has been updated.', array('%name' => $edit['title'])), t('The feed %name has been updated.', array('%name' => $edit['title'])));

    // Check feed data.
    $this->assertEqual($this->getUrl(), url('admin/content/aggregator/', array('absolute' => TRUE)));
    $this->assertTrue($this->uniqueFeed($edit['title'], $edit['url']), t('The feed is unique.'));

    // Check feed source.
    $this->drupalGet('aggregator/sources/' . $feed->fid);
    $this->assertResponse(200, t('Feed source exists.'));
    $this->assertText($edit['title'], t('Page title'));

    // Delete feed.
    $feed->title = $edit['title']; // Set correct title so deleteFeed() will work.
    $this->deleteFeed($feed);
  }
}

class RemoveFeedTestCase extends AggregatorTestCase {
  /**
   * Implementation of getInfo().
   */
  function getInfo() {
    return array(
      'name' => t('Remove feed functionality'),
      'description' => t('Remove feed test.'),
      'group' => t('Aggregator')
    );
  }

  /**
   * Remove a feed and ensure that all it services are removed.
   */
  function testRemoveFeed() {
    $feed = $this->createFeed();

    // Delete feed.
    $this->deleteFeed($feed);

    // Check feed source.
    $this->drupalGet('aggregator/sources/' . $feed->fid);
    $this->assertResponse(404, t('Deleted feed source does not exists.'));

    // Check database for feed.
    $result = db_result(db_query("SELECT count(*) FROM {aggregator_feed} WHERE title = '%s' AND url='%s'", $feed->title, $feed->url));
    $this->assertFalse($result, t('Feed not found in database'));
  }
}

class UpdateFeedItemTestCase extends AggregatorTestCase {
  /**
   * Implementation of getInfo().
   */
  function getInfo() {
    return array(
      'name' => t('Update feed item functionality'),
      'description' => t('Update feed items from a feed.'),
      'group' => t('Aggregator')
    );
  }

  /**
   * Test running "update items" from the 'admin/content/aggregator' page.
   */
  function testUpdateFeedItem() {
    // Create a feed and test updating feed items if possible.
    $feed = $this->createFeed();
    if (!empty($feed)) {
      $this->updateFeedItems($feed);
      $this->removeFeedItems($feed);
    }

    // Delete feed.
    $this->deleteFeed($feed);
  }
}

class RemoveFeedItemTestCase extends AggregatorTestCase {
  /**
   * Implementation of getInfo().
   */
  function getInfo() {
    return array(
      'name' => t('Remove feed item functionality'),
      'description' => t('Remove feed items from a feed.'),
      'group' => t('Aggregator')
    );
  }

  /**
   * Test running "remove items" from the 'admin/content/aggregator' page.
   */
  function testRemoveFeedItem() {
    $feed = $this->createFeed();

    // Add and remove feed items and ensure that the count is zero.
    $this->updateFeedItems($feed);
    $this->removeFeedItems($feed);
    $count = db_result(db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = %d', $feed->fid));
    $this->assertTrue($count == 0);

    // Delete feed.
    $this->deleteFeed($feed);
  }
}

class CategorizeFeedItemTestCase extends AggregatorTestCase {
  /**
   * Implementation of getInfo().
   */
  function getInfo() {
    return array(
      'name' => t('Categorize feed item functionality'),
      'description' => t('Test feed item categorization.'),
      'group' => t('Aggregator')
    );
  }

  /**
   * If a feed has a category, make sure that the children inherit that
   * categorization.
   */
  function testCategorizeFeedItem() {
    // TODO: Need to add categories to the feed on creation.
    $feed = $this->createFeed();
    $this->updateFeedItems($feed);
    $this->getFeedCategories($feed);

    // For each category of a feed, ensure feed items have that category, too.
    if (!empty($feed->categories) && !empty($feed->items)) {
      foreach ($feed->categories as $category) {
        $items_str = implode(', ', $feed->items);
        $categorized_count = db_result(db_query('SELECT COUNT(*) FROM {aggregator_category_item} WHERE iid IN (' . $items_str . ')'));
        $this->assertEqual($feed->item_count, $categorized_count, t('Total items in feed equal to the total categorized feed items in database'));
      }
    }

    // Delete feed.
    $this->deleteFeed($feed);
  }
}

class ImportOPMLTestCase extends AggregatorTestCase {
  private static $prefix = 'simpletest_aggregator_';

  /**
   * Implementation of getInfo().
   */
  function getInfo() {
    return array(
      'name' => t('Import feeds from OPML functionality'),
      'description' => t('Test OPML import.'),
      'group' => t('Aggregator'),
    );
  }

  /**
   * Open OPML import form.
   */
  function openImportForm() {
    db_query('TRUNCATE {aggregator_category}');

    $category = $this->randomName(10, self::$prefix);
    db_query("INSERT INTO {aggregator_category} (cid, title, description) VALUES (%d, '%s', '%s')", 1, $category, '');

    $this->drupalGet('admin/content/aggregator/add/opml');
    $this->assertText('A single OPML document may contain a collection of many feeds.', t('Looking for help text.'));
    $this->assertFieldByName('files[upload]', '', t('Looking for file upload field.'));
    $this->assertFieldByName('remote', '', t('Looking for remote URL field.'));
    $this->assertFieldByName('refresh', '', t('Looking for refresh field.'));
    $this->assertFieldByName('category[1]', '1', t('Looking for category field.'));
  }

  /**
   * Submit form filled with invalid fields.
   */
  function validateImportFormFields() {
    $before = db_result(db_query('SELECT COUNT(*) FROM {aggregator_feed}'));

    $form = array();
    $this->drupalPost('admin/content/aggregator/add/opml', $form, t('Import'));
    $this->assertRaw(t('You must <em>either</em> upload a file or enter a URL.'), t('Error if no fields are filled.'));

    $path = $this->getEmptyOpml();
    $form = array(
      'files[upload]' => $path,
      'remote' => file_create_url($path),
    );
    $this->drupalPost('admin/content/aggregator/add/opml', $form, t('Import'));
    $this->assertRaw(t('You must <em>either</em> upload a file or enter a URL.'), t('Error if both fields are filled.'));

    $form = array('remote' => 'invalidUrl://empty');
    $this->drupalPost('admin/content/aggregator/add/opml', $form, t('Import'));
    $this->assertText(t('This URL is not valid.'), t('Error if the URL is invalid.'));

    $after = db_result(db_query('SELECT COUNT(*) FROM {aggregator_feed}'));
    $this->assertEqual($before, $after, t('No feeds were added during the three last form submissions.'));
  }

  /**
   * Submit form with invalid, empty and valid OPML files.
   */
  function submitImportForm() {
    $before = db_result(db_query('SELECT COUNT(*) FROM {aggregator_feed}'));

    $form['files[upload]'] = $this->getInvalidOpml();
    $this->drupalPost('admin/content/aggregator/add/opml', $form, t('Import'));
    $this->assertText(t('No new feed has been added.'), t('Attempting to upload invalid XML.'));

    $form = array('remote' => file_create_url($this->getEmptyOpml()));
    $this->drupalPost('admin/content/aggregator/add/opml', $form, t('Import'));
    $this->assertText(t('No new feed has been added.'), t('Attempting to load empty OPML from remote URL.'));

    $after = db_result(db_query('SELECT COUNT(*) FROM {aggregator_feed}'));
    $this->assertEqual($before, $after, t('No feeds were added during the two last form submissions.'));

    db_query('TRUNCATE {aggregator_feed}');
    db_query('TRUNCATE {aggregator_category}');
    db_query('TRUNCATE {aggregator_category_feed}');

    $category = $this->randomName(10, self::$prefix);
    db_query("INSERT INTO {aggregator_category} (cid, title, description) VALUES (%d, '%s', '%s')", 1, $category, '');

    $feeds[0] = $this->getFeedEditArray();
    $feeds[1] = $this->getFeedEditArray();
    $feeds[2] = $this->getFeedEditArray();
    $form = array(
      'files[upload]' => $this->getValidOpml($feeds),
      'refresh'       => '900',
      'category[1]'   => $category,
    );
    $this->drupalPost('admin/content/aggregator/add/opml', $form, t('Import'));
    $this->assertRaw(t('A feed with the URL %url already exists.', array('%url' => $feeds[0]['url'])), t('Verifying that a duplicate URL was identified'));
    $this->assertRaw(t('A feed named %title already exists.', array('%title' => $feeds[1]['title'])), t('Verifying that a duplicate title was identified'));

    $after = db_result(db_query('SELECT COUNT(*) FROM {aggregator_feed}'));
    $this->assertEqual($after, 2, t('Verifying that two distinct feeds were added.'));

    $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");
    $refresh = $category = TRUE;
    while ($feed = db_fetch_array($feeds_from_db)) {
      $title[$feed['url']] = $feed['title'];
      $url[$feed['title']] = $feed['url'];
      $category = $category && $feed['cid'] == 1;
      $refresh = $refresh && $feed['refresh'] == 900;
    }

    $this->assertEqual($title[$feeds[0]['url']], $feeds[0]['title'], t('First feed was added correctly.'));
    $this->assertEqual($url[$feeds[1]['title']], $feeds[1]['url'], t('Second feed was added correctly.'));
    $this->assertTrue($refresh, t('Refresh times are correct.'));
    $this->assertTrue($category, t('Categories are correct.'));
  }

  function testOPMLImport() {
    $this->openImportForm();
    $this->validateImportFormFields();
    $this->submitImportForm();
  }
}