Project

General

Profile

Paste
Download (38 KB) Statistics
| Branch: | Revision:

root / drupal7 / modules / aggregator / aggregator.test @ b0dc3a2e

1
<?php
2

    
3
/**
4
 * @file
5
 * Tests for aggregator.module.
6
 */
7

    
8
/**
9
 * Defines a base class for testing the Aggregator module.
10
 */
11
class AggregatorTestCase extends DrupalWebTestCase {
12
  function setUp() {
13
    parent::setUp('aggregator', 'aggregator_test');
14
    $web_user = $this->drupalCreateUser(array('administer news feeds', 'access news feeds', 'create article content'));
15
    $this->drupalLogin($web_user);
16
  }
17

    
18
  /**
19
   * Creates an aggregator feed.
20
   *
21
   * This method simulates the form submission on path
22
   * admin/config/services/aggregator/add/feed.
23
   *
24
   * @param $feed_url
25
   *   (optional) If given, feed will be created with this URL, otherwise
26
   *   /rss.xml will be used. Defaults to NULL.
27
   *
28
   * @return $feed
29
   *   Full feed object if possible.
30
   *
31
   * @see getFeedEditArray()
32
   */
33
  function createFeed($feed_url = NULL) {
34
    $edit = $this->getFeedEditArray($feed_url);
35
    $this->drupalPost('admin/config/services/aggregator/add/feed', $edit, t('Save'));
36
    $this->assertRaw(t('The feed %name has been added.', array('%name' => $edit['title'])), format_string('The feed !name has been added.', array('!name' => $edit['title'])));
37

    
38
    $feed = db_query("SELECT *  FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $edit['title'], ':url' => $edit['url']))->fetch();
39
    $this->assertTrue(!empty($feed), 'The feed found in database.');
40
    return $feed;
41
  }
42

    
43
  /**
44
   * Deletes an aggregator feed.
45
   *
46
   * @param $feed
47
   *   Feed object representing the feed.
48
   */
49
  function deleteFeed($feed) {
50
    $this->drupalPost('admin/config/services/aggregator/edit/feed/' . $feed->fid, array(), t('Delete'));
51
    $this->assertRaw(t('The feed %title has been deleted.', array('%title' => $feed->title)), 'Feed deleted successfully.');
52
  }
53

    
54
  /**
55
   * Returns a randomly generated feed edit array.
56
   *
57
   * @param $feed_url
58
   *   (optional) If given, feed will be created with this URL, otherwise
59
   *   /rss.xml will be used. Defaults to NULL.
60
   * @return
61
   *   A feed array.
62
   */
63
  function getFeedEditArray($feed_url = NULL) {
64
    $feed_name = $this->randomName(10);
65
    if (!$feed_url) {
66
      $feed_url = url('rss.xml', array(
67
        'query' => array('feed' => $feed_name),
68
        'absolute' => TRUE,
69
      ));
70
    }
71
    $edit = array(
72
      'title' => $feed_name,
73
      'url' => $feed_url,
74
      'refresh' => '900',
75
    );
76
    return $edit;
77
  }
78

    
79
  /**
80
   * Returns the count of the randomly created feed array.
81
   *
82
   * @return
83
   *   Number of feed items on default feed created by createFeed().
84
   */
85
  function getDefaultFeedItemCount() {
86
    // Our tests are based off of rss.xml, so let's find out how many elements should be related.
87
    $feed_count = db_query_range('SELECT COUNT(*) FROM {node} n WHERE n.promote = 1 AND n.status = 1', 0, variable_get('feed_default_items', 10))->fetchField();
88
    return $feed_count > 10 ? 10 : $feed_count;
89
  }
90

    
91
  /**
92
   * Updates the feed items.
93
   *
94
   * This method simulates a click to
95
   * admin/config/services/aggregator/update/$fid.
96
   *
97
   * @param $feed
98
   *   Feed object representing the feed, passed by reference.
99
   * @param $expected_count
100
   *   Expected number of feed items.
101
   */
102
  function updateFeedItems(&$feed, $expected_count) {
103
    // First, let's ensure we can get to the rss xml.
104
    $this->drupalGet($feed->url);
105
    $this->assertResponse(200, format_string('!url is reachable.', array('!url' => $feed->url)));
106

    
107
    // Attempt to access the update link directly without an access token.
108
    $this->drupalGet('admin/config/services/aggregator/update/' . $feed->fid);
109
    $this->assertResponse(403);
110

    
111
    // Refresh the feed (simulated link click).
112
    $this->drupalGet('admin/config/services/aggregator');
113
    $this->clickLink('update items');
114

    
115
    // Ensure we have the right number of items.
116
    $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid));
117
    $items = array();
118
    $feed->items = array();
119
    foreach ($result as $item) {
120
      $feed->items[] = $item->iid;
121
    }
122
    $feed->item_count = count($feed->items);
123
    $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)));
124
  }
125

    
126
  /**
127
   * Confirms an item removal from a feed.
128
   *
129
   * @param $feed
130
   *   Feed object representing the feed.
131
   */
132
  function removeFeedItems($feed) {
133
    $this->drupalPost('admin/config/services/aggregator/remove/' . $feed->fid, array(), t('Remove items'));
134
    $this->assertRaw(t('The news items from %title have been removed.', array('%title' => $feed->title)), 'Feed items removed.');
135
  }
