AggregatorTestBase.php 12.1 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\aggregator\Tests;

5
use Drupal\aggregator\Entity\Feed;
6
use Drupal\Component\Utility\Html;
7
use Drupal\simpletest\WebTestBase;
8
use Drupal\aggregator\FeedInterface;
9 10

/**
11
 * Defines a base class for testing the Aggregator module.
12 13 14
 *
 * @deprecated Scheduled for removal in Drupal 9.0.0.
 *   Use \Drupal\Tests\aggregator\Functional\AggregatorTestBase instead.
15
 */
16
abstract class AggregatorTestBase extends WebTestBase {
17

18 19 20 21 22 23 24
  /**
   * A user with permission to administer feeds and create content.
   *
   * @var \Drupal\user\Entity\User
   */
  protected $adminUser;

25
  /**
26
   * Modules to install.
27 28 29
   *
   * @var array
   */
30
  public static $modules = ['block', 'node', 'aggregator', 'aggregator_test', 'views'];
31

32 33 34
  /**
   * {@inheritdoc}
   */
35
  protected function setUp() {
36
    parent::setUp();
37 38 39

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

43
    $this->adminUser = $this->drupalCreateUser(['access administration pages', 'administer news feeds', 'access news feeds', 'create article content']);
44
    $this->drupalLogin($this->adminUser);
45
    $this->drupalPlaceBlock('local_tasks_block');
46 47 48
  }

  /**
49 50
   * Creates an aggregator feed.
   *
51
   * This method simulates the form submission on path aggregator/sources/add.
52
   *
53
   * @param string $feed_url
54 55
   *   (optional) If given, feed will be created with this URL, otherwise
   *   /rss.xml will be used. Defaults to NULL.
56 57
   * @param array $edit
   *   Array with additional form fields.
58
   *
59
   * @return \Drupal\aggregator\FeedInterface
60 61 62 63
   *   Full feed object if possible.
   *
   * @see getFeedEditArray()
   */
64
  public function createFeed($feed_url = NULL, array $edit = []) {
65
    $edit = $this->getFeedEditArray($feed_url, $edit);
66
    $this->drupalPostForm('aggregator/sources/add', $edit, t('Save'));
67
    $this->assertText(t('The feed @name has been added.', ['@name' => $edit['title[0][value]']]), format_string('The feed @name has been added.', ['@name' => $edit['title[0][value]']]));
68 69

    // Verify that the creation message contains a link to a feed.
70
    $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'aggregator/sources/']);
71
    $this->assert(isset($view_link), 'The message area contains a link to a feed');
72

73
    $fid = db_query("SELECT fid FROM {aggregator_feed} WHERE title = :title AND url = :url", [':title' => $edit['title[0][value]'], ':url' => $edit['url[0][value]']])->fetchField();
74
    $this->assertTrue(!empty($fid), 'The feed found in database.');
75
    return Feed::load($fid);
76 77 78
  }

  /**
79
   * Deletes an aggregator feed.
80
   *
81
   * @param \Drupal\aggregator\FeedInterface $feed
82 83
   *   Feed object representing the feed.
   */
84
  public function deleteFeed(FeedInterface $feed) {
85 86
    $this->drupalPostForm('aggregator/sources/' . $feed->id() . '/delete', [], t('Delete'));
    $this->assertRaw(t('The feed %title has been deleted.', ['%title' => $feed->label()]), 'Feed deleted successfully.');
87 88 89
  }

  /**
90
   * Returns a randomly generated feed edit array.
91
   *
92
   * @param string $feed_url
93 94
   *   (optional) If given, feed will be created with this URL, otherwise
   *   /rss.xml will be used. Defaults to NULL.
95 96
   * @param array $edit
   *   Array with additional form fields.
97
   *
98
   * @return array
99 100
   *   A feed array.
   */
101
  public function getFeedEditArray($feed_url = NULL, array $edit = []) {
102
    $feed_name = $this->randomMachineName(10);
103
    if (!$feed_url) {
104 105
      $feed_url = \Drupal::url('view.frontpage.feed_1', [], [
        'query' => ['feed' => $feed_name],
106
        'absolute' => TRUE,
107
      ]);
108
    }
109
    $edit += [
110 111
      'title[0][value]' => $feed_name,
      'url[0][value]' => $feed_url,
112
      'refresh' => '900',
113
    ];
114 115 116
    return $edit;
  }

