AggregatorTestBase.php 11.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Definition of Drupal\aggregator\Tests\AggregatorTestBase.
 */

namespace Drupal\aggregator\Tests;

10
use Drupal\aggregator\Entity\Feed;
11
use Drupal\Core\Language\Language;
12
use Drupal\simpletest\WebTestBase;
13
use Drupal\aggregator\FeedInterface;
14 15

/**
16
 * Defines a base class for testing the Aggregator module.
17
 */
18
abstract class AggregatorTestBase extends WebTestBase {
19 20 21 22 23 24

  /**
   * Modules to enable.
   *
   * @var array
   */
25
  public static $modules = array('node', 'aggregator', 'aggregator_test', 'views');
26

27
  function setUp() {
28
    parent::setUp();
29 30 31 32 33 34

    // Create an Article node type.
    if ($this->profile != 'standard') {
      $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
    }

35
    $web_user = $this->drupalCreateUser(array('access administration pages', 'administer news feeds', 'access news feeds', 'create article content'));
36 37 38 39
    $this->drupalLogin($web_user);
  }

  /**
40 41
   * Creates an aggregator feed.
   *
42
   * This method simulates the form submission on path aggregator/sources/add.
43 44
   *
   * @param $feed_url
45 46
   *   (optional) If given, feed will be created with this URL, otherwise
   *   /rss.xml will be used. Defaults to NULL.
47 48
   * @param array $edit
   *   Array with additional form fields.
49
   *
50
   * @return \Drupal\aggregator\FeedInterface
51 52 53 54
   *   Full feed object if possible.
   *
   * @see getFeedEditArray()
   */
55 56
  function createFeed($feed_url = NULL, array $edit = array()) {
    $edit = $this->getFeedEditArray($feed_url, $edit);
57
    $this->drupalPostForm('aggregator/sources/add', $edit, t('Save'));
58
    $this->assertRaw(t('The feed %name has been added.', array('%name' => $edit['title[0][value]'])), format_string('The feed !name has been added.', array('!name' => $edit['title[0][value]'])));
59

60
    $fid = db_query("SELECT fid FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $edit['title[0][value]'], ':url' => $edit['url[0][value]']))->fetchField();
61
    $this->assertTrue(!empty($fid), 'The feed found in database.');
62
    return Feed::load($fid);
63 64 65
  }

  /**
66
   * Deletes an aggregator feed.
67
   *
68
   * @param \Drupal\aggregator\FeedInterface $feed
69 70
   *   Feed object representing the feed.
   */
71
  function deleteFeed(FeedInterface $feed) {
72
    $this->drupalPostForm('aggregator/sources/' . $feed->id() . '/delete', array(), t('Delete'));
73
    $this->assertRaw(t('The feed %title has been deleted.', array('%title' => $feed->label())), 'Feed deleted successfully.');
74 75 76
  }

  /**
77
   * Returns a randomly generated feed edit array.
78 79
   *
   * @param $feed_url
80 81
   *   (optional) If given, feed will be created with this URL, otherwise
   *   /rss.xml will be used. Defaults to NULL.
82 83
   * @param array $edit
   *   Array with additional form fields.
84
   *
85 86 87
   * @return
   *   A feed array.
   */
88
  function getFeedEditArray($feed_url = NULL, array $edit = array()) {
89 90 91 92 93 94 95
    $feed_name = $this->randomName(10);
    if (!$feed_url) {
      $feed_url = url('rss.xml', array(
        'query' => array('feed' => $feed_name),
        'absolute' => TRUE,
      ));
    }
96
    $edit += array(
97 98
      'title[0][value]' => $feed_name,
      'url[0][value]' => $feed_url,
99 100 101 102 103
      'refresh' => '900',
    );
    return $edit;
  }

104 105 106 107 108 109 110 111 112
  /**
   * Returns a randomly generated feed edit object.
   *
   * @param string $feed_url
   *   (optional) If given, feed will be created with this URL, otherwise
   *   /rss.xml will be used. Defaults to NULL.
   * @param array $values
   *   (optional) Default values to initialize object properties with.
   *
113
   * @return \Drupal\aggregator\FeedInterface
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
   *   A feed object.
   */
  function getFeedEditObject($feed_url = NULL, array $values = array()) {
    $feed_name = $this->randomName(10);
    if (!$feed_url) {
      $feed_url = url('rss.xml', array(
        'query' => array('feed' => $feed_name),
        'absolute' => TRUE,
      ));
    }
    $values += array(
      'title' => $feed_name,
      'url' => $feed_url,
      'refresh' => '900',
    );
    return entity_create('aggregator_feed', $values);
  }

132
  /**
133
   * Returns the count of the randomly created feed array.
134 135 136 137 138 139
   *
   * @return
   *   Number of feed items on default feed created by createFeed().
   */
  function getDefaultFeedItemCount() {
    // Our tests are based off of rss.xml, so let's find out how many elements should be related.
140
    $feed_count = db_query_range('SELECT COUNT(DISTINCT nid) FROM {node_field_data} n WHERE n.promote = 1 AND n.status = 1', 0, $this->container->get('config.factory')->get('system.rss')->get('items.limit'))->fetchField();
141 142 143 144
    return $feed_count > 10 ? 10 : $feed_count;
  }

  /**
145 146 147 148
   * Updates the feed items.
   *
   * This method simulates a click to
   * admin/config/services/aggregator/update/$fid.
149
   *
150
   * @param \Drupal\aggregator\FeedInterface $feed
151
   *   Feed object representing the feed.
152 153
   * @param int|null $expected_count
   *   Expected number of feed items. If omitted no check will happen.
154
   */
155
  function updateFeedItems(FeedInterface $feed, $expected_count = NULL) {
156
    // First, let's ensure we can get to the rss xml.
157 158
    $this->drupalGet($feed->getUrl());
    $this->assertResponse(200, format_string('!url is reachable.', array('!url' => $feed->getUrl())));
159 160

    // Attempt to access the update link directly without an access token.
161
    $this->drupalGet('admin/config/services/aggregator/update/' . $feed->id());
162 163 164 165
    $this->assertResponse(403);

    // Refresh the feed (simulated link click).
    $this->drupalGet('admin/config/services/aggregator');
166
    $this->clickLink('Update items');
167 168

    // Ensure we have the right number of items.
169
    $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()));
170 171 172 173
    $feed->items = array();
    foreach ($result as $item) {
      $feed->items[] = $item->iid;
    }
174 175 176 177 178