136

    
137
  /**
138
   * Adds and removes feed items and ensure that the count is zero.
139
   *
140
   * @param $feed
141
   *   Feed object representing the feed.
142
   * @param $expected_count
143
   *   Expected number of feed items.
144
   */
145
  function updateAndRemove($feed, $expected_count) {
146
    $this->updateFeedItems($feed, $expected_count);
147
    $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField();
148
    $this->assertTrue($count);
149
    $this->removeFeedItems($feed);
150
    $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField();
151
    $this->assertTrue($count == 0);
152
  }
153

    
154
  /**
155
   * Pulls feed categories from {aggregator_category_feed} table.
156
   *
157
   * @param $feed
158
   *   Feed object representing the feed.
159
   */
160
  function getFeedCategories($feed) {
161
    // add the categories to the feed so we can use them
162
    $result = db_query('SELECT cid FROM {aggregator_category_feed} WHERE fid = :fid', array(':fid' => $feed->fid));
163
    foreach ($result as $category) {
164
      $feed->categories[] = $category->cid;
165
    }
166
  }
167

    
168
  /**
169
   * Pulls categories from {aggregator_category} table.
170
   *
171
   * @return
172
   *   An associative array keyed by category ID and values are set to the
173
   *   category names.
174
   */
175
  function getCategories() {
176
    $categories = array();
177
    $result = db_query('SELECT * FROM {aggregator_category}');
178
    foreach ($result as $category) {
179
      $categories[$category->cid] = $category;
180
    }
181
    return $categories;
182
  }
183

    
184
  /**
185
   * Checks whether the feed name and URL are unique.
186
   *
187
   * @param $feed_name
188
   *   String containing the feed name to check.
189
   * @param $feed_url
190
   *   String containing the feed URL to check.
191
   *
192
   * @return
193
   *   TRUE if feed is unique.
194
   */
195
  function uniqueFeed($feed_name, $feed_url) {
196
    $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $feed_name, ':url' => $feed_url))->fetchField();
197
    return (1 == $result);
198
  }
199

    
200
  /**
201
   * Creates a valid OPML file from an array of feeds.
202
   *
203
   * @param $feeds
204
   *   An array of feeds.
205
   *
206
   * @return
207
   *   Path to valid OPML file.
208
   */
209
  function getValidOpml($feeds) {
210
    // Properly escape URLs so that XML parsers don't choke on them.
211
    foreach ($feeds as &$feed) {
212
      $feed['url'] = htmlspecialchars($feed['url']);
213
    }
214
    /**
215
     * Does not have an XML declaration, must pass the parser.
216
     */
217
    $opml = <<<EOF
218
<opml version="1.0">
219
  <head></head>
220
  <body>
221
    <!-- First feed to be imported. -->
222
    <outline text="{$feeds[0]['title']}" xmlurl="{$feeds[0]['url']}" />
223

    
224
    <!-- Second feed. Test string delimitation and attribute order. -->
225
    <outline xmlurl='{$feeds[1]['url']}' text='{$feeds[1]['title']}'/>
226

    
227
    <!-- Test for duplicate URL and title. -->
228
    <outline xmlurl="{$feeds[0]['url']}" text="Duplicate URL"/>
229
    <outline xmlurl="http://duplicate.title" text="{$feeds[1]['title']}"/>
230

    
231
    <!-- Test that feeds are only added with required attributes. -->
232
    <outline text="{$feeds[2]['title']}" />
233
    <outline xmlurl="{$feeds[2]['url']}" />
234
  </body>
235
</opml>
236
EOF;
237

    
238
    $path = 'public://valid-opml.xml';
239
    return file_unmanaged_save_data($opml, $path);
240
  }
241

    
242
  /**
243
   * Creates an invalid OPML file.
244
   *
245
   * @return
246
   *   Path to invalid OPML file.
247
   */
248
  function getInvalidOpml() {
249
    $opml = <<<EOF
250
<opml>
251
  <invalid>
252
</opml>
253
EOF;
254

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

    
259
  /**
260
   * Creates a valid but empty OPML file.
261
   *
262
   * @return
263
   *   Path to empty OPML file.
264
   */
265
  function getEmptyOpml() {
266
    $opml = <<<EOF
267
<?xml version="1.0" encoding="utf-8"?>
268
<opml version="1.0">
269
  <head></head>
270
  <body>
271
    <outline text="Sample text" />
272
    <outline text="Sample text" url="Sample URL" />
273
  </body>
274
</opml>
275
EOF;
276

    
277
    $path = 'public://empty-opml.xml';
278
    return file_unmanaged_save_data($opml, $path);
279
  }
280

    
281
  function getRSS091Sample() {
282
    return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/aggregator_test_rss091.xml';
283
  }
284

    
285
  function getAtomSample() {
286
    // The content of this sample ATOM feed is based directly off of the
287
    // example provided in RFC 4287.
288
    return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/aggregator_test_atom.xml';
289
  }
290

    
291
  function getHtmlEntitiesSample() {
292
    return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/aggregator_test_title_entities.xml';
293
  }
294

    
295
  /**
296
   * Creates sample article nodes.
297
   *
298
   * @param $count
299
   *   (optional) The number of nodes to generate. Defaults to five.
300
   */
301
  function createSampleNodes($count = 5) {
302
    $langcode = LANGUAGE_NONE;
303
    // Post $count article nodes.
304
    for ($i = 0; $i < $count; $i++) {
305
      $edit = array();
306
      $edit['title'] = $this->randomName();
307
      $edit["body[$langcode][0][value]"] = $this->randomName();
308
      $this->drupalPost('node/add/article', $edit, t('Save'));
309
    }
310
  }
311
}
312

    
313
/**
314
 * Tests functionality of the configuration settings in the Aggregator module.
315
 */