117 118 119 120 121 122 123 124 125
  /**
   * 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.
   *
126
   * @return \Drupal\aggregator\FeedInterface
127 128
   *   A feed object.
   */
129
  public function getFeedEditObject($feed_url = NULL, array $values = []) {
130
    $feed_name = $this->randomMachineName(10);
131
    if (!$feed_url) {
132 133
      $feed_url = \Drupal::url('view.frontpage.feed_1', [
        'query' => ['feed' => $feed_name],
134
        'absolute' => TRUE,
135
      ]);
136
    }
137
    $values += [
138 139 140
      'title' => $feed_name,
      'url' => $feed_url,
      'refresh' => '900',
141
    ];
142
    return Feed::create($values);
143 144
  }

145
  /**
146
   * Returns the count of the randomly created feed array.
147
   *
148
   * @return int
149 150
   *   Number of feed items on default feed created by createFeed().
   */
151
  public function getDefaultFeedItemCount() {
152
    // Our tests are based off of rss.xml, so let's find out how many elements should be related.
153
    $feed_count = db_query_range('SELECT COUNT(DISTINCT nid) FROM {node_field_data} n WHERE n.promote = 1 AND n.status = 1', 0, $this->config('system.rss')->get('items.limit'))->fetchField();
154 155 156 157
    return $feed_count > 10 ? 10 : $feed_count;
  }

  /**
158 159 160 161
   * Updates the feed items.
   *
   * This method simulates a click to
   * admin/config/services/aggregator/update/$fid.
162
   *
163
   * @param \Drupal\aggregator\FeedInterface $feed
164
   *   Feed object representing the feed.
165 166
   * @param int|null $expected_count
   *   Expected number of feed items. If omitted no check will happen.
167
   */
168
  public function updateFeedItems(FeedInterface $feed, $expected_count = NULL) {
169
    // First, let's ensure we can get to the rss xml.
170
    $this->drupalGet($feed->getUrl());
171
    $this->assertResponse(200, format_string(':url is reachable.', [':url' => $feed->getUrl()]));
172 173

    // Attempt to access the update link directly without an access token.
174
    $this->drupalGet('admin/config/services/aggregator/update/' . $feed->id());
175 176 177 178
    $this->assertResponse(403);

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

    // Ensure we have the right number of items.
182 183
    $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()]);
    $feed->items = [];
184 185 186
    foreach ($result as $item) {
      $feed->items[] = $item->iid;
    }
187 188 189

    if ($expected_count !== NULL) {
      $feed->item_count = count($feed->items);
190
      $this->assertEqual($expected_count, $feed->item_count, format_string('Total items in feed equal to the total items in database (@val1 != @val2)', ['@val1' => $expected_count, '@val2' => $feed->item_count]));
191
    }
192 193 194
  }

  /**
195
   * Confirms an item removal from a feed.
196
   *
197
   * @param \Drupal\aggregator\FeedInterface $feed
198 199
   *   Feed object representing the feed.
   */
200
  public function deleteFeedItems(FeedInterface $feed) {
201 202
    $this->drupalPostForm('admin/config/services/aggregator/delete/' . $feed->id(), [], t('Delete items'));
    $this->assertRaw(t('The news items from %title have been deleted.', ['%title' => $feed->label()]), 'Feed items deleted.');
203 204 205
  }

  /**
206
   * Adds and deletes feed items and ensure that the count is zero.
207
   *
208
   * @param \Drupal\aggregator\FeedInterface $feed
209
   *   Feed object representing the feed.
210
   * @param int $expected_count
211 212
   *   Expected number of feed items.
   */
213
  public function updateAndDelete(FeedInterface $feed, $expected_count) {
214
    $this->updateFeedItems($feed, $expected_count);
215
    $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField();
216
    $this->assertTrue($count);
217
    $this->deleteFeedItems($feed);
218
    $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField();
219 220 221 222
    $this->assertTrue($count == 0);
  }

  /**
223
   * Checks whether the feed name and URL are unique.
224
   *
225
   * @param string $feed_name
226
   *   String containing the feed name to check.
227
   * @param string $feed_url
228
   *   String containing the feed url to check.
229
   *
230
   * @return bool
231 232
   *   TRUE if feed is unique.
   */
