1. 8.2.x core/modules/aggregator/src/Tests/AggregatorTestBase.php
  2. 8.0.x core/modules/aggregator/src/Tests/AggregatorTestBase.php
  3. 8.1.x core/modules/aggregator/src/Tests/AggregatorTestBase.php
  4. 8.3.x core/modules/aggregator/tests/src/Functional/AggregatorTestBase.php
  5. 8.3.x core/modules/aggregator/src/Tests/AggregatorTestBase.php

Namespace

Drupal\aggregator\Tests

File

core/modules/aggregator/src/Tests/AggregatorTestBase.php
View source
  1. <?php
  2. namespace Drupal\aggregator\Tests;
  3. use Drupal\aggregator\Entity\Feed;
  4. use Drupal\Component\Utility\Html;
  5. use Drupal\simpletest\WebTestBase;
  6. use Drupal\aggregator\FeedInterface;
  7. /**
  8. * Defines a base class for testing the Aggregator module.
  9. */
  10. abstract class AggregatorTestBase extends WebTestBase {
  11. /**
  12. * A user with permission to administer feeds and create content.
  13. *
  14. * @var \Drupal\user\Entity\User
  15. */
  16. protected $adminUser;
  17. /**
  18. * Modules to install.
  19. *
  20. * @var array
  21. */
  22. public static $modules = ['block', 'node', 'aggregator', 'aggregator_test', 'views'];
  23. /**
  24. * {@inheritdoc}
  25. */
  26. protected function setUp() {
  27. parent::setUp();
  28. // Create an Article node type.
  29. if ($this->profile != 'standard') {
  30. $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
  31. }
  32. $this->adminUser = $this->drupalCreateUser(array('access administration pages', 'administer news feeds', 'access news feeds', 'create article content'));
  33. $this->drupalLogin($this->adminUser);
  34. $this->drupalPlaceBlock('local_tasks_block');
  35. }
  36. /**
  37. * Creates an aggregator feed.
  38. *
  39. * This method simulates the form submission on path aggregator/sources/add.
  40. *
  41. * @param string $feed_url
  42. * (optional) If given, feed will be created with this URL, otherwise
  43. * /rss.xml will be used. Defaults to NULL.
  44. * @param array $edit
  45. * Array with additional form fields.
  46. *
  47. * @return \Drupal\aggregator\FeedInterface
  48. * Full feed object if possible.
  49. *
  50. * @see getFeedEditArray()
  51. */
  52. public function createFeed($feed_url = NULL, array $edit = array()) {
  53. $edit = $this->getFeedEditArray($feed_url, $edit);
  54. $this->drupalPostForm('aggregator/sources/add', $edit, t('Save'));
  55. $this->assertText(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]'])));
  56. // Verify that the creation message contains a link to a feed.
  57. $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', array(':href' => 'aggregator/sources/'));
  58. $this->assert(isset($view_link), 'The message area contains a link to a feed');
  59. $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();
  60. $this->assertTrue(!empty($fid), 'The feed found in database.');
  61. return Feed::load($fid);
  62. }
  63. /**
  64. * Deletes an aggregator feed.
  65. *
  66. * @param \Drupal\aggregator\FeedInterface $feed
  67. * Feed object representing the feed.
  68. */
  69. public function deleteFeed(FeedInterface $feed) {
  70. $this->drupalPostForm('aggregator/sources/' . $feed->id() . '/delete', array(), t('Delete'));
  71. $this->assertRaw(t('The feed %title has been deleted.', array('%title' => $feed->label())), 'Feed deleted successfully.');
  72. }
  73. /**
  74. * Returns a randomly generated feed edit array.
  75. *
  76. * @param string $feed_url
  77. * (optional) If given, feed will be created with this URL, otherwise
  78. * /rss.xml will be used. Defaults to NULL.
  79. * @param array $edit
  80. * Array with additional form fields.
  81. *
  82. * @return array
  83. * A feed array.
  84. */
  85. public function getFeedEditArray($feed_url = NULL, array $edit = array()) {
  86. $feed_name = $this->randomMachineName(10);
  87. if (!$feed_url) {
  88. $feed_url = \Drupal::url('view.frontpage.feed_1', array(), array(
  89. 'query' => array('feed' => $feed_name),
  90. 'absolute' => TRUE,
  91. ));
  92. }
  93. $edit += array(
  94. 'title[0][value]' => $feed_name,
  95. 'url[0][value]' => $feed_url,
  96. 'refresh' => '900',
  97. );
  98. return $edit;
  99. }
  100. /**
  101. * Returns a randomly generated feed edit object.
  102. *
  103. * @param string $feed_url
  104. * (optional) If given, feed will be created with this URL, otherwise
  105. * /rss.xml will be used. Defaults to NULL.
  106. * @param array $values
  107. * (optional) Default values to initialize object properties with.
  108. *
  109. * @return \Drupal\aggregator\FeedInterface
  110. * A feed object.
  111. */
  112. public function getFeedEditObject($feed_url = NULL, array $values = array()) {
  113. $feed_name = $this->randomMachineName(10);
  114. if (!$feed_url) {
  115. $feed_url = \Drupal::url('view.frontpage.feed_1', array(
  116. 'query' => array('feed' => $feed_name),
  117. 'absolute' => TRUE,
  118. ));
  119. }
  120. $values += array(
  121. 'title' => $feed_name,
  122. 'url' => $feed_url,
  123. 'refresh' => '900',
  124. );
  125. return Feed::create($values);
  126. }
  127. /**
  128. * Returns the count of the randomly created feed array.
  129. *
  130. * @return int
  131. * Number of feed items on default feed created by createFeed().
  132. */
  133. public function getDefaultFeedItemCount() {
  134. // Our tests are based off of rss.xml, so let's find out how many elements should be related.
  135. $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();
  136. return $feed_count > 10 ? 10 : $feed_count;
  137. }
  138. /**
  139. * Updates the feed items.
  140. *
  141. * This method simulates a click to
  142. * admin/config/services/aggregator/update/$fid.
  143. *
  144. * @param \Drupal\aggregator\FeedInterface $feed
  145. * Feed object representing the feed.
  146. * @param int|null $expected_count
  147. * Expected number of feed items. If omitted no check will happen.
  148. */
  149. public function updateFeedItems(FeedInterface $feed, $expected_count = NULL) {
  150. // First, let's ensure we can get to the rss xml.
  151. $this->drupalGet($feed->getUrl());
  152. $this->assertResponse(200, format_string(':url is reachable.', array(':url' => $feed->getUrl())));
  153. // Attempt to access the update link directly without an access token.
  154. $this->drupalGet('admin/config/services/aggregator/update/' . $feed->id());
  155. $this->assertResponse(403);
  156. // Refresh the feed (simulated link click).
  157. $this->drupalGet('admin/config/services/aggregator');
  158. $this->clickLink('Update items');
  159. // Ensure we have the right number of items.
  160. $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()));
  161. $feed->items = array();
  162. foreach ($result as $item) {
  163. $feed->items[] = $item->iid;
  164. }
  165. if ($expected_count !== NULL) {
  166. $feed->item_count = count($feed->items);
  167. $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)));
  168. }
  169. }
  170. /**
  171. * Confirms an item removal from a feed.
  172. *
  173. * @param \Drupal\aggregator\FeedInterface $feed
  174. * Feed object representing the feed.
  175. */
  176. public function deleteFeedItems(FeedInterface $feed) {
  177. $this->drupalPostForm('admin/config/services/aggregator/delete/' . $feed->id(), array(), t('Delete items'));
  178. $this->assertRaw(t('The news items from %title have been deleted.', array('%title' => $feed->label())), 'Feed items deleted.');
  179. }
  180. /**
  181. * Adds and deletes feed items and ensure that the count is zero.
  182. *
  183. * @param \Drupal\aggregator\FeedInterface $feed
  184. * Feed object representing the feed.
  185. * @param int $expected_count
  186. * Expected number of feed items.
  187. */
  188. public function updateAndDelete(FeedInterface $feed, $expected_count) {
  189. $this->updateFeedItems($feed, $expected_count);
  190. $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField();
  191. $this->assertTrue($count);
  192. $this->deleteFeedItems($feed);
  193. $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField();
  194. $this->assertTrue($count == 0);
  195. }
  196. /**
  197. * Checks whether the feed name and URL are unique.
  198. *
  199. * @param string $feed_name
  200. * String containing the feed name to check.
  201. * @param string $feed_url
  202. * String containing the feed url to check.
  203. *
  204. * @return bool
  205. * TRUE if feed is unique.
  206. */
  207. public function uniqueFeed($feed_name, $feed_url) {
  208. $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $feed_name, ':url' => $feed_url))->fetchField();
  209. return (1 == $result);
  210. }
  211. /**
  212. * Creates a valid OPML file from an array of feeds.
  213. *
  214. * @param array $feeds
  215. * An array of feeds.
  216. *
  217. * @return string
  218. * Path to valid OPML file.
  219. */
  220. public function getValidOpml(array $feeds) {
  221. // Properly escape URLs so that XML parsers don't choke on them.
  222. foreach ($feeds as &$feed) {
  223. $feed['url[0][value]'] = Html::escape($feed['url[0][value]']);
  224. }
  225. /**
  226. * Does not have an XML declaration, must pass the parser.
  227. */
  228. $opml = <<<EOF
  229. <opml version="1.0">
  230. <head></head>
  231. <body>
  232. <!-- First feed to be imported. -->
  233. <outline text="{$feeds[0]['title[0][value]']}" xmlurl="{$feeds[0]['url[0][value]']}" />
  234. <!-- Second feed. Test string delimitation and attribute order. -->
  235. <outline xmlurl='{$feeds[1]['url[0][value]']}' text='{$feeds[1]['title[0][value]']}'/>
  236. <!-- Test for duplicate URL and title. -->
  237. <outline xmlurl="{$feeds[0]['url[0][value]']}" text="Duplicate URL"/>
  238. <outline xmlurl="http://duplicate.title" text="{$feeds[1]['title[0][value]']}"/>
  239. <!-- Test that feeds are only added with required attributes. -->
  240. <outline text="{$feeds[2]['title[0][value]']}" />
  241. <outline xmlurl="{$feeds[2]['url[0][value]']}" />
  242. </body>
  243. </opml>
  244. EOF;
  245. $path = 'public://valid-opml.xml';
  246. return file_unmanaged_save_data($opml, $path);
  247. }
  248. /**
  249. * Creates an invalid OPML file.
  250. *
  251. * @return string
  252. * Path to invalid OPML file.
  253. */
  254. public function getInvalidOpml() {
  255. $opml = <<<EOF
  256. <opml>
  257. <invalid>
  258. </opml>
  259. EOF;
  260. $path = 'public://invalid-opml.xml';
  261. return file_unmanaged_save_data($opml, $path);
  262. }
  263. /**
  264. * Creates a valid but empty OPML file.
  265. *
  266. * @return string
  267. * Path to empty OPML file.
  268. */
  269. public function getEmptyOpml() {
  270. $opml = <<<EOF
  271. <?xml version="1.0" encoding="utf-8"?>
  272. <opml version="1.0">
  273. <head></head>
  274. <body>
  275. <outline text="Sample text" />
  276. <outline text="Sample text" url="Sample URL" />
  277. </body>
  278. </opml>
  279. EOF;
  280. $path = 'public://empty-opml.xml';
  281. return file_unmanaged_save_data($opml, $path);
  282. }
  283. /**
  284. * Returns a example RSS091 feed.
  285. *
  286. * @return string
  287. * Path to the feed.
  288. */
  289. public function getRSS091Sample() {
  290. return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_rss091.xml';
  291. }
  292. /**
  293. * Returns a example Atom feed.
  294. *
  295. * @return string
  296. * Path to the feed.
  297. */
  298. public function getAtomSample() {
  299. // The content of this sample ATOM feed is based directly off of the
  300. // example provided in RFC 4287.
  301. return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_atom.xml';
  302. }
  303. /**
  304. * Returns a example feed.
  305. *
  306. * @return string
  307. * Path to the feed.
  308. */
  309. public function getHtmlEntitiesSample() {
  310. return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_title_entities.xml';
  311. }
  312. /**
  313. * Creates sample article nodes.
  314. *
  315. * @param int $count
  316. * (optional) The number of nodes to generate. Defaults to five.
  317. */
  318. public function createSampleNodes($count = 5) {
  319. // Post $count article nodes.
  320. for ($i = 0; $i < $count; $i++) {
  321. $edit = array();
  322. $edit['title[0][value]'] = $this->randomMachineName();
  323. $edit['body[0][value]'] = $this->randomMachineName();
  324. $this->drupalPostForm('node/add/article', $edit, t('Save'));
  325. }
  326. }
  327. /**
  328. * Enable the plugins coming with aggregator_test module.
  329. */
  330. public function enableTestPlugins() {
  331. $this->config('aggregator.settings')
  332. ->set('fetcher', 'aggregator_test_fetcher')
  333. ->set('parser', 'aggregator_test_parser')
  334. ->set('processors', array(
  335. 'aggregator_test_processor' => 'aggregator_test_processor',
  336. 'aggregator' => 'aggregator',
  337. ))
  338. ->save();
  339. }
  340. }

Classes

Namesort descending Description
AggregatorTestBase Defines a base class for testing the Aggregator module.