316
class AggregatorConfigurationTestCase extends AggregatorTestCase {
317
  public static function getInfo() {
318
    return array(
319
      'name' => 'Aggregator configuration',
320
      'description' => 'Test aggregator settings page.',
321
      'group' => 'Aggregator',
322
    );
323
  }
324

    
325
  /**
326
   * Tests the settings form to ensure the correct default values are used.
327
   */
328
  function testSettingsPage() {
329
    $edit = array(
330
      'aggregator_allowed_html_tags' => '<a>',
331
      'aggregator_summary_items' => 10,
332
      'aggregator_clear' => 3600,
333
      'aggregator_category_selector' => 'select',
334
      'aggregator_teaser_length' => 200,
335
    );
336
    $this->drupalPost('admin/config/services/aggregator/settings', $edit, t('Save configuration'));
337
    $this->assertText(t('The configuration options have been saved.'));
338

    
339
    foreach ($edit as $name => $value) {
340
      $this->assertFieldByName($name, $value, format_string('"@name" has correct default value.', array('@name' => $name)));
341
    }
342
  }
343
}
344

    
345
/**
346
 * Tests adding aggregator feeds.
347
 */
348
class AddFeedTestCase extends AggregatorTestCase {
349
  public static function getInfo() {
350
    return array(
351
      'name' => 'Add feed functionality',
352
      'description' => 'Add feed test.',
353
      'group' => 'Aggregator'
354
    );
355
  }
356

    
357
  /**
358
   * Creates and ensures that a feed is unique, checks source, and deletes feed.
359
   */
360
  function testAddFeed() {
361
    $feed = $this->createFeed();
362

    
363
    // Check feed data.
364
    $this->assertEqual($this->getUrl(), url('admin/config/services/aggregator/add/feed', array('absolute' => TRUE)), 'Directed to correct url.');
365
    $this->assertTrue($this->uniqueFeed($feed->title, $feed->url), 'The feed is unique.');
366

    
367
    // Check feed source.
368
    $this->drupalGet('aggregator/sources/' . $feed->fid);
369
    $this->assertResponse(200, 'Feed source exists.');
370
    $this->assertText($feed->title, 'Page title');
371
    $this->drupalGet('aggregator/sources/' . $feed->fid . '/categorize');
372
    $this->assertResponse(200, 'Feed categorization page exists.');
373

    
374
    // Delete feed.
375
    $this->deleteFeed($feed);
376
  }
377

    
378
  /**
379
   * Tests feeds with very long URLs.
380
   */
381
  function testAddLongFeed() {
382
    // Create a feed with a URL of > 255 characters.
383
    $long_url = "https://www.google.com/search?ix=heb&sourceid=chrome&ie=UTF-8&q=angie+byron#sclient=psy-ab&hl=en&safe=off&source=hp&q=angie+byron&pbx=1&oq=angie+byron&aq=f&aqi=&aql=&gs_sm=3&gs_upl=0l0l0l10534l0l0l0l0l0l0l0l0ll0l0&bav=on.2,or.r_gc.r_pw.r_cp.,cf.osb&fp=a70b6b1f0abe28d8&biw=1629&bih=889&ix=heb";
384
    $feed = $this->createFeed($long_url);
385

    
386
    // Create a second feed of > 255 characters, where the only difference is
387
    // after the 255th character.
388
    $long_url_2 = "https://www.google.com/search?ix=heb&sourceid=chrome&ie=UTF-8&q=angie+byron#sclient=psy-ab&hl=en&safe=off&source=hp&q=angie+byron&pbx=1&oq=angie+byron&aq=f&aqi=&aql=&gs_sm=3&gs_upl=0l0l0l10534l0l0l0l0l0l0l0l0ll0l0&bav=on.2,or.r_gc.r_pw.r_cp.,cf.osb&fp=a70b6b1f0abe28d8&biw=1629&bih=889";
389
    $feed_2 = $this->createFeed($long_url_2);
390

    
391
    // Check feed data.
392
    $this->assertTrue($this->uniqueFeed($feed->title, $feed->url), 'The first long URL feed is unique.');
393
    $this->assertTrue($this->uniqueFeed($feed_2->title, $feed_2->url), 'The second long URL feed is unique.');
394

    
395
    // Check feed source.
396
    $this->drupalGet('aggregator/sources/' . $feed->fid);
397
    $this->assertResponse(200, 'Long URL feed source exists.');
398
    $this->assertText($feed->title, 'Page title');
399
    $this->drupalGet('aggregator/sources/' . $feed->fid . '/categorize');
400
    $this->assertResponse(200, 'Long URL feed categorization page exists.');
401

    
402
    // Delete feeds.
403
    $this->deleteFeed($feed);
404
    $this->deleteFeed($feed_2);
405
  }
406
}
407

    
408
/**
409
 * Tests the categorize feed functionality in the Aggregator module.
410
 */
