3 namespace Drupal\Tests\aggregator\Functional;
5 use Drupal\aggregator\Entity\Feed;
6 use Drupal\Component\Utility\Html;
7 use Drupal\Tests\BrowserTestBase;
8 use Drupal\aggregator\FeedInterface;
11 * Defines a base class for testing the Aggregator module.
13 abstract class AggregatorTestBase extends BrowserTestBase {
16 * A user with permission to administer feeds and create content.
18 * @var \Drupal\user\Entity\User
27 public static $modules = ['block', 'node', 'aggregator', 'aggregator_test', 'views'];
32 protected function setUp() {
35 // Create an Article node type.
36 if ($this->profile != 'standard') {
37 $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
40 $this->adminUser = $this->drupalCreateUser(['access administration pages', 'administer news feeds', 'access news feeds', 'create article content']);
41 $this->drupalLogin($this->adminUser);
42 $this->drupalPlaceBlock('local_tasks_block');
46 * Creates an aggregator feed.
48 * This method simulates the form submission on path aggregator/sources/add.
50 * @param string $feed_url
51 * (optional) If given, feed will be created with this URL, otherwise
52 * /rss.xml will be used. Defaults to NULL.
54 * Array with additional form fields.
56 * @return \Drupal\aggregator\FeedInterface
57 * Full feed object if possible.
59 * @see getFeedEditArray()
61 public function createFeed($feed_url = NULL, array $edit = []) {
62 $edit = $this->getFeedEditArray($feed_url, $edit);
63 $this->drupalPostForm('aggregator/sources/add', $edit, t('Save'));
64 $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]']]));
66 // Verify that the creation message contains a link to a feed.
67 $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'aggregator/sources/']);
68 $this->assert(isset($view_link), 'The message area contains a link to a feed');
70 $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();
71 $this->assertTrue(!empty($fid), 'The feed found in database.');
72 return Feed::load($fid);
76 * Deletes an aggregator feed.
78 * @param \Drupal\aggregator\FeedInterface $feed
79 * Feed object representing the feed.
81 public function deleteFeed(FeedInterface $feed) {
82 $this->drupalPostForm('aggregator/sources/' . $feed->id() . '/delete', [], t('Delete'));
83 $this->assertRaw(t('The feed %title has been deleted.', ['%title' => $feed->label()]), 'Feed deleted successfully.');
87 * Returns a randomly generated feed edit array.
89 * @param string $feed_url
90 * (optional) If given, feed will be created with this URL, otherwise
91 * /rss.xml will be used. Defaults to NULL.
93 * Array with additional form fields.
98 public function getFeedEditArray($feed_url = NULL, array $edit = []) {
99 $feed_name = $this->randomMachineName(10);
101 $feed_url = \Drupal::url('view.frontpage.feed_1', [], [
102 'query' => ['feed' => $feed_name],
107 'title[0][value]' => $feed_name,
108 'url[0][value]' => $feed_url,
115 * Returns a randomly generated feed edit object.
117 * @param string $feed_url
118 * (optional) If given, feed will be created with this URL, otherwise
119 * /rss.xml will be used. Defaults to NULL.
120 * @param array $values
121 * (optional) Default values to initialize object properties with.
123 * @return \Drupal\aggregator\FeedInterface
126 public function getFeedEditObject($feed_url = NULL, array $values = []) {
127 $feed_name = $this->randomMachineName(10);
129 $feed_url = \Drupal::url('view.frontpage.feed_1', [
130 'query' => ['feed' => $feed_name],
135 'title' => $feed_name,
139 return Feed::create($values);
143 * Returns the count of the randomly created feed array.
146 * Number of feed items on default feed created by createFeed().
148 public function getDefaultFeedItemCount() {
149 // Our tests are based off of rss.xml, so let's find out how many elements should be related.
150 $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();
151 return $feed_count > 10 ? 10 : $feed_count;
155 * Updates the feed items.
157 * This method simulates a click to
158 * admin/config/services/aggregator/update/$fid.
160 * @param \Drupal\aggregator\FeedInterface $feed
161 * Feed object representing the feed.
162 * @param int|null $expected_count
163 * Expected number of feed items. If omitted no check will happen.
165 public function updateFeedItems(FeedInterface $feed, $expected_count = NULL) {
166 // First, let's ensure we can get to the rss xml.
167 $this->drupalGet($feed->getUrl());
168 $this->assertResponse(200, format_string(':url is reachable.', [':url' => $feed->getUrl()]));
170 // Attempt to access the update link directly without an access token.
171 $this->drupalGet('admin/config/services/aggregator/update/' . $feed->id());
172 $this->assertResponse(403);
174 // Refresh the feed (simulated link click).
175 $this->drupalGet('admin/config/services/aggregator');
176 $this->clickLink('Update items');
178 // Ensure we have the right number of items.
179 $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()]);
181 foreach ($result as $item) {
182 $feed->items[] = $item->iid;
185 if ($expected_count !== NULL) {
186 $feed->item_count = count($feed->items);
187 $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]));
192 * Confirms an item removal from a feed.
194 * @param \Drupal\aggregator\FeedInterface $feed
195 * Feed object representing the feed.
197 public function deleteFeedItems(FeedInterface $feed) {
198 $this->drupalPostForm('admin/config/services/aggregator/delete/' . $feed->id(), [], t('Delete items'));
199 $this->assertRaw(t('The news items from %title have been deleted.', ['%title' => $feed->label()]), 'Feed items deleted.');
203 * Adds and deletes feed items and ensure that the count is zero.
205 * @param \Drupal\aggregator\FeedInterface $feed
206 * Feed object representing the feed.
207 * @param int $expected_count
208 * Expected number of feed items.
210 public function updateAndDelete(FeedInterface $feed, $expected_count) {
211 $this->updateFeedItems($feed, $expected_count);
212 $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField();
213 $this->assertTrue($count);
214 $this->deleteFeedItems($feed);
215 $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField();
216 $this->assertTrue($count == 0);
220 * Checks whether the feed name and URL are unique.
222 * @param string $feed_name
223 * String containing the feed name to check.
224 * @param string $feed_url
225 * String containing the feed url to check.
228 * TRUE if feed is unique.
230 public function uniqueFeed($feed_name, $feed_url) {
231 $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", [':title' => $feed_name, ':url' => $feed_url])->fetchField();
232 return (1 == $result);
236 * Creates a valid OPML file from an array of feeds.
238 * @param array $feeds
242 * Path to valid OPML file.
244 public function getValidOpml(array $feeds) {
245 // Properly escape URLs so that XML parsers don't choke on them.
246 foreach ($feeds as &$feed) {
247 $feed['url[0][value]'] = Html::escape($feed['url[0][value]']);
250 * Does not have an XML declaration, must pass the parser.
256 <!-- First feed to be imported. -->
257 <outline text="{$feeds[0]['title[0][value]']}" xmlurl="{$feeds[0]['url[0][value]']}" />
259 <!-- Second feed. Test string delimitation and attribute order. -->
260 <outline xmlurl='{$feeds[1]['url[0][value]']}' text='{$feeds[1]['title[0][value]']}'/>
262 <!-- Test for duplicate URL and title. -->
263 <outline xmlurl="{$feeds[0]['url[0][value]']}" text="Duplicate URL"/>
264 <outline xmlurl="http://duplicate.title" text="{$feeds[1]['title[0][value]']}"/>
266 <!-- Test that feeds are only added with required attributes. -->
267 <outline text="{$feeds[2]['title[0][value]']}" />
268 <outline xmlurl="{$feeds[2]['url[0][value]']}" />
273 $path = 'public://valid-opml.xml';
274 // Add the UTF-8 byte order mark.
275 return file_unmanaged_save_data(chr(239) . chr(187) . chr(191) . $opml, $path);
279 * Creates an invalid OPML file.
282 * Path to invalid OPML file.
284 public function getInvalidOpml() {
291 $path = 'public://invalid-opml.xml';
292 return file_unmanaged_save_data($opml, $path);
296 * Creates a valid but empty OPML file.
299 * Path to empty OPML file.
301 public function getEmptyOpml() {
303 <?xml version="1.0" encoding="utf-8"?>
307 <outline text="Sample text" />
308 <outline text="Sample text" url="Sample URL" />
313 $path = 'public://empty-opml.xml';
314 return file_unmanaged_save_data($opml, $path);
318 * Returns a example RSS091 feed.
323 public function getRSS091Sample() {
324 return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_rss091.xml';
328 * Returns a example Atom feed.
333 public function getAtomSample() {
334 // The content of this sample ATOM feed is based directly off of the
335 // example provided in RFC 4287.
336 return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_atom.xml';
340 * Returns a example feed.
345 public function getHtmlEntitiesSample() {
346 return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_title_entities.xml';
350 * Creates sample article nodes.
353 * (optional) The number of nodes to generate. Defaults to five.
355 public function createSampleNodes($count = 5) {
356 // Post $count article nodes.
357 for ($i = 0; $i < $count; $i++) {
359 $edit['title[0][value]'] = $this->randomMachineName();
360 $edit['body[0][value]'] = $this->randomMachineName();
361 $this->drupalPostForm('node/add/article', $edit, t('Save'));
366 * Enable the plugins coming with aggregator_test module.
368 public function enableTestPlugins() {
369 $this->config('aggregator.settings')
370 ->set('fetcher', 'aggregator_test_fetcher')
371 ->set('parser', 'aggregator_test_parser')
372 ->set('processors', [
373 'aggregator_test_processor' => 'aggregator_test_processor',
374 'aggregator' => 'aggregator',