Pull merge.
[yaffs-website] / web / core / modules / aggregator / tests / src / Functional / AggregatorTestBase.php
1 <?php
2
3 namespace Drupal\Tests\aggregator\Functional;
4
5 use Drupal\aggregator\Entity\Feed;
6 use Drupal\Component\Utility\Html;
7 use Drupal\Tests\BrowserTestBase;
8 use Drupal\aggregator\FeedInterface;
9
10 /**
11  * Defines a base class for testing the Aggregator module.
12  */
13 abstract class AggregatorTestBase extends BrowserTestBase {
14
15   /**
16    * A user with permission to administer feeds and create content.
17    *
18    * @var \Drupal\user\Entity\User
19    */
20   protected $adminUser;
21
22   /**
23    * Modules to install.
24    *
25    * @var array
26    */
27   public static $modules = ['block', 'node', 'aggregator', 'aggregator_test', 'views'];
28
29   /**
30    * {@inheritdoc}
31    */
32   protected function setUp() {
33     parent::setUp();
34
35     // Create an Article node type.
36     if ($this->profile != 'standard') {
37       $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
38     }
39
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');
43   }
44
45   /**
46    * Creates an aggregator feed.
47    *
48    * This method simulates the form submission on path aggregator/sources/add.
49    *
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.
53    * @param array $edit
54    *   Array with additional form fields.
55    *
56    * @return \Drupal\aggregator\FeedInterface
57    *   Full feed object if possible.
58    *
59    * @see getFeedEditArray()
60    */
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]']]));
65
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');
69
70     $fids = \Drupal::entityQuery('aggregator_feed')->condition('title', $edit['title[0][value]'])->condition('url', $edit['url[0][value]'])->execute();
71     $this->assertNotEmpty($fids, 'The feed found in database.');
72     return Feed::load(array_values($fids)[0]);
73   }
74
75   /**
76    * Deletes an aggregator feed.
77    *
78    * @param \Drupal\aggregator\FeedInterface $feed
79    *   Feed object representing the feed.
80    */
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.');
84   }
85
86   /**
87    * Returns a randomly generated feed edit array.
88    *
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.
92    * @param array $edit
93    *   Array with additional form fields.
94    *
95    * @return array
96    *   A feed array.
97    */
98   public function getFeedEditArray($feed_url = NULL, array $edit = []) {
99     $feed_name = $this->randomMachineName(10);
100     if (!$feed_url) {
101       $feed_url = \Drupal::url('view.frontpage.feed_1', [], [
102         'query' => ['feed' => $feed_name],
103         'absolute' => TRUE,
104       ]);
105     }
106     $edit += [
107       'title[0][value]' => $feed_name,
108       'url[0][value]' => $feed_url,
109       'refresh' => '900',
110     ];
111     return $edit;
112   }
113
114   /**
115    * Returns a randomly generated feed edit object.
116    *
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.
122    *
123    * @return \Drupal\aggregator\FeedInterface
124    *   A feed object.
125    */
126   public function getFeedEditObject($feed_url = NULL, array $values = []) {
127     $feed_name = $this->randomMachineName(10);
128     if (!$feed_url) {
129       $feed_url = \Drupal::url('view.frontpage.feed_1', [
130         'query' => ['feed' => $feed_name],
131         'absolute' => TRUE,
132       ]);
133     }
134     $values += [
135       'title' => $feed_name,
136       'url' => $feed_url,
137       'refresh' => '900',
138     ];
139     return Feed::create($values);
140   }
141
142   /**
143    * Returns the count of the randomly created feed array.
144    *
145    * @return int
146    *   Number of feed items on default feed created by createFeed().
147    */
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;
152   }
153
154   /**
155    * Updates the feed items.
156    *
157    * This method simulates a click to
158    * admin/config/services/aggregator/update/$fid.
159    *
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.
164    */
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()]));
169
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);
173
174     // Refresh the feed (simulated link click).
175     $this->drupalGet('admin/config/services/aggregator');
176     $this->clickLink('Update items');
177
178     // Ensure we have the right number of items.
179     $iids = \Drupal::entityQuery('aggregator_item')->condition('fid', $feed->id())->execute();
180     $feed->items = [];
181     foreach ($iids as $iid) {
182       $feed->items[] = $iid;
183     }
184
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]));
188     }
189   }
190
191   /**
192    * Confirms an item removal from a feed.
193    *
194    * @param \Drupal\aggregator\FeedInterface $feed
195    *   Feed object representing the feed.
196    */
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.');
200   }
201
202   /**
203    * Adds and deletes feed items and ensure that the count is zero.
204    *
205    * @param \Drupal\aggregator\FeedInterface $feed
206    *   Feed object representing the feed.
207    * @param int $expected_count
208    *   Expected number of feed items.
209    */
210   public function updateAndDelete(FeedInterface $feed, $expected_count) {
211     $count_query = \Drupal::entityQuery('aggregator_item')->condition('fid', $feed->id())->count();
212     $this->updateFeedItems($feed, $expected_count);
213     $count = $count_query->execute();
214     $this->assertTrue($count);
215     $this->deleteFeedItems($feed);
216     $count = $count_query->execute();
217     $this->assertTrue($count == 0);
218   }
219
220   /**
221    * Checks whether the feed name and URL are unique.
222    *
223    * @param string $feed_name
224    *   String containing the feed name to check.
225    * @param string $feed_url
226    *   String containing the feed url to check.
227    *
228    * @return bool
229    *   TRUE if feed is unique.
230    */
231   public function uniqueFeed($feed_name, $feed_url) {
232     $result = \Drupal::entityQuery('aggregator_feed')->condition('title', $feed_name)->condition('url', $feed_url)->count()->execute();
233     return (1 == $result);
234   }
235
236   /**
237    * Creates a valid OPML file from an array of feeds.
238    *
239    * @param array $feeds
240    *   An array of feeds.
241    *
242    * @return string
243    *   Path to valid OPML file.
244    */
245   public function getValidOpml(array $feeds) {
246     // Properly escape URLs so that XML parsers don't choke on them.
247     foreach ($feeds as &$feed) {
248       $feed['url[0][value]'] = Html::escape($feed['url[0][value]']);
249     }
250     /**
251      * Does not have an XML declaration, must pass the parser.
252      */
253     $opml = <<<EOF
254 <opml version="1.0">
255   <head></head>
256   <body>
257     <!-- First feed to be imported. -->
258     <outline text="{$feeds[0]['title[0][value]']}" xmlurl="{$feeds[0]['url[0][value]']}" />
259
260     <!-- Second feed. Test string delimitation and attribute order. -->
261     <outline xmlurl='{$feeds[1]['url[0][value]']}' text='{$feeds[1]['title[0][value]']}'/>
262
263     <!-- Test for duplicate URL and title. -->
264     <outline xmlurl="{$feeds[0]['url[0][value]']}" text="Duplicate URL"/>
265     <outline xmlurl="http://duplicate.title" text="{$feeds[1]['title[0][value]']}"/>
266
267     <!-- Test that feeds are only added with required attributes. -->
268     <outline text="{$feeds[2]['title[0][value]']}" />
269     <outline xmlurl="{$feeds[2]['url[0][value]']}" />
270   </body>
271 </opml>
272 EOF;
273
274     $path = 'public://valid-opml.xml';
275     // Add the UTF-8 byte order mark.
276     return file_unmanaged_save_data(chr(239) . chr(187) . chr(191) . $opml, $path);
277   }
278
279   /**
280    * Creates an invalid OPML file.
281    *
282    * @return string
283    *   Path to invalid OPML file.
284    */
285   public function getInvalidOpml() {
286     $opml = <<<EOF
287 <opml>
288   <invalid>
289 </opml>
290 EOF;
291
292     $path = 'public://invalid-opml.xml';
293     return file_unmanaged_save_data($opml, $path);
294   }
295
296   /**
297    * Creates a valid but empty OPML file.
298    *
299    * @return string
300    *   Path to empty OPML file.
301    */
302   public function getEmptyOpml() {
303     $opml = <<<EOF
304 <?xml version="1.0" encoding="utf-8"?>
305 <opml version="1.0">
306   <head></head>
307   <body>
308     <outline text="Sample text" />
309     <outline text="Sample text" url="Sample URL" />
310   </body>
311 </opml>
312 EOF;
313
314     $path = 'public://empty-opml.xml';
315     return file_unmanaged_save_data($opml, $path);
316   }
317
318   /**
319    * Returns a example RSS091 feed.
320    *
321    * @return string
322    *   Path to the feed.
323    */
324   public function getRSS091Sample() {
325     return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_rss091.xml';
326   }
327
328   /**
329    * Returns a example Atom feed.
330    *
331    * @return string
332    *   Path to the feed.
333    */
334   public function getAtomSample() {
335     // The content of this sample ATOM feed is based directly off of the
336     // example provided in RFC 4287.
337     return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_atom.xml';
338   }
339
340   /**
341    * Returns a example feed.
342    *
343    * @return string
344    *   Path to the feed.
345    */
346   public function getHtmlEntitiesSample() {
347     return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_title_entities.xml';
348   }
349
350   /**
351    * Creates sample article nodes.
352    *
353    * @param int $count
354    *   (optional) The number of nodes to generate. Defaults to five.
355    */
356   public function createSampleNodes($count = 5) {
357     // Post $count article nodes.
358     for ($i = 0; $i < $count; $i++) {
359       $edit = [];
360       $edit['title[0][value]'] = $this->randomMachineName();
361       $edit['body[0][value]'] = $this->randomMachineName();
362       $this->drupalPostForm('node/add/article', $edit, t('Save'));
363     }
364   }
365
366   /**
367    * Enable the plugins coming with aggregator_test module.
368    */
369   public function enableTestPlugins() {
370     $this->config('aggregator.settings')
371       ->set('fetcher', 'aggregator_test_fetcher')
372       ->set('parser', 'aggregator_test_parser')
373       ->set('processors', [
374         'aggregator_test_processor' => 'aggregator_test_processor',
375         'aggregator' => 'aggregator',
376       ])
377       ->save();
378   }
379
380 }