Projet

Général

Profil

Paste
Télécharger (37,5 ko) Statistiques
| Branche: | Révision:

root / htmltest / modules / aggregator / aggregator.test @ 85ad3d82

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

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

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

    
335
    foreach ($edit as $name => $value) {
336
      $this->assertFieldByName($name, $value, format_string('"@name" has correct default value.', array('@name' => $name)));
337
    }
338
  }
339
}
340

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

    
353
  /**
354
   * Creates and ensures that a feed is unique, checks source, and deletes feed.
355
   */
356
  function testAddFeed() {
357
    $feed = $this->createFeed();
358

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

    
363
    // Check feed source.
364
    $this->drupalGet('aggregator/sources/' . $feed->fid);
365
    $this->assertResponse(200, 'Feed source exists.');
366
    $this->assertText($feed->title, 'Page title');
367
    $this->drupalGet('aggregator/sources/' . $feed->fid . '/categorize');
368
    $this->assertResponse(200, 'Feed categorization page exists.');
369

    
370
    // Delete feed.
371
    $this->deleteFeed($feed);
372
  }
373

    
374
  /**
375
   * Tests feeds with very long URLs.
376
   */
377
  function testAddLongFeed() {
378
    // Create a feed with a URL of > 255 characters.
379
    $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";
380
    $feed = $this->createFeed($long_url);
381

    
382
    // Create a second feed of > 255 characters, where the only difference is
383
    // after the 255th character.
384
    $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";
385
    $feed_2 = $this->createFeed($long_url_2);
386

    
387
    // Check feed data.
388
    $this->assertTrue($this->uniqueFeed($feed->title, $feed->url), 'The first long URL feed is unique.');
389
    $this->assertTrue($this->uniqueFeed($feed_2->title, $feed_2->url), 'The second long URL feed is unique.');
390

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

    
398
    // Delete feeds.
399
    $this->deleteFeed($feed);
400
    $this->deleteFeed($feed_2);
401
  }
402
}
403

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

    
416
  /**
417
   * Creates a feed and makes sure you can add more than one category to it.
418
   */
419
  function testCategorizeFeed() {
420

    
421
    // Create 2 categories.
422
    $category_1 = array('title' => $this->randomName(10), 'description' => '');
423
    $this->drupalPost('admin/config/services/aggregator/add/category', $category_1, t('Save'));
424
    $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'])));
425

    
426
    $category_2 = array('title' => $this->randomName(10), 'description' => '');
427
    $this->drupalPost('admin/config/services/aggregator/add/category', $category_2, t('Save'));
428
    $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'])));
429

    
430
    // Get categories from database.
431
    $categories = $this->getCategories();
432

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

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

    
444
    // Assert the feed has two categories.
445
    $this->getFeedCategories($db_feed);
446
    $this->assertEqual(count($db_feed->categories), 2, 'Feed has 2 categories');
447
  }
448
}
449

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

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

    
470
      // Get new feed data array and modify newly created feed.
471
      $edit = $this->getFeedEditArray();
472
      $edit['refresh'] =  1800; // Change refresh value.
473
      if (isset($feed->{$same_field})) {
474
        $edit[$same_field] = $feed->{$same_field};
475
      }
476
      $this->drupalPost('admin/config/services/aggregator/edit/feed/' . $feed->fid, $edit, t('Save'));
477
      $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'])));
478

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

    
483
      // Check feed source.
484
      $this->drupalGet('aggregator/sources/' . $feed->fid);
485
      $this->assertResponse(200, 'Feed source exists.');
486
      $this->assertText($edit['title'], 'Page title');
487

    
488
      // Delete feed.
489
      $feed->title = $edit['title']; // Set correct title so deleteFeed() will work.
490
      $this->deleteFeed($feed);
491
    }
492
  }
493
}
494

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

    
507
  /**
508
   * Removes a feed and ensures that all of its services are removed.
509
   */
510
  function testRemoveFeed() {
511
    $feed = $this->createFeed();
512

    
513
    // Delete feed.
514
    $this->deleteFeed($feed);
515

    
516
    // Check feed source.
517
    $this->drupalGet('aggregator/sources/' . $feed->fid);
518
    $this->assertResponse(404, 'Deleted feed source does not exists.');
519

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

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

    
538
  /**
539
   * Tests running "update items" from 'admin/config/services/aggregator' page.
540
   */
541
  function testUpdateFeedItem() {
542
    $this->createSampleNodes();
543

    
544
    // Create a feed and test updating feed items if possible.
545
    $feed = $this->createFeed();
546
    if (!empty($feed)) {
547
      $this->updateFeedItems($feed, $this->getDefaultFeedItemCount());
548
      $this->removeFeedItems($feed);
549
    }
550

    
551
    // Delete feed.
552
    $this->deleteFeed($feed);
553

    
554
    // Test updating feed items without valid timestamp information.
555
    $edit = array(
556
      'title' => "Feed without publish timestamp",
557
      'url' => $this->getRSS091Sample(),
558
    );
559

    
560
    $this->drupalGet($edit['url']);
561
    $this->assertResponse(array(200), format_string('URL !url is accessible', array('!url' => $edit['url'])));
562

    
563
    $this->drupalPost('admin/config/services/aggregator/add/feed', $edit, t('Save'));
564
    $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'])));
565

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

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

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

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

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

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

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

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

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

    
648
    // Simulate form submission on "admin/config/services/aggregator/add/category".
649
    $edit = array('title' => $this->randomName(10), 'description' => '');
650
    $this->drupalPost('admin/config/services/aggregator/add/category', $edit, t('Save'));
651
    $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'])));
652

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

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

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

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

    
680
        $this->assertEqual($feed->item_count, $categorized_count, 'Total items in feed equal to the total categorized feed items in database');
681
      }
682
    }
683

    
684
    // Delete feed.
685
    $this->deleteFeed($feed);
686
  }
687
}
688

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

    
701
  /**
702
   * Opens OPML import form.
703
   */
704
  function openImportForm() {
705
    db_delete('aggregator_category')->execute();
706

    
707
    $category = $this->randomName(10);
708
    $cid = db_insert('aggregator_category')
709
      ->fields(array(
710
        'title' => $category,
711
        'description' => '',
712
      ))
713
      ->execute();
714

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

    
723
  /**
724
   * Submits form filled with invalid fields.
725
   */
726
  function validateImportFormFields() {
727
    $before = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField();
728

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

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

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

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

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

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

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

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

    
766
    db_delete('aggregator_feed')->execute();
767
    db_delete('aggregator_category')->execute();
768
    db_delete('aggregator_category_feed')->execute();
769

    
770
    $category = $this->randomName(10);
771
    db_insert('aggregator_category')
772
      ->fields(array(
773
        'cid' => 1,
774
        'title' => $category,
775
        'description' => '',
776
      ))
777
      ->execute();
778

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

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

    
794
    $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");
795
    $refresh = $category = TRUE;
796
    foreach ($feeds_from_db as $feed) {
797
      $title[$feed->url] = $feed->title;
798
      $url[$feed->title] = $feed->url;
799
      $category = $category && $feed->cid == 1;
800
      $refresh = $refresh && $feed->refresh == 900;
801
    }
802

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

    
809
  /**
810
   * Tests the import of an OPML file.
811
   */
812
  function testOPMLImport() {
813
    $this->openImportForm();
814
    $this->validateImportFormFields();
815
    $this->submitImportForm();
816
  }
817
}
818

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

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

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

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

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

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

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

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

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

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

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

    
949
    // Create a feed with 30 items.
950
    $this->createSampleNodes(30);
951
    $feed = $this->createFeed();
952
    $this->updateFeedItems($feed, 30);
953

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

    
959
    // Reset the number of items in rss.xml to the default value.
960
    variable_set('feed_default_items', 10);
961
  }
962
}
963

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

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

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

    
996
    // Several additional items that include elements over 255 characters.
997
    $this->assertRaw("Second example feed item title.");
998
    $this->assertText('Long link feed item title');
999
    $this->assertText('Long link feed item description');
1000
    $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');
1001
    $this->assertText('Long author feed item title');
1002
    $this->assertText('Long author feed item description');
1003
    $this->assertLinkByHref('http://example.com/long/author');
1004
  }
1005

    
1006
  /**
1007
   * Tests a feed that uses the Atom format.
1008
   */
1009
  function testAtomSample() {
1010
    $feed = $this->createFeed($this->getAtomSample());
1011
    aggregator_refresh($feed);
1012
    $this->drupalGet('aggregator/sources/' . $feed->fid);
1013
    $this->assertResponse(200, format_string('Feed %name exists.', array('%name' => $feed->title)));
1014
    $this->assertText('Atom-Powered Robots Run Amok');
1015
    $this->assertLinkByHref('http://example.org/2003/12/13/atom03');
1016
    $this->assertText('Some text.');
1017
    $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.');
1018
  }
1019
}