Projet

Général

Profil

Paste
Télécharger (23,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / feeds / tests / feeds.test @ 651307cd

1
<?php
2

    
3
/**
4
 * @file
5
 * Common functionality for all Feeds tests.
6
 */
7

    
8
/**
9
 * Test basic Data API functionality.
10
 */
11
class FeedsWebTestCase extends DrupalWebTestCase {
12
  protected $profile = 'testing';
13

    
14
  public function setUp() {
15
    $args = func_get_args();
16

    
17
    // Build the list of required modules which can be altered by passing in an
18
    // array of module names to setUp().
19
    if (isset($args[0])) {
20
      if (is_array($args[0])) {
21
        $modules = $args[0];
22
      }
23
      else {
24
        $modules = $args;
25
      }
26
    }
27
    else {
28
      $modules = array();
29
    }
30

    
31
    $modules[] = 'taxonomy';
32
    $modules[] = 'image';
33
    $modules[] = 'file';
34
    $modules[] = 'field';
35
    $modules[] = 'field_ui';
36
    $modules[] = 'feeds';
37
    $modules[] = 'feeds_ui';
38
    $modules[] = 'feeds_tests';
39
    $modules[] = 'ctools';
40
    $modules[] = 'job_scheduler';
41
    $modules = array_unique($modules);
42
    parent::setUp($modules);
43

    
44
    // Add text formats Directly.
45
    $filtered_html_format = array(
46
      'format' => 'filtered_html',
47
      'name' => 'Filtered HTML',
48
      'weight' => 0,
49
      'filters' => array(
50
        // URL filter.
51
        'filter_url' => array(
52
          'weight' => 0,
53
          'status' => 1,
54
        ),
55
        // HTML filter.
56
        'filter_html' => array(
57
          'weight' => 1,
58
          'status' => 1,
59
        ),
60
        // Line break filter.
61
        'filter_autop' => array(
62
          'weight' => 2,
63
          'status' => 1,
64
        ),
65
        // HTML corrector filter.
66
        'filter_htmlcorrector' => array(
67
          'weight' => 10,
68
          'status' => 1,
69
        ),
70
      ),
71
    );
72
    $filtered_html_format = (object) $filtered_html_format;
73
    filter_format_save($filtered_html_format);
74

    
75
    // Build the list of required administration permissions. Additional
76
    // permissions can be passed as an array into setUp()'s second parameter.
77
    if (isset($args[1]) && is_array($args[1])) {
78
      $permissions = $args[1];
79
    }
80
    else {
81
      $permissions = array();
82
    }
83

    
84
    $permissions[] = 'access content';
85
    $permissions[] = 'administer site configuration';
86
    $permissions[] = 'administer content types';
87
    $permissions[] = 'administer nodes';
88
    $permissions[] = 'bypass node access';
89
    $permissions[] = 'administer taxonomy';
90
    $permissions[] = 'administer users';
91
    $permissions[] = 'administer feeds';
92
    $permissions[] = 'administer filters';
93
    $permissions[] = 'administer fields';
94

    
95
    // Create an admin user and log in.
96
    $this->admin_user = $this->drupalCreateUser($permissions);
97
    $this->drupalLogin($this->admin_user);
98

    
99
    $types = array(
100
      array(
101
        'type' => 'page',
102
        'name' => 'Basic page',
103
        'node_options[status]' => 1,
104
        'node_options[promote]' => 0,
105
      ),
106
      array(
107
        'type' => 'article',
108
        'name' => 'Article',
109
        'node_options[status]' => 1,
110
        'node_options[promote]' => 1,
111
      ),
112
    );
113
    foreach ($types as $type) {
114
      $this->drupalPost('admin/structure/types/add', $type, 'Save content type');
115
      $this->assertText("The content type " . $type['name'] . " has been added.");
116
    }
117
  }
118

    
119
  /**
120
   * Absolute path to Drupal root.
121
   */
122
  public function absolute() {
123
    return realpath(getcwd());
124
  }
125

    
126
  /**
127
   * Get the absolute directory path of the feeds module.
128
   */
129
  public function absolutePath() {
130
    return  $this->absolute() . '/' . drupal_get_path('module', 'feeds');
131
  }
132

    
133
  /**
134
   * Generate an OPML test feed.
135
   *
136
   * The purpose of this function is to create a dynamic OPML feed that points
137
   * to feeds included in this test.
138
   */
139
  public function generateOPML() {
140
    $path = $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'feeds') . '/tests/feeds/';
141

    
142
  $output =
143
'<?xml version="1.0" encoding="utf-8"?>
144
<opml version="1.1">
145
<head>
146
    <title>Feeds test OPML</title>
147
    <dateCreated>Fri, 16 Oct 2009 02:53:17 GMT</dateCreated>
148
    <ownerName></ownerName>
149
</head>
150
<body>
151
  <outline text="Feeds test group" >
152
    <outline title="Development Seed - Technological Solutions for Progressive Organizations" text="" xmlUrl="' . $path . 'developmentseed.rss2" type="rss" />
153
    <outline title="Magyar Nemzet Online - H\'rek" text="" xmlUrl="' . $path . 'feed_without_guid.rss2" type="rss" />
154
    <outline title="Drupal planet" text="" type="rss" xmlUrl="' . $path . 'drupalplanet.rss2" />
155
  </outline>
156
</body>
157
</opml>';
158

    
159
    // UTF 8 encode output string and write it to disk
160
    $output = utf8_encode($output);
161
    $filename = file_default_scheme() . '://test-opml-' . $this->randomName() . '.opml';
162

    
163
    $filename = file_unmanaged_save_data($output, $filename);
164
    return $filename;
165
  }
166

    
167
  /**
168
   * Create an importer configuration.
169
   *
170
   * @param $name
171
   *   The natural name of the feed.
172
   * @param $id
173
   *   The persistent id of the feed.
174
   * @param $edit
175
   *   Optional array that defines the basic settings for the feed in a format
176
   *   that can be posted to the feed's basic settings form.
177
   */
178
  public function createImporterConfiguration($name = 'Syndication', $id = 'syndication') {
179
    // Create new feed configuration.
180
    $this->drupalGet('admin/structure/feeds');
181
    $this->clickLink('Add importer');
182
    $edit = array(
183
      'name' => $name,
184
      'id' => $id,
185
    );
186
    $this->drupalPost('admin/structure/feeds/create', $edit, 'Create');
187

    
188
    // Assert message and presence of default plugins.
189
    $this->assertText('Your configuration has been created with default settings.');
190
    $this->assertPlugins($id, 'FeedsHTTPFetcher', 'FeedsSyndicationParser', 'FeedsNodeProcessor');
191
    // Per default attach to page content type.
192
    $this->setSettings($id, NULL, array('content_type' => 'page'));
193
    // Per default attached to article content type.
194
    $this->setSettings($id, 'FeedsNodeProcessor', array('bundle' => 'article'));
195
  }
196

    
197
  /**
198
   * Choose a plugin for a importer configuration and assert it.
199
   *
200
   * @param $id
201
   *   The importer configuration's id.
202
   * @param $plugin_key
203
   *   The key string of the plugin to choose (one of the keys defined in
204
   *   feeds_feeds_plugins()).
205
   */
206
  public function setPlugin($id, $plugin_key) {
207
    if ($type = FeedsPlugin::typeOf($plugin_key)) {
208
      $edit = array(
209
        'plugin_key' => $plugin_key,
210
      );
211
      $this->drupalPost("admin/structure/feeds/$id/$type", $edit, 'Save');
212

    
213
      // Assert actual configuration.
214
      $config = unserialize(db_query("SELECT config FROM {feeds_importer} WHERE id = :id", array(':id' => $id))->fetchField());
215
      $this->assertEqual($config[$type]['plugin_key'], $plugin_key, 'Verified correct ' . $type . ' (' . $plugin_key . ').');
216
    }
217
  }
218

    
219
  /**
220
   * Set importer or plugin settings.
221
   *
222
   * @param $id
223
   *   The importer configuration's id.
224
   * @param $plugin
225
   *   The plugin (class) name, or NULL to set importer's settings
226
   * @param $settings
227
   *   The settings to set.
228
   */
229
  public function setSettings($id, $plugin, $settings) {
230
    $this->drupalPost('admin/structure/feeds/' . $id . '/settings/' . $plugin, $settings, 'Save');
231
    $this->assertText('Your changes have been saved.');
232
  }
233

    
234
  /**
235
   * Create a test feed node. Test user has to have sufficient permissions:
236
   *
237
   * * create [type] content
238
   * * use feeds
239
   *
240
   * Assumes that page content type has been configured with
241
   * createImporterConfiguration() as a feed content type.
242
   *
243
   * @return
244
   *   The node id of the node created.
245
   */
246
  public function createFeedNode($id = 'syndication', $feed_url = NULL, $title = '', $content_type = NULL) {
247
    if (empty($feed_url)) {
248
      $feed_url = $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'feeds') . '/tests/feeds/developmentseed.rss2';
249
    }
250

    
251
    // If content type not given, retrieve it.
252
    if (!$content_type) {
253
      $result= db_select('feeds_importer', 'f')
254
        ->condition('f.id', $id, '=')
255
        ->fields('f', array('config'))
256
        ->execute();
257
      $config = unserialize($result->fetchField());
258
      $content_type = $config['content_type'];
259
      $this->assertFalse(empty($content_type), 'Valid content type found: ' . $content_type);
260
    }
261

    
262
    // Create a feed node.
263
    $edit = array(
264
      'title' => $title,
265
      'feeds[FeedsHTTPFetcher][source]' => $feed_url,
266
    );
267
    $this->drupalPost('node/add/' . str_replace('_', '-', $content_type), $edit, 'Save');
268
    $this->assertText('has been created.');
269

    
270
    // Get the node id from URL.
271
    $nid = $this->getNid($this->getUrl());
272

    
273
    // Check whether feed got recorded in feeds_source table.
274
    $query = db_select('feeds_source', 's')
275
      ->condition('s.id', $id, '=')
276
      ->condition('s.feed_nid', $nid, '=');
277
    $query->addExpression("COUNT(*)");
278
    $result = $query->execute()->fetchField();
279
    $this->assertEqual(1, $result);
280

    
281
    $source = db_select('feeds_source', 's')
282
      ->condition('s.id', $id, '=')
283
      ->condition('s.feed_nid', $nid, '=')
284
      ->fields('s', array('config'))
285
      ->execute()->fetchObject();
286
    $config = unserialize($source->config);
287
    $this->assertEqual($config['FeedsHTTPFetcher']['source'], $feed_url, t('URL in DB correct.'));
288
    return $nid;
289
  }