411
class CategorizeFeedTestCase extends AggregatorTestCase {
412
  public static function getInfo() {
413
    return array(
414
      'name' => 'Categorize feed functionality',
415
      'description' => 'Categorize feed test.',
416
      'group' => 'Aggregator'
417
    );
418
  }
419

    
420
  /**
421
   * Creates a feed and makes sure you can add more than one category to it.
422
   */
423
  function testCategorizeFeed() {
424

    
425
    // Create 2 categories.
426
    $category_1 = array('title' => $this->randomName(10), 'description' => '');
427
    $this->drupalPost('admin/config/services/aggregator/add/category', $category_1, t('Save'));
428
    $this->assertRaw(t('The category %title has been added.', array('%title' => $category_1['title'])), format_string('The category %title has been added.', array('%title' => $category_1['title'])));
429

    
430
    $category_2 = array('title' => $this->randomName(10), 'description' => '');
431
    $this->drupalPost('admin/config/services/aggregator/add/category', $category_2, t('Save'));
432
    $this->assertRaw(t('The category %title has been added.', array('%title' => $category_2['title'])), format_string('The category %title has been added.', array('%title' => $category_2['title'])));
433

    
434
    // Get categories from database.
435
    $categories = $this->getCategories();
436

    
437
    // Create a feed and assign 2 categories to it.
438
    $feed = $this->getFeedEditArray();
439
    $feed['block'] = 5;
440
    foreach ($categories as $cid => $category) {
441
      $feed['category'][$cid] = $cid;
442
    }
443

    
444
    // Use aggregator_save_feed() function to save the feed.
445
    aggregator_save_feed($feed);
446
    $db_feed = db_query("SELECT *  FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $feed['title'], ':url' => $feed['url']))->fetch();
447

    
448
    // Assert the feed has two categories.
449
    $this->getFeedCategories($db_feed);
450
    $this->assertEqual(count($db_feed->categories), 2, 'Feed has 2 categories');
451
  }
452
}
453

    
454
/**
455
 * Tests functionality of updating the feed in the Aggregator module.
456
 */
457
class UpdateFeedTestCase extends AggregatorTestCase {
458
  public static function getInfo() {
459
    return array(
460
      'name' => 'Update feed functionality',
461
      'description' => 'Update feed test.',
462
      'group' => 'Aggregator'
463
    );
464
  }
465

    
466
  /**
467
   * Creates a feed and attempts to update it.
468
   */
469
  function testUpdateFeed() {
470
    $remamining_fields = array('title', 'url', '');
471
    foreach ($remamining_fields as $same_field) {
472
      $feed = $this->createFeed();
473

    
474
      // Get new feed data array and modify newly created feed.
475
      $edit = $this->getFeedEditArray();
476
      $edit['refresh'] =  1800; // Change refresh value.
477
      if (isset($feed->{$same_field})) {
478
        $edit[$same_field] = $feed->{$same_field};
479
      }
480
      $this->drupalPost('admin/config/services/aggregator/edit/feed/' . $feed->fid, $edit, t('Save'));
481
      $this->assertRaw(t('The feed %name has been updated.', array('%name' => $edit['title'])), format_string('The feed %name has been updated.', array('%name' => $edit['title'])));
482

    
483
      // Check feed data.
484
      $this->assertEqual($this->getUrl(), url('admin/config/services/aggregator/', array('absolute' => TRUE)));
485
      $this->assertTrue($this->uniqueFeed($edit['title'], $edit['url']), 'The feed is unique.');
486

    
487
      // Check feed source.
488
      $this->drupalGet('aggregator/sources/' . $feed->fid);
489
      $this->assertResponse(200, 'Feed source exists.');
490
      $this->assertText($edit['title'], 'Page title');
491

    
492
      // Delete feed.
493
      $feed->title = $edit['title']; // Set correct title so deleteFeed() will work.
494
      $this->deleteFeed($feed);
495
    }
496
  }
497
}
498

    
499
/**
500
 * Tests functionality for removing feeds in the Aggregator module.
501
 */
502
class RemoveFeedTestCase extends AggregatorTestCase {
503
  public static function getInfo() {
504
    return array(
505
      'name' => 'Remove feed functionality',
506
      'description' => 'Remove feed test.',
507
      'group' => 'Aggregator'
508
    );
509
  }
510

    
511
  /**
512
   * Removes a feed and ensures that all of its services are removed.
513
   */
514
  function testRemoveFeed() {
515
    $feed = $this->createFeed();
516

    
517
    // Delete feed.
518
    $this->deleteFeed($feed);
519

    
520
    // Check feed source.
521
    $this->drupalGet('aggregator/sources/' . $feed->fid);
522
    $this->assertResponse(404, 'Deleted feed source does not exists.');
523

    
524
    // Check database for feed.
525
    $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $feed->title, ':url' => $feed->url))->fetchField();
526
    $this->assertFalse($result, 'Feed not found in database');
527
  }
528
}
529

    
530
/**
531
 * Tests functionality of updating a feed item in the Aggregator module.
532
 */
533
class UpdateFeedItemTestCase extends AggregatorTestCase {
534
  public static function getInfo() {
535
    return array(
536
      'name' => 'Update feed item functionality',
537
      'description' => 'Update feed items from a feed.',
538
      'group' => 'Aggregator'
539
    );
540
  }
541

    
542
  /**
543
   * Tests running "update items" from 'admin/config/services/aggregator' page.
544
   */
545
  function testUpdateFeedItem() {
546
    $this->createSampleNodes();
547

    
548
    // Create a feed and test updating feed items if possible.
549
    $feed = $this->createFeed();
550
    if (!empty($feed)) {
551
      $this->updateFeedItems($feed, $this->getDefaultFeedItemCount());
552
      $this->removeFeedItems($feed);
553
    }
554

    
555
    // Delete feed.
556
    $this->deleteFeed($feed);
557

    
558
    // Test updating feed items without valid timestamp information.
559
    $edit = array(
560
      'title' => "Feed without publish timestamp",
561
      'url' => $this->getRSS091Sample(),
562
    );
563

    
564
    $this->drupalGet($edit['url']);
565
    $this->assertResponse(array(200), format_string('URL !url is accessible', array('!url' => $edit['url'])));
566

    
567
    $this->drupalPost('admin/config/services/aggregator/add/feed', $edit, t('Save'));
568
    $this->assertRaw(t('The feed %name has been added.', array('%name' => $edit['title'])), format_string('The feed !name has been added.', array('!name' => $edit['title'])));
569

    
570
    $feed = db_query("SELECT * FROM {aggregator_feed} WHERE url = :url", array(':url' => $edit['url']))->fetchObject();
571

    
572
    aggregator_refresh($feed);
573
    $before = db_query('SELECT timestamp FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField();
574

    
575
    // Sleep for 3 second.
576
    sleep(3);
577
    db_update('aggregator_feed')
578
      ->condition('fid', $feed->fid)
579
      ->fields(array(
580
        'checked' => 0,
581
        'hash' => '',
582
        'etag' => '',
583
        'modified' => 0,
584
      ))
585
      ->execute();
586
    aggregator_refresh($feed);
587

    
588
    $after = db_query('SELECT timestamp FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField();
589
    $this->assertTrue($before === $after, format_string('Publish timestamp of feed item was not updated (!before === !after)', array('!before' => $before, '!after' => $after)));
590
  }
591
}
592

    
593
class RemoveFeedItemTestCase extends AggregatorTestCase {
594
  public static function getInfo() {
595
    return array(
596
      'name' => 'Remove feed item functionality',
597
      'description' => 'Remove feed items from a feed.',
598
      'group' => 'Aggregator'
599
    );
600
  }
601

    
602
  /**
603
   * Tests running "remove items" from 'admin/config/services/aggregator' page.
604
   */
605
  function testRemoveFeedItem() {
606
    // Create a bunch of test feeds.
607
    $feed_urls = array();
608
    // No last-modified, no etag.
609
    $feed_urls[] = url('aggregator/test-feed', array('absolute' => TRUE));
610
    // Last-modified, but no etag.
611
    $feed_urls[] = url('aggregator/test-feed/1', array('absolute' => TRUE));
612
    // No Last-modified, but etag.
613
    $feed_urls[] = url('aggregator/test-feed/0/1', array('absolute' => TRUE));
614
    // Last-modified and etag.
615
    $feed_urls[] = url('aggregator/test-feed/1/1', array('absolute' => TRUE));
616

    
617
    foreach ($feed_urls as $feed_url) {
618
      $feed = $this->createFeed($feed_url);
619
      // Update and remove items two times in a row to make sure that removal
620
      // resets all 'modified' information (modified, etag, hash) and allows for
621
      // immediate update.
622
      $this->updateAndRemove($feed, 4);
623
      $this->updateAndRemove($feed, 4);
624
      $this->updateAndRemove($feed, 4);
625
      // Delete feed.
626
      $this->deleteFeed($feed);
627
    }
628
  }
629
}
630

    
631
/**
632
 * Tests categorization functionality in the Aggregator module.
633
 */
634
class CategorizeFeedItemTestCase extends AggregatorTestCase {
635
  public static function getInfo() {
636
    return array(
637
      'name' => 'Categorize feed item functionality',
638
      'description' => 'Test feed item categorization.',
639
      'group' => 'Aggregator'
640
    );
641
  }
642

    
643
  /**
644
   * Checks that children of a feed inherit a defined category.
645
   *
646
   * If a feed has a category, make sure that the children inherit that
647
   * categorization.
648
   */
649
  function testCategorizeFeedItem() {
650
    $this->createSampleNodes();
651

    
652
    // Simulate form submission on "admin/config/services/aggregator/add/category".
653
    $edit = array('title' => $this->randomName(10), 'description' => '');
654
    $this->drupalPost('admin/config/services/aggregator/add/category', $edit, t('Save'));
655
    $this->assertRaw(t('The category %title has been added.', array('%title' => $edit['title'])), format_string('The category %title has been added.', array('%title' => $edit['title'])));
656

    
657
    $category = db_query("SELECT * FROM {aggregator_category} WHERE title = :title", array(':title' => $edit['title']))->fetch();
658
    $this->assertTrue(!empty($category), 'The category found in database.');
659

    
660
    $link_path = 'aggregator/categories/' . $category->cid;
661
    $menu_link = db_query("SELECT * FROM {menu_links} WHERE link_path = :link_path", array(':link_path' => $link_path))->fetch();
662
    $this->assertTrue(!empty($menu_link), 'The menu link associated with the category found in database.');
663

    
664
    $feed = $this->createFeed();
665
    db_insert('aggregator_category_feed')
666
      ->fields(array(
667
        'cid' => $category->cid,
668
        'fid' => $feed->fid,
669
      ))
670
      ->execute();
671
    $this->updateFeedItems($feed, $this->getDefaultFeedItemCount());
672
    $this->getFeedCategories($feed);
673
    $this->assertTrue(!empty($feed->categories), 'The category found in the feed.');
674

    
675
    // For each category of a feed, ensure feed items have that category, too.
676
    if (!empty($feed->categories) && !empty($feed->items)) {
677
      foreach ($feed->categories as $category) {
678
        $categorized_count = db_select('aggregator_category_item')
679
          ->condition('iid', $feed->items, 'IN')
680
          ->countQuery()
681
          ->execute()
682
          ->fetchField();
683

    
684
        $this->assertEqual($feed->item_count, $categorized_count, 'Total items in feed equal to the total categorized feed items in database');
685
      }
686
    }
687

    
688
    // Delete feed.
689
    $this->deleteFeed($feed);
690
  }
691
}
692

    
693
/**
694
 * Tests importing feeds from OPML functionality for the Aggregator module.
695
 */
696
class ImportOPMLTestCase extends AggregatorTestCase {
697
  public static function getInfo() {
698
    return array(
699
      'name' => 'Import feeds from OPML functionality',
700
      'description' => 'Test OPML import.',
701
      'group' => 'Aggregator',
702
    );
703
  }
704

    
705
  /**
706
   * Opens OPML import form.
707
   */
708
  function openImportForm() {
709
    db_delete('aggregator_category')->execute();
710

    
711
    $category = $this->randomName(10);
712
    $cid = db_insert('aggregator_category')
713
      ->fields(array(
714
        'title' => $category,
715
        'description' => '',
716
      ))
717
      ->execute();
718

    
719
    $this->drupalGet('admin/config/services/aggregator/add/opml');
720
    $this->assertText('A single OPML document may contain a collection of many feeds.', 'Found OPML help text.');
721
    $this->assertField('files[upload]', 'Found file upload field.');
722
    $this->assertField('remote', 'Found Remote URL field.');
723
    $this->assertField('refresh', 'Found Refresh field.');
724
    $this->assertFieldByName("category[$cid]", $cid, 'Found category field.');
725
  }
726

    
727
  /**
728
   * Submits form filled with invalid fields.
729
   */
730
  function validateImportFormFields() {
731
    $before = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
732

    
733
    $edit = array();
734
    $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
735
    $this->assertRaw(t('You must <em>either</em> upload a file or enter a URL.'), 'Error if no fields are filled.');
736

    
737
    $path = $this->getEmptyOpml();
738
    $edit = array(
739
      'files[upload]' => $path,
740
      'remote' => file_create_url($path),
741
    );
742
    $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
743
    $this->assertRaw(t('You must <em>either</em> upload a file or enter a URL.'), 'Error if both fields are filled.');
744

    
745
    $edit = array('remote' => 'invalidUrl://empty');
746
    $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
747
    $this->assertText(t('This URL is not valid.'), 'Error if the URL is invalid.');
748

    
749
    $after = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
750
    $this->assertEqual($before, $after, 'No feeds were added during the three last form submissions.');
751
  }
752

    
753
  /**
754
   * Submits form with invalid, empty, and valid OPML files.
755
   */
756
  function submitImportForm() {
757
    $before = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
758

    
759
    $form['files[upload]'] = $this->getInvalidOpml();
760
    $this->drupalPost('admin/config/services/aggregator/add/opml', $form, t('Import'));
761
    $this->assertText(t('No new feed has been added.'), 'Attempting to upload invalid XML.');
762

    
763
    $edit = array('remote' => file_create_url($this->getEmptyOpml()));
764
    $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
765
    $this->assertText(t('No new feed has been added.'), 'Attempting to load empty OPML from remote URL.');
766

    
767
    $after = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
768
    $this->assertEqual($before, $after, 'No feeds were added during the two last form submissions.');
769

    
770
    db_delete('aggregator_feed')->execute();
771
    db_delete('aggregator_category')->execute();
772
    db_delete('aggregator_category_feed')->execute();
773

    
774
    $category = $this->randomName(10);
775
    db_insert('aggregator_category')
776
      ->fields(array(
777
        'cid' => 1,
778
        'title' => $category,
779
        'description' => '',
780
      ))
781
      ->execute();
782

    
783
    $feeds[0] = $this->getFeedEditArray();
784
    $feeds[1] = $this->getFeedEditArray();
785
    $feeds[2] = $this->getFeedEditArray();
786
    $edit = array(
787
      'files[upload]' => $this->getValidOpml($feeds),
788
      'refresh'       => '900',
789
      'category[1]'   => $category,
790
    );
791
    $this->drupalPost('admin/config/services/aggregator/add/opml', $edit, t('Import'));
792
    $this->assertRaw(t('A feed with the URL %url already exists.', array('%url' => $feeds[0]['url'])), 'Verifying that a duplicate URL was identified');
793
    $this->assertRaw(t('A feed named %title already exists.', array('%title' => $feeds[1]['title'])), 'Verifying that a duplicate title was identified');
794

    
795
    $after = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
796
    $this->assertEqual($after, 2, 'Verifying that two distinct feeds were added.');
797

    
798
    $feeds_from_db = db_query("SELECT f.title, f.url, f.refresh, cf.cid FROM {aggregator_feed} f LEFT JOIN {aggregator_category_feed} cf ON f.fid = cf.fid");
799
    $refresh = $category = TRUE;
800
    foreach ($feeds_from_db as $feed) {
801
      $title[$feed->url] = $feed->title;
802
      $url[$feed->title] = $feed->url;
803
      $category = $category && $feed->cid == 1;
804
      $refresh = $refresh && $feed->refresh == 900;
805
    }
806

    
807
    $this->assertEqual($title[$feeds[0]['url']], $feeds[0]['title'], 'First feed was added correctly.');
808
    $this->assertEqual($url[$feeds[1]['title']], $feeds[1]['url'], 'Second feed was added correctly.');
809
    $this->assertTrue($refresh, 'Refresh times are correct.');
810
    $this->assertTrue($category, 'Categories are correct.');
811
  }
812

    
813
  /**
814
   * Tests the import of an OPML file.
815
   */
816
  function testOPMLImport() {
817
    $this->openImportForm();
818
    $this->validateImportFormFields();
819
    $this->submitImportForm();
820
  }
821
}
822

    
823
/**
824
 * Tests functionality of the cron process in the Aggregator module.
825
 */
826
class AggregatorCronTestCase extends AggregatorTestCase {
827
  public static function getInfo() {
828
    return array(
829
      'name' => 'Update on cron functionality',
830
      'description' => 'Update feeds on cron.',
831
      'group' => 'Aggregator'
832
    );
833
  }
834

    
835
  /**
836
   * Adds feeds and updates them via cron process.
837
   */
838
  public function testCron() {
839
    // Create feed and test basic updating on cron.
840
    global $base_url;
841
    $key = variable_get('cron_key', 'drupal');
842
    $this->createSampleNodes();
843
    $feed = $this->createFeed();
844
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
845
    $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
846
    $this->removeFeedItems($feed);
847
    $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
848
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
849
    $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
850

    
851
    // Test feed locking when queued for update.
852
    $this->removeFeedItems($feed);
853
    db_update('aggregator_feed')
854
      ->condition('fid', $feed->fid)
855
      ->fields(array(
856
        'queued' => REQUEST_TIME,
857
      ))
858
      ->execute();
859
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
860
    $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
861
    db_update('aggregator_feed')
862
      ->condition('fid', $feed->fid)
863
      ->fields(array(
864
        'queued' => 0,
865
      ))
866
      ->execute();
867
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
868
    $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->fid))->fetchField(), 'Expected number of items in database.');
869
  }
870
}
871

    
872
/**
873
 * Tests rendering functionality in the Aggregator module.
874
 */
875
class AggregatorRenderingTestCase extends AggregatorTestCase {
876
  public static function getInfo() {
877
    return array(
878
      'name' => 'Checks display of aggregator items',
879
      'description' => 'Checks display of aggregator items on the page.',
880
      'group' => 'Aggregator'
881
    );
882
  }
883

    
884
  /**
885
   * Adds a feed block to the page and checks its links.
886
   *
887
   * @todo Test the category block as well.
888
   */
889
  public function testBlockLinks() {
890
    // Create feed.
891
    $this->createSampleNodes();
892
    $feed = $this->createFeed();
893
    $this->updateFeedItems($feed, $this->getDefaultFeedItemCount());
894

    
895
    // Place block on page (@see block.test:moveBlockToRegion())
896
    // Need admin user to be able to access block admin.
897
    $this->admin_user = $this->drupalCreateUser(array(
898
      'administer blocks',
899
      'access administration pages',
900
      'administer news feeds',
901
      'access news feeds',
902
    ));
903
    $this->drupalLogin($this->admin_user);
904

    
905
    // Prepare to use the block admin form.
906
    $block = array(
907
      'module' => 'aggregator',
908
      'delta' => 'feed-' . $feed->fid,
909
      'title' => $feed->title,
910
    );
911
    $region = 'footer';
912
    $edit = array();
913
    $edit['blocks[' . $block['module'] . '_' . $block['delta'] . '][region]'] = $region;
914
    // Check the feed block is available in the block list form.
915
    $this->drupalGet('admin/structure/block');
916
    $this->assertFieldByName('blocks[' . $block['module'] . '_' . $block['delta'] . '][region]', '', 'Aggregator feed block is available for positioning.');
917
    // Position it.
918
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
919
    $this->assertText(t('The block settings have been updated.'), format_string('Block successfully moved to %region_name region.', array( '%region_name' => $region)));
920
    // Confirm that the block is now being displayed on pages.
921
    $this->drupalGet('node');
922
    $this->assertText(t($block['title']), 'Feed block is displayed on the page.');
923

    
924
    // Find the expected read_more link.
925
    $href = 'aggregator/sources/' . $feed->fid;
926
    $links = $this->xpath('//a[@href = :href]', array(':href' => url($href)));
927
    $this->assert(isset($links[0]), format_string('Link to href %href found.', array('%href' => $href)));
928

    
929
    // Visit that page.
930
    $this->drupalGet($href);
931
    $correct_titles = $this->xpath('//h1[normalize-space(text())=:title]', array(':title' => $feed->title));
932
    $this->assertFalse(empty($correct_titles), 'Aggregator feed page is available and has the correct title.');
933

    
934
    // Set the number of news items to 0 to test that the block does not show
935
    // up.
936
    $feed->block = 0;
937
    aggregator_save_feed((array) $feed);
938
    // It is necessary to flush the cache after saving the number of items.
939
    drupal_flush_all_caches();
940
    // Check that the block is no longer displayed.
941
    $this->drupalGet('node');
942
    $this->assertNoText(t($block['title']), 'Feed block is not displayed on the page when number of items is set to 0.');
943
  }
944

    
945
  /**
946
   * Creates a feed and checks that feed's page.
947
   */
948
  public function testFeedPage() {
949
    // Increase the number of items published in the rss.xml feed so we have
950
    // enough articles to test paging.
951
    variable_set('feed_default_items', 30);
952

    
953
    // Create a feed with 30 items.
954
    $this->createSampleNodes(30);
955
    $feed = $this->createFeed();
956
    $this->updateFeedItems($feed, 30);
957

    
958
    // Check for the presence of a pager.
959
    $this->drupalGet('aggregator/sources/' . $feed->fid);
960
    $elements = $this->xpath("//ul[@class=:class]", array(':class' => 'pager'));
961
    $this->assertTrue(!empty($elements), 'Individual source page contains a pager.');
962

    
963
    // Reset the number of items in rss.xml to the default value.
964
    variable_set('feed_default_items', 10);
965
  }
966
}
967

    
968
/**
969
 * Tests feed parsing in the Aggregator module.
970
 */
971
class FeedParserTestCase extends AggregatorTestCase {
972
  public static function getInfo() {
973
    return array(
974
      'name' => 'Feed parser functionality',
975
      'description' => 'Test the built-in feed parser with valid feed samples.',
976
      'group' => 'Aggregator',
977
    );
978
  }
979

    
980
  function setUp() {
981
    parent::setUp();
982
    // Do not remove old aggregator items during these tests, since our sample
983
    // feeds have hardcoded dates in them (which may be expired when this test
984
    // is run).
985
    variable_set('aggregator_clear', AGGREGATOR_CLEAR_NEVER);
986
  }
987

    
988
  /**
989
   * Tests a feed that uses the RSS 0.91 format.
990
   */
991
  function testRSS091Sample() {
992
    $feed = $this->createFeed($this->getRSS091Sample());
993
    aggregator_refresh($feed);
994
    $this->drupalGet('aggregator/sources/' . $feed->fid);
995
    $this->assertResponse(200, format_string('Feed %name exists.', array('%name' => $feed->title)));
996
    $this->assertText('First example feed item title');
997
    $this->assertLinkByHref('http://example.com/example-turns-one');
998
    $this->assertText('First example feed item description.');
999

    
1000
    // Several additional items that include elements over 255 characters.
1001
    $this->assertRaw("Second example feed item title.");
1002
    $this->assertText('Long link feed item title');
1003
    $this->assertText('Long link feed item description');
1004
    $this->assertLinkByHref('http://example.com/tomorrow/and/tomorrow/and/tomorrow/creeps/in/this/petty/pace/from/day/to/day/to/the/last/syllable/of/recorded/time/and/all/our/yesterdays/have/lighted/fools/the/way/to/dusty/death/out/out/brief/candle/life/is/but/a/walking/shadow/a/poor/player/that/struts/and/frets/his/hour/upon/the/stage/and/is/heard/no/more/it/is/a/tale/told/by/an/idiot/full/of/sound/and/fury/signifying/nothing');
1005
    $this->assertText('Long author feed item title');
1006
    $this->assertText('Long author feed item description');
1007
    $this->assertLinkByHref('http://example.com/long/author');
1008
  }
1009

    
1010
  /**
1011
   * Tests a feed that uses the Atom format.
1012
   */
1013
  function testAtomSample() {
1014
    $feed = $this->createFeed($this->getAtomSample());
1015
    aggregator_refresh($feed);
1016
    $this->drupalGet('aggregator/sources/' . $feed->fid);
1017
    $this->assertResponse(200, format_string('Feed %name exists.', array('%name' => $feed->title)));
1018
    $this->assertText('Atom-Powered Robots Run Amok');
1019
    $this->assertLinkByHref('http://example.org/2003/12/13/atom03');
1020
    $this->assertText('Some text.');
1021
    $this->assertEqual('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a', db_query('SELECT guid FROM {aggregator_item} WHERE link = :link', array(':link' => 'http://example.org/2003/12/13/atom03'))->fetchField(), 'Atom entry id element is parsed correctly.');
1022
  }
1023

    
1024
  /**
1025
   * Tests a feed that uses HTML entities in item titles.
1026
   */
1027
  function testHtmlEntitiesSample() {
1028
    $feed = $this->createFeed($this->getHtmlEntitiesSample());
1029
    aggregator_refresh($feed);
1030
    $this->drupalGet('aggregator/sources/' . $feed->fid);
1031
    $this->assertResponse(200, format_string('Feed %name exists.', array('%name' => $feed->title)));
1032
    $this->assertRaw("Quote&quot; Amp&amp;");
1033
  }
1034
}