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