    if ($expected_count !== NULL) {
      $feed->item_count = count($feed->items);
      $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)));
    }
179 180 181
  }

  /**
182
   * Confirms an item removal from a feed.
183
   *
184
   * @param \Drupal\aggregator\FeedInterface $feed
185 186
   *   Feed object representing the feed.
   */
187 188 189
  function deleteFeedItems(FeedInterface $feed) {
    $this->drupalPostForm('admin/config/services/aggregator/delete/' . $feed->id(), array(), t('Delete items'));
    $this->assertRaw(t('The news items from %title have been deleted.', array('%title' => $feed->label())), 'Feed items deleted.');
190 191 192
  }

  /**
193
   * Adds and deletes feed items and ensure that the count is zero.
194
   *
195
   * @param \Drupal\aggregator\FeedInterface $feed
196
   *   Feed object representing the feed.
197
   * @param int $expected_count
198 199
   *   Expected number of feed items.
   */
200
  function updateAndDelete(FeedInterface $feed, $expected_count) {
201
    $this->updateFeedItems($feed, $expected_count);
202
    $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField();
203
    $this->assertTrue($count);
204
    $this->deleteFeedItems($feed);
205
    $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField();
206 207 208 209
    $this->assertTrue($count == 0);
  }

  /**
210
   * Checks whether the feed name and URL are unique.
211 212 213 214 215
   *
   * @param $feed_name
   *   String containing the feed name to check.
   * @param $feed_url
   *   String containing the feed url to check.
216
   *
217 218 219 220 221 222 223 224 225
   * @return
   *   TRUE if feed is unique.
   */
  function uniqueFeed($feed_name, $feed_url) {
    $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $feed_name, ':url' => $feed_url))->fetchField();
    return (1 == $result);
  }

  /**
226
   * Creates a valid OPML file from an array of feeds.
227 228 229
   *
   * @param $feeds
   *   An array of feeds.
230
   *
231 232 233 234 235 236
   * @return
   *   Path to valid OPML file.
   */
  function getValidOpml($feeds) {
    // Properly escape URLs so that XML parsers don't choke on them.
    foreach ($feeds as &$feed) {
237
      $feed['url[0][value]'] = htmlspecialchars($feed['url[0][value]']);
238 239 240 241 242 243 244 245 246
    }
    /**
     * Does not have an XML declaration, must pass the parser.
     */
    $opml = <<<EOF
<opml version="1.0">
  <head></head>
  <body>
    <!-- First feed to be imported. -->
247
    <outline text="{$feeds[0]['title[0][value]']}" xmlurl="{$feeds[0]['url[0][value]']}" />
248 249

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

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

    <!-- Test that feeds are only added with required attributes. -->
257 258
    <outline text="{$feeds[2]['title[0][value]']}" />
    <outline xmlurl="{$feeds[2]['url[0][value]']}" />
259 260 261 262 263 264 265 266 267
  </body>
</opml>
EOF;

    $path = 'public://valid-opml.xml';
    return file_unmanaged_save_data($opml, $path);
  }

  /**
268
   * Creates an invalid OPML file.
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
   *
   * @return
   *   Path to invalid OPML file.
   */
  function getInvalidOpml() {
    $opml = <<<EOF
<opml>
  <invalid>
</opml>
EOF;

    $path = 'public://invalid-opml.xml';
    return file_unmanaged_save_data($opml, $path);
  }

  /**
285
   * Creates a valid but empty OPML file.
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
   *
   * @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 = 'public://empty-opml.xml';
    return file_unmanaged_save_data($opml, $path);
  }

  function getRSS091Sample() {
307
    return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_rss091.xml';
308 309 310 311 312
  }

  function getAtomSample() {
    // The content of this sample ATOM feed is based directly off of the
    // example provided in RFC 4287.
313
    return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_atom.xml';
314 315 316
  }

  function getHtmlEntitiesSample() {
317
    return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_title_entities.xml';
318 319 320 321 322 323
  }

  /**
   * Creates sample article nodes.
   *
   * @param $count
324
   *   (optional) The number of nodes to generate. Defaults to five.
325 326 327 328 329
   */
  function createSampleNodes($count = 5) {
    // Post $count article nodes.
    for ($i = 0; $i < $count; $i++) {
      $edit = array();
330
      $edit['title[0][value]'] = $this->randomName();
331
      $edit['body[0][value]'] = $this->randomName();
332
      $this->drupalPostForm('node/add/article', $edit, t('Save'));
333 334
    }
  }
335 336 337 338 339

  /**
   * Enable the plugins coming with aggregator_test module.
   */
  function enableTestPlugins() {
340
    $this->container->get('config.factory')->get('aggregator.settings')
341 342 343 344 345 346 347 348
      ->set('fetcher', 'aggregator_test_fetcher')
      ->set('parser', 'aggregator_test_parser')
      ->set('processors', array(
        'aggregator_test_processor' => 'aggregator_test_processor',
        'aggregator' => 'aggregator'
      ))
      ->save();
  }
349
}