233
  public function uniqueFeed($feed_name, $feed_url) {
234
    $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", [':title' => $feed_name, ':url' => $feed_url])->fetchField();
235 236 237 238
    return (1 == $result);
  }

  /**
239
   * Creates a valid OPML file from an array of feeds.
240
   *
241
   * @param array $feeds
242
   *   An array of feeds.
243
   *
244
   * @return string
245 246
   *   Path to valid OPML file.
   */
247
  public function getValidOpml(array $feeds) {
248 249
    // Properly escape URLs so that XML parsers don't choke on them.
    foreach ($feeds as &$feed) {
250
      $feed['url[0][value]'] = Html::escape($feed['url[0][value]']);
251 252 253 254 255 256 257 258 259
    }
    /**
     * Does not have an XML declaration, must pass the parser.
     */
    $opml = <<<EOF
<opml version="1.0">
  <head></head>
  <body>
    <!-- First feed to be imported. -->
260
    <outline text="{$feeds[0]['title[0][value]']}" xmlurl="{$feeds[0]['url[0][value]']}" />
261 262

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

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

    <!-- Test that feeds are only added with required attributes. -->
270 271
    <outline text="{$feeds[2]['title[0][value]']}" />
    <outline xmlurl="{$feeds[2]['url[0][value]']}" />
272 273 274 275 276
  </body>
</opml>
EOF;

    $path = 'public://valid-opml.xml';
277 278
    // Add the UTF-8 byte order mark.
    return file_unmanaged_save_data(chr(239) . chr(187) . chr(191) . $opml, $path);
279 280 281
  }

  /**
282
   * Creates an invalid OPML file.
283
   *
284
   * @return string
285 286
   *   Path to invalid OPML file.
   */
287
  public function getInvalidOpml() {
288 289 290 291 292 293 294 295 296 297 298
    $opml = <<<EOF
<opml>
  <invalid>
</opml>
EOF;

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

  /**
299
   * Creates a valid but empty OPML file.
300
   *
301
   * @return string
302 303
   *   Path to empty OPML file.
   */
304
  public function getEmptyOpml() {
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    $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);
  }

320 321 322 323 324 325 326
  /**
   * Returns a example RSS091 feed.
   *
   * @return string
   *   Path to the feed.
   */
  public function getRSS091Sample() {
327
    return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_rss091.xml';
328 329
  }

330 331 332 333 334 335 336
  /**
   * Returns a example Atom feed.
   *
   * @return string
   *   Path to the feed.
   */
  public function getAtomSample() {
337 338
    // The content of this sample ATOM feed is based directly off of the
    // example provided in RFC 4287.
339
    return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_atom.xml';
340 341
  }

342 343 344 345 346 347 348
  /**
   * Returns a example feed.
   *
   * @return string
   *   Path to the feed.
   */
  public function getHtmlEntitiesSample() {
349
    return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_title_entities.xml';
350 351 352 353 354
  }

  /**
   * Creates sample article nodes.
   *
355
   * @param int $count
356
   *   (optional) The number of nodes to generate. Defaults to five.
357
   */
358
  public function createSampleNodes($count = 5) {
359 360
    // Post $count article nodes.
    for ($i = 0; $i < $count; $i++) {
361
      $edit = [];
362 363
      $edit['title[0][value]'] = $this->randomMachineName();
      $edit['body[0][value]'] = $this->randomMachineName();
364
      $this->drupalPostForm('node/add/article', $edit, t('Save'));
365 366
    }
  }
367 368 369 370

  /**
   * Enable the plugins coming with aggregator_test module.
   */
371
  public function enableTestPlugins() {
372
    $this->config('aggregator.settings')
373 374
      ->set('fetcher', 'aggregator_test_fetcher')
      ->set('parser', 'aggregator_test_parser')
375
      ->set('processors', [
376
        'aggregator_test_processor' => 'aggregator_test_processor',
377
        'aggregator' => 'aggregator',
378
      ])
379 380
      ->save();
  }
381

382
}