290

    
291
  /**
292
   * Edit the configuration of a feed node to test update behavior.
293
   *
294
   * @param $nid
295
   *   The nid to edit.
296
   * @param $feed_url
297
   *   The new (absolute) feed URL to use.
298
   * @param $title
299
   *   Optional parameter to change title of feed node.
300
   */
301
  public function editFeedNode($nid, $feed_url, $title = '') {
302
    $edit = array(
303
      'title' => $title,
304
      'feeds[FeedsHTTPFetcher][source]' => $feed_url,
305
    );
306
    // Check that the update was saved.
307
    $this->drupalPost('node/' . $nid . '/edit', $edit, 'Save');
308
    $this->assertText('has been updated.');
309

    
310
    // Check that the URL was updated in the feeds_source table.
311
    $source = db_query("SELECT * FROM {feeds_source} WHERE feed_nid = :nid", array(':nid' => $nid))->fetchObject();
312
    $config = unserialize($source->config);
313
    $this->assertEqual($config['FeedsHTTPFetcher']['source'], $feed_url, t('URL in DB correct.'));
314
  }
315

    
316
  /**
317
   * Batch create a variable amount of feed nodes. All will have the
318
   * same URL configured.
319
   *
320
   * @return
321
   *   An array of node ids of the nodes created.
322
   */
323
  public function createFeedNodes($id = 'syndication', $num = 20, $content_type = NULL) {
324
    $nids = array();
325
    for ($i = 0; $i < $num; $i++) {
326
      $nids[] = $this->createFeedNode($id, NULL, $this->randomName(), $content_type);
327
    }
328
    return $nids;
329
  }
330

    
331
  /**
332
   * Import a URL through the import form. Assumes FeedsHTTPFetcher in place.
333
   */
334
  public function importURL($id, $feed_url = NULL) {
335
    if (empty($feed_url)) {
336
      $feed_url = $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'feeds') . '/tests/feeds/developmentseed.rss2';
337
    }
338
    $edit = array(
339
      'feeds[FeedsHTTPFetcher][source]' => $feed_url,
340
    );
341
    $nid = $this->drupalPost('import/' . $id, $edit, 'Import');
342

    
343
    // Check whether feed got recorded in feeds_source table.
344
    $this->assertEqual(1, db_query("SELECT COUNT(*) FROM {feeds_source} WHERE id = :id AND feed_nid = 0", array(':id' => $id))->fetchField());
345
    $source = db_query("SELECT * FROM {feeds_source} WHERE id = :id AND feed_nid = 0",  array(':id' => $id))->fetchObject();
346
    $config = unserialize($source->config);
347
    $this->assertEqual($config['FeedsHTTPFetcher']['source'], $feed_url, t('URL in DB correct.'));
348

    
349
    // Check whether feed got properly added to scheduler.
350
    $this->assertEqual(1, db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = :id AND id = 0 AND name = 'feeds_source_import' AND last <> 0 AND scheduled = 0", array(':id' => $id))->fetchField());
351
    // Check expire scheduler.
352
    if (feeds_importer($id)->processor->expiryTime() == FEEDS_EXPIRE_NEVER) {
353
      $this->assertEqual(0, db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = :id AND id = 0 AND name = 'feeds_source_expire'", array(':id' => $id))->fetchField());
354
    }
355
    else {
356
      $this->assertEqual(1, db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = :id AND id = 0 AND name = 'feeds_source_expire'", array(':id' => $id))->fetchField());
357
    }
358
  }
359

    
360
  /**
361
   * Import a file through the import form. Assumes FeedsFileFetcher in place.
362
   */
363
  public function importFile($id, $file) {
364

    
365
    $this->assertTrue(file_exists($file), 'Source file exists');
366
    $edit = array(
367
      'files[feeds]' => $file,
368
    );
369
    $this->drupalPost('import/' . $id, $edit, 'Import');
370
  }
371

    
372
  /**
373
   * Assert a feeds configuration's plugins.
374
   *
375
   * @deprecated:
376
   *   Use setPlugin() instead.
377
   *
378
   * @todo Refactor users of assertPlugin() and make them use setPugin() instead.
379
   */
380
  public function assertPlugins($id, $fetcher, $parser, $processor) {
381
    // Assert actual configuration.
382
    $config = unserialize(db_query("SELECT config FROM {feeds_importer} WHERE id = :id", array(':id' => $id))->fetchField());
383

    
384
    $this->assertEqual($config['fetcher']['plugin_key'], $fetcher, 'Correct fetcher');
385
    $this->assertEqual($config['parser']['plugin_key'], $parser, 'Correct parser');
386
    $this->assertEqual($config['processor']['plugin_key'], $processor, 'Correct processor');
387
  }
388

    
389
  /**
390
   * Overrides DrupalWebTestCase::assertFieldByXPath().
391
   *
392
   * The core version has a bug, this is the D8 version.
393
   *
394
   * @todo Remove once https://drupal.org/node/2105617 lands.
395
   */
396
  protected function assertFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
397
    $fields = $this->xpath($xpath);
398

    
399
    // If value specified then check array for match.
400
    $found = TRUE;
401
    if (isset($value)) {
402
      $found = FALSE;
403
      if ($fields) {
404
        foreach ($fields as $field) {
405
          if (isset($field['value']) && $field['value'] == $value) {
406
            // Input element with correct value.
407
            $found = TRUE;
408
          }
409
          elseif (isset($field->option) || isset($field->optgroup)) {
410
            // Select element found.
411
            $selected = $this->getSelectedItem($field);
412
            if ($selected === FALSE) {
413
              // No item selected so use first item.
414
              $items = $this->getAllOptions($field);
415
              if (!empty($items) && $items[0]['value'] == $value) {
416
                $found = TRUE;
417
              }
418
            }
419
            elseif ($selected == $value) {
420
              $found = TRUE;
421
            }
422
          }
423
          elseif ((string) $field == $value) {
424
            // Text area with correct text.
425
            $found = TRUE;
426
          }
427
        }
428
      }
429
    }
430
    return $this->assertTrue($fields && $found, $message, $group);
431
  }
432

    
433
   /**
434
    * Adds mappings to a given configuration.
435
    *
436
    * @param string $id
437
    *   ID of the importer.
438
    * @param array $mappings
439
    *   An array of mapping arrays. Each mapping array must have a source and
440
    *   an target key and can have a unique key.
441
    * @param bool $test_mappings
442
    *   (optional) TRUE to automatically test mapping configs. Defaults to TRUE.
443
    */
444
  public function addMappings($id, array $mappings, $test_mappings = TRUE) {
445

    
446
    $path = "admin/structure/feeds/$id/mapping";
447

    
448
    // Iterate through all mappings and add the mapping via the form.
449
    foreach ($mappings as $i => $mapping) {
450

    
451
      if ($test_mappings) {
452
        $current_mapping_key = $this->mappingExists($id, $i, $mapping['source'], $mapping['target']);
453
        $this->assertEqual($current_mapping_key, -1, 'Mapping does not exist before addition.');
454
      }
455

    
456
      // Get unique flag and unset it. Otherwise, drupalPost will complain that
457
      // Split up config and mapping.
458
      $config = $mapping;
459
      unset($config['source'], $config['target']);
460
      $mapping = array('source' => $mapping['source'], 'target' => $mapping['target']);
461

    
462
      // Add mapping.
463
      $this->drupalPost($path, $mapping, t('Save'));
464

    
465
      // If there are other configuration options, set them.
466
      if ($config) {
467
        $this->drupalPostAJAX(NULL, array(), 'mapping_settings_edit_' . $i);
468

    
469
        // Set some settings.
470
        $edit = array();
471
        foreach ($config as $key => $value) {
472
          if (is_array($value)) {
473
            foreach ($value as $subkey => $subvalue) {
474
              $edit["config[$i][settings][$key][$subkey]"] = $subvalue;
475
            }
476
          }
477
          else {
478
            $edit["config[$i][settings][$key]"] = $value;
479
          }
480
        }
481
        $this->drupalPostAJAX(NULL, $edit, 'mapping_settings_update_' . $i);
482
        $this->drupalPost(NULL, array(), t('Save'));
483
      }
484

    
485
      if ($test_mappings) {
486
        $current_mapping_key = $this->mappingExists($id, $i, $mapping['source'], $mapping['target']);
487
        $this->assertTrue($current_mapping_key >= 0, 'Mapping exists after addition.');
488
      }
489
    }
490
  }
491

    
492
  /**
493
   * Remove mappings from a given configuration.
494
   *
495
   * @param string $id
496
   *   ID of the importer.
497
   * @param array $mappings
498
   *   An array of mapping arrays. Each mapping array must have a source and
499
   *   a target key and can have a unique key.
500
   * @param bool $test_mappings
501
   *   (optional) TRUE to automatically test mapping configs. Defaults to TRUE.
502
   */
503
  public function removeMappings($id, array $mappings, $test_mappings = TRUE) {
504
    $path = "admin/structure/feeds/$id/mapping";
505

    
506
    $edit = array();
507

    
508
    // Iterate through all mappings and remove via the form.
509
    foreach ($mappings as $i => $mapping) {
510

    
511
      if ($test_mappings) {
512
        $current_mapping_key = $this->mappingExists($id, $i, $mapping['source'], $mapping['target']);
513
        $this->assertEqual($current_mapping_key, $i, 'Mapping exists before removal.');
514
      }
515

    
516
      $edit["remove_flags[$i]"] = 1;
517
    }
518

    
519
    $this->drupalPost($path, $edit, t('Save'));
520
    $this->assertText('Your changes have been saved.');
521
  }
522

    
523
  /**
524
   * Gets an array of current mappings from the feeds_importer config.
525
   *
526
   * @param string $id
527
   *   ID of the importer.
528
   *
529
   * @return bool|array
530
   *   FALSE if the importer has no mappings, or an an array of mappings.
531
   */
532
  public function getCurrentMappings($id) {
533
    $config = db_query("SELECT config FROM {feeds_importer} WHERE id = :id", array(':id' => $id))->fetchField();
534

    
535
    $config = unserialize($config);
536

    
537
    // We are very specific here. 'mappings' can either be an array or not
538
    // exist.
539
    if (array_key_exists('mappings', $config['processor']['config'])) {
540
      $this->assertTrue(is_array($config['processor']['config']['mappings']), 'Mappings is an array.');
541

    
542
      return $config['processor']['config']['mappings'];
543
    }
544

    
545
    return FALSE;
546
  }
547

    
548
  /**
549
   * Determines if a mapping exists for a given importer.
550
   *
551
   * @param string $id
552
   *   ID of the importer.
553
   * @param integer $i
554
   *   The key of the mapping.
555
   * @param string $source
556
   *   The source field.
557
   * @param string $target
558
   *   The target field.
559
   *
560
   * @return integer
561
   *   -1 if the mapping doesn't exist, the key of the mapping otherwise.
562
   */
563
  public function mappingExists($id, $i, $source, $target) {
564

    
565
    $current_mappings = $this->getCurrentMappings($id);
566

    
567
    if ($current_mappings) {
568
      foreach ($current_mappings as $key => $mapping) {
569
        if ($mapping['source'] == $source && $mapping['target'] == $target && $key == $i) {
570
          return $key;
571
        }
572
      }
573
    }
574

    
575
    return -1;
576
  }
577

    
578
  /**
579
   * Helper function, retrieves node id from a URL.
580
   */
581
  public function getNid($url) {
582
    $matches = array();
583
    preg_match('/node\/(\d+?)$/', $url, $matches);
584
    $nid = $matches[1];
585

    
586
    // Test for actual integerness.
587
    $this->assertTrue($nid === (string) (int) $nid, 'Node id is an integer.');
588

    
589
    return $nid;
590
  }
591

    
592
  /**
593
   * Copies a directory.
594
   *
595
   * @param string $source
596
   *   The path of the source directory, from which files should be copied.
597
   * @param string $dest
598
   *   The path of the destination directory, where files should be copied to.
599
   * @param array $mapping
600
   *   (optional) The files to rename in the process.
601
   *   To skip files from being copied, map filename to FALSE.
602
   */
603
  public function copyDir($source, $dest, array $mapping = array()) {
604
    $result = file_prepare_directory($dest, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
605
    foreach (@scandir($source) as $file) {
606
      if (is_file("$source/$file")) {
607
        $new_name = isset($mapping[$file]) ? $mapping[$file] : $file;
608
        if ($new_name !== FALSE) {
609
          $file = file_unmanaged_copy("$source/$file", "$dest/$new_name");
610
        }
611
      }
612
    }
613
  }
614

    
615
  /**
616
   * Download and extract SimplePIE.
617
   *
618
   * Sets the 'feeds_simplepie_library_dir' variable to the directory where
619
   * SimplePie is downloaded.
620
   */
621
  function downloadExtractSimplePie($version) {
622
    $url = "http://simplepie.org/downloads/simplepie_$version.mini.php";
623
    $filename = 'simplepie.mini.php';
624

    
625
    // Avoid downloading the file dozens of times
626
    $library_dir = DRUPAL_ROOT . '/' . $this->originalFileDirectory . '/simpletest/feeds';
627
    $simplepie_library_dir = $library_dir . '/simplepie';
628

    
629
    if (!file_exists($library_dir)) {
630
      drupal_mkdir($library_dir);
631
    }
632

    
633
    if (!file_exists($simplepie_library_dir)) {
634
      drupal_mkdir($simplepie_library_dir);
635
    }
636

    
637
    // Local file name.
638
    $local_file = $simplepie_library_dir . '/' . $filename;
639

    
640
    // Begin single threaded code.
641
    if (function_exists('sem_get')) {
642
      $semaphore = sem_get(ftok(__FILE__, 1));
643
      sem_acquire($semaphore);
644
    }
645

    
646
    // Download and extact the archive, but only in one thread.
647
    if (!file_exists($local_file)) {
648
      $local_file = system_retrieve_file($url, $local_file, FALSE, FILE_EXISTS_REPLACE);
649
    }
650

    
651
    if (function_exists('sem_get')) {
652
      sem_release($semaphore);
653
    }
654
    // End single threaded code.
655

    
656
    // Verify that files were successfully extracted.
657
    $this->assertTrue(file_exists($local_file), t('@file found.', array('@file' => $local_file)));
658

    
659
    // Set the simpletest library directory.
660
    variable_set('feeds_library_dir', $library_dir);
661
  }
662
}
663

    
664
/**
665
 * Provides a wrapper for DrupalUnitTestCase for Feeds unit testing.
666
 */
667
class FeedsUnitTestHelper extends DrupalUnitTestCase {
668
  public function setUp() {
669
    parent::setUp();
670

    
671
    // Manually include the feeds module.
672
    // @todo Allow an array of modules from the child class.
673
    drupal_load('module', 'feeds');
674
  }
675
}
676

    
677
class FeedsUnitTestCase extends FeedsUnitTestHelper {
678
  public static function getInfo() {
679
    return array(
680
      'name' => 'Unit tests',
681
      'description' => 'Test basic low-level Feeds module functionality.',
682
      'group' => 'Feeds',
683
    );
684
  }
685

    
686
  /**
687
   * Test valid absolute urls.
688
   *
689
   * @see ValidUrlTestCase
690
   *
691
   * @todo Remove when http://drupal.org/node/1191252 is fixed.
692
   */
693
  function testFeedsValidURL() {
694
    $url_schemes = array('http', 'https', 'ftp', 'feed', 'webcal');
695
    $valid_absolute_urls = array(
696
      'example.com',
697
      'www.example.com',
698
      'ex-ample.com',
699
      '3xampl3.com',
700
      'example.com/paren(the)sis',
701
      'example.com/index.html#pagetop',
702
      'example.com:8080',
703
      'subdomain.example.com',
704
      'example.com/index.php?q=node',
705
      'example.com/index.php?q=node&param=false',
706
      'user@www.example.com',
707
      'user:pass@www.example.com:8080/login.php?do=login&style=%23#pagetop',
708
      '127.0.0.1',
709
      'example.org?',
710
      'john%20doe:secret:foo@example.org/',
711
      'example.org/~,$\'*;',
712
      'caf%C3%A9.example.org',
713
      '[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
714
      'graph.asfdasdfasdf.com/blarg/feed?access_token=133283760145143|tGew8jbxi1ctfVlYh35CPYij1eE',
715
    );
716

    
717
    foreach ($url_schemes as $scheme) {
718
      foreach ($valid_absolute_urls as $url) {
719
        $test_url = $scheme . '://' . $url;
720
        $valid_url = feeds_valid_url($test_url, TRUE);
721
        $this->assertTrue($valid_url, t('@url is a valid url.', array('@url' => $test_url)));
722
      }
723
    }
724

    
725
    $invalid_ablosule_urls = array(
726
      '',
727
      'ex!ample.com',
728
      'ex%ample.com',
729
    );
730

    
731
    foreach ($url_schemes as $scheme) {
732
      foreach ($invalid_ablosule_urls as $url) {
733
        $test_url = $scheme . '://' . $url;
734
        $valid_url = feeds_valid_url($test_url, TRUE);
735
        $this->assertFalse($valid_url, t('@url is NOT a valid url.', array('@url' => $test_url)));
736
      }
737
    }
738
  }
739
}