Projet

Général

Profil

Paste
Télécharger (25,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / feeds / tests / feeds.test @ ec2b0e7b

1 85ad3d82 Assos Assos
<?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 41cc1b08 Assos Assos
        $modules = $args[0];
22
      }
23 85ad3d82 Assos Assos
      else {
24 41cc1b08 Assos Assos
        $modules = $args;
25
      }
26 85ad3d82 Assos Assos
    }
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 41cc1b08 Assos Assos
    $permissions[] = 'administer filters';
93 7295e063 Assos Assos
    $permissions[] = 'administer fields';
94 85ad3d82 Assos Assos
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 41cc1b08 Assos Assos
    // 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 85ad3d82 Assos Assos
  }
359
360
  /**
361
   * Import a file through the import form. Assumes FeedsFileFetcher in place.
362 ec2b0e7b Assos Assos
   *
363
   * @param string $id
364
   *   The ID of the importer.
365
   * @param string $file
366
   *   The absolute path to the file.
367
   * @param string $submit
368
   *   (optional) The button to press.
369
   *   Defaults to the button "Import".
370 85ad3d82 Assos Assos
   */
371 ec2b0e7b Assos Assos
  public function importFile($id, $file, $submit = NULL) {
372 85ad3d82 Assos Assos
    $this->assertTrue(file_exists($file), 'Source file exists');
373
    $edit = array(
374
      'files[feeds]' => $file,
375
    );
376 ec2b0e7b Assos Assos
    if (empty($submit)) {
377
      $submit = 'Import';
378
    }
379
    $this->drupalPost('import/' . $id, $edit, $submit);
380
  }
381
382
  /**
383
   * Asserts that the given number of nodes exist.
384
   *
385
   * @param int $expected_node_count
386
   *   The expected number of nodes in the node table.
387
   * @param string $message
388
   *   (optional) The message to assert.
389
   */
390
  protected function assertNodeCount($expected_node_count, $message = '') {
391
    if (!$message) {
392
      $message = '@expected nodes have been created (actual: @count).';
393
    }
394
395
    $node_count = db_select('node')
396
      ->fields('node', array())
397
      ->countQuery()
398
      ->execute()
399
      ->fetchField();
400
    $this->assertEqual($expected_node_count, $node_count, format_string($message, array(
401
      '@expected' => $expected_node_count,
402
      '@count' => $node_count,
403
    )));
404 85ad3d82 Assos Assos
  }
405
406
  /**
407
   * Assert a feeds configuration's plugins.
408
   *
409
   * @deprecated:
410
   *   Use setPlugin() instead.
411
   *
412
   * @todo Refactor users of assertPlugin() and make them use setPugin() instead.
413
   */
414
  public function assertPlugins($id, $fetcher, $parser, $processor) {
415
    // Assert actual configuration.
416
    $config = unserialize(db_query("SELECT config FROM {feeds_importer} WHERE id = :id", array(':id' => $id))->fetchField());
417
418
    $this->assertEqual($config['fetcher']['plugin_key'], $fetcher, 'Correct fetcher');
419
    $this->assertEqual($config['parser']['plugin_key'], $parser, 'Correct parser');
420
    $this->assertEqual($config['processor']['plugin_key'], $processor, 'Correct processor');
421
  }
422
423 41cc1b08 Assos Assos
  /**
424
   * Overrides DrupalWebTestCase::assertFieldByXPath().
425
   *
426
   * The core version has a bug, this is the D8 version.
427
   *
428
   * @todo Remove once https://drupal.org/node/2105617 lands.
429
   */
430
  protected function assertFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
431
    $fields = $this->xpath($xpath);
432
433
    // If value specified then check array for match.
434
    $found = TRUE;
435
    if (isset($value)) {
436
      $found = FALSE;
437
      if ($fields) {
438
        foreach ($fields as $field) {
439
          if (isset($field['value']) && $field['value'] == $value) {
440
            // Input element with correct value.
441
            $found = TRUE;
442
          }
443
          elseif (isset($field->option) || isset($field->optgroup)) {
444
            // Select element found.
445
            $selected = $this->getSelectedItem($field);
446
            if ($selected === FALSE) {
447
              // No item selected so use first item.
448
              $items = $this->getAllOptions($field);
449
              if (!empty($items) && $items[0]['value'] == $value) {
450
                $found = TRUE;
451
              }
452
            }
453
            elseif ($selected == $value) {
454
              $found = TRUE;
455
            }
456
          }
457
          elseif ((string) $field == $value) {
458
            // Text area with correct text.
459
            $found = TRUE;
460
          }
461
        }
462
      }
463
    }
464
    return $this->assertTrue($fields && $found, $message, $group);
465
  }
466
467 ec2b0e7b Assos Assos
  /**
468
   * Asserts that a field in the current page is enabled.
469
   *
470
   * @param string $name
471
   *   Name of field to assert.
472
   * @param string $message
473
   *   (optional) A message to display with the assertion.
474
   *
475
   * @return bool
476
   *   TRUE on pass, FALSE on fail.
477
   */
478
  protected function assertFieldEnabled($name, $message = '') {
479
    $elements = $this->xpath($this->constructFieldXpath('name', $name));
480
    return $this->assertTrue(isset($elements[0]) && empty($elements[0]['disabled']), $message ? $message : t('Field %name is enabled.', array('%name' => $name)), t('Browser'));
481
  }
482
483
  /**
484
   * Asserts that a field in the current page is disabled.
485
   *
486
   * @param string $name
487
   *   Name of field to assert.
488
   * @param string $message
489
   *   (optional) A message to display with the assertion.
490
   *
491
   * @return bool
492
   *   TRUE on pass, FALSE on fail.
493
   */
494
  protected function assertFieldDisabled($name, $message = '') {
495
    $elements = $this->xpath($this->constructFieldXpath('name', $name));
496
    return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['disabled']), $message ? $message : t('Field %name is disabled.', array('%name' => $name)), t('Browser'));
497
  }
498
499
  /**
500
   * Adds mappings to a given configuration.
501
   *
502
   * @param string $id
503
   *   ID of the importer.
504
   * @param array $mappings
505
   *   An array of mapping arrays. Each mapping array must have a source and
506
   *   an target key and can have a unique key.
507
   * @param bool $test_mappings
508
   *   (optional) TRUE to automatically test mapping configs. Defaults to TRUE.
509
   */
510 41cc1b08 Assos Assos
  public function addMappings($id, array $mappings, $test_mappings = TRUE) {
511 85ad3d82 Assos Assos
512
    $path = "admin/structure/feeds/$id/mapping";
513
514
    // Iterate through all mappings and add the mapping via the form.
515
    foreach ($mappings as $i => $mapping) {
516
517
      if ($test_mappings) {
518
        $current_mapping_key = $this->mappingExists($id, $i, $mapping['source'], $mapping['target']);
519
        $this->assertEqual($current_mapping_key, -1, 'Mapping does not exist before addition.');
520
      }
521
522
      // Get unique flag and unset it. Otherwise, drupalPost will complain that
523
      // Split up config and mapping.
524
      $config = $mapping;
525
      unset($config['source'], $config['target']);
526
      $mapping = array('source' => $mapping['source'], 'target' => $mapping['target']);
527
528
      // Add mapping.
529
      $this->drupalPost($path, $mapping, t('Save'));
530
531
      // If there are other configuration options, set them.
532
      if ($config) {
533
        $this->drupalPostAJAX(NULL, array(), 'mapping_settings_edit_' . $i);
534
535
        // Set some settings.
536
        $edit = array();
537
        foreach ($config as $key => $value) {
538 7295e063 Assos Assos
          if (is_array($value)) {
539
            foreach ($value as $subkey => $subvalue) {
540
              $edit["config[$i][settings][$key][$subkey]"] = $subvalue;
541
            }
542
          }
543
          else {
544
            $edit["config[$i][settings][$key]"] = $value;
545
          }
546 85ad3d82 Assos Assos
        }
547
        $this->drupalPostAJAX(NULL, $edit, 'mapping_settings_update_' . $i);
548
        $this->drupalPost(NULL, array(), t('Save'));
549
      }
550
551
      if ($test_mappings) {
552
        $current_mapping_key = $this->mappingExists($id, $i, $mapping['source'], $mapping['target']);
553
        $this->assertTrue($current_mapping_key >= 0, 'Mapping exists after addition.');
554
      }
555
    }
556
  }
557
558
  /**
559
   * Remove mappings from a given configuration.
560
   *
561 41cc1b08 Assos Assos
   * @param string $id
562
   *   ID of the importer.
563 85ad3d82 Assos Assos
   * @param array $mappings
564
   *   An array of mapping arrays. Each mapping array must have a source and
565
   *   a target key and can have a unique key.
566
   * @param bool $test_mappings
567
   *   (optional) TRUE to automatically test mapping configs. Defaults to TRUE.
568
   */
569 41cc1b08 Assos Assos
  public function removeMappings($id, array $mappings, $test_mappings = TRUE) {
570 85ad3d82 Assos Assos
    $path = "admin/structure/feeds/$id/mapping";
571
572 41cc1b08 Assos Assos
    $edit = array();
573 85ad3d82 Assos Assos
574
    // Iterate through all mappings and remove via the form.
575
    foreach ($mappings as $i => $mapping) {
576
577
      if ($test_mappings) {
578
        $current_mapping_key = $this->mappingExists($id, $i, $mapping['source'], $mapping['target']);
579
        $this->assertEqual($current_mapping_key, $i, 'Mapping exists before removal.');
580
      }
581
582 41cc1b08 Assos Assos
      $edit["remove_flags[$i]"] = 1;
583 85ad3d82 Assos Assos
    }
584 41cc1b08 Assos Assos
585
    $this->drupalPost($path, $edit, t('Save'));
586
    $this->assertText('Your changes have been saved.');
587 85ad3d82 Assos Assos
  }
588
589
  /**
590
   * Gets an array of current mappings from the feeds_importer config.
591
   *
592
   * @param string $id
593
   *   ID of the importer.
594
   *
595
   * @return bool|array
596
   *   FALSE if the importer has no mappings, or an an array of mappings.
597
   */
598
  public function getCurrentMappings($id) {
599
    $config = db_query("SELECT config FROM {feeds_importer} WHERE id = :id", array(':id' => $id))->fetchField();
600
601
    $config = unserialize($config);
602
603
    // We are very specific here. 'mappings' can either be an array or not
604
    // exist.
605
    if (array_key_exists('mappings', $config['processor']['config'])) {
606
      $this->assertTrue(is_array($config['processor']['config']['mappings']), 'Mappings is an array.');
607
608
      return $config['processor']['config']['mappings'];
609
    }
610
611
    return FALSE;
612
  }
613
614
  /**
615
   * Determines if a mapping exists for a given importer.
616
   *
617
   * @param string $id
618
   *   ID of the importer.
619
   * @param integer $i
620
   *   The key of the mapping.
621
   * @param string $source
622
   *   The source field.
623
   * @param string $target
624
   *   The target field.
625
   *
626
   * @return integer
627
   *   -1 if the mapping doesn't exist, the key of the mapping otherwise.
628
   */
629
  public function mappingExists($id, $i, $source, $target) {
630
631
    $current_mappings = $this->getCurrentMappings($id);
632
633
    if ($current_mappings) {
634
      foreach ($current_mappings as $key => $mapping) {
635
        if ($mapping['source'] == $source && $mapping['target'] == $target && $key == $i) {
636
          return $key;
637
        }
638
      }
639
    }
640
641
    return -1;
642
  }
643
644
  /**
645
   * Helper function, retrieves node id from a URL.
646
   */
647
  public function getNid($url) {
648
    $matches = array();
649
    preg_match('/node\/(\d+?)$/', $url, $matches);
650
    $nid = $matches[1];
651
652
    // Test for actual integerness.
653
    $this->assertTrue($nid === (string) (int) $nid, 'Node id is an integer.');
654
655
    return $nid;
656
  }
657
658
  /**
659
   * Copies a directory.
660 7295e063 Assos Assos
   *
661
   * @param string $source
662
   *   The path of the source directory, from which files should be copied.
663
   * @param string $dest
664
   *   The path of the destination directory, where files should be copied to.
665
   * @param array $mapping
666
   *   (optional) The files to rename in the process.
667
   *   To skip files from being copied, map filename to FALSE.
668 85ad3d82 Assos Assos
   */
669 7295e063 Assos Assos
  public function copyDir($source, $dest, array $mapping = array()) {
670 85ad3d82 Assos Assos
    $result = file_prepare_directory($dest, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
671
    foreach (@scandir($source) as $file) {
672
      if (is_file("$source/$file")) {
673 7295e063 Assos Assos
        $new_name = isset($mapping[$file]) ? $mapping[$file] : $file;
674
        if ($new_name !== FALSE) {
675
          $file = file_unmanaged_copy("$source/$file", "$dest/$new_name");
676
        }
677 85ad3d82 Assos Assos
      }
678
    }
679
  }
680
681
  /**
682
   * Download and extract SimplePIE.
683
   *
684
   * Sets the 'feeds_simplepie_library_dir' variable to the directory where
685
   * SimplePie is downloaded.
686
   */
687
  function downloadExtractSimplePie($version) {
688
    $url = "http://simplepie.org/downloads/simplepie_$version.mini.php";
689
    $filename = 'simplepie.mini.php';
690
691
    // Avoid downloading the file dozens of times
692
    $library_dir = DRUPAL_ROOT . '/' . $this->originalFileDirectory . '/simpletest/feeds';
693
    $simplepie_library_dir = $library_dir . '/simplepie';
694
695
    if (!file_exists($library_dir)) {
696
      drupal_mkdir($library_dir);
697
    }
698
699
    if (!file_exists($simplepie_library_dir)) {
700
      drupal_mkdir($simplepie_library_dir);
701
    }
702
703
    // Local file name.
704
    $local_file = $simplepie_library_dir . '/' . $filename;
705
706
    // Begin single threaded code.
707
    if (function_exists('sem_get')) {
708
      $semaphore = sem_get(ftok(__FILE__, 1));
709
      sem_acquire($semaphore);
710
    }
711
712
    // Download and extact the archive, but only in one thread.
713
    if (!file_exists($local_file)) {
714
      $local_file = system_retrieve_file($url, $local_file, FALSE, FILE_EXISTS_REPLACE);
715
    }
716
717
    if (function_exists('sem_get')) {
718
      sem_release($semaphore);
719
    }
720
    // End single threaded code.
721
722
    // Verify that files were successfully extracted.
723
    $this->assertTrue(file_exists($local_file), t('@file found.', array('@file' => $local_file)));
724
725
    // Set the simpletest library directory.
726
    variable_set('feeds_library_dir', $library_dir);
727
  }
728
}
729
730
/**
731
 * Provides a wrapper for DrupalUnitTestCase for Feeds unit testing.
732
 */
733
class FeedsUnitTestHelper extends DrupalUnitTestCase {
734
  public function setUp() {
735
    parent::setUp();
736
737
    // Manually include the feeds module.
738
    // @todo Allow an array of modules from the child class.
739
    drupal_load('module', 'feeds');
740
  }
741
}
742
743
class FeedsUnitTestCase extends FeedsUnitTestHelper {
744
  public static function getInfo() {
745
    return array(
746
      'name' => 'Unit tests',
747
      'description' => 'Test basic low-level Feeds module functionality.',
748
      'group' => 'Feeds',
749
    );
750
  }
751
752
  /**
753
   * Test valid absolute urls.
754
   *
755
   * @see ValidUrlTestCase
756
   *
757
   * @todo Remove when http://drupal.org/node/1191252 is fixed.
758
   */
759
  function testFeedsValidURL() {
760
    $url_schemes = array('http', 'https', 'ftp', 'feed', 'webcal');
761
    $valid_absolute_urls = array(
762
      'example.com',
763
      'www.example.com',
764
      'ex-ample.com',
765
      '3xampl3.com',
766
      'example.com/paren(the)sis',
767
      'example.com/index.html#pagetop',
768
      'example.com:8080',
769
      'subdomain.example.com',
770
      'example.com/index.php?q=node',
771
      'example.com/index.php?q=node&param=false',
772
      'user@www.example.com',
773
      'user:pass@www.example.com:8080/login.php?do=login&style=%23#pagetop',
774
      '127.0.0.1',
775
      'example.org?',
776
      'john%20doe:secret:foo@example.org/',
777
      'example.org/~,$\'*;',
778
      'caf%C3%A9.example.org',
779
      '[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
780
      'graph.asfdasdfasdf.com/blarg/feed?access_token=133283760145143|tGew8jbxi1ctfVlYh35CPYij1eE',
781
    );
782
783
    foreach ($url_schemes as $scheme) {
784
      foreach ($valid_absolute_urls as $url) {
785
        $test_url = $scheme . '://' . $url;
786
        $valid_url = feeds_valid_url($test_url, TRUE);
787
        $this->assertTrue($valid_url, t('@url is a valid url.', array('@url' => $test_url)));
788
      }
789
    }
790
791
    $invalid_ablosule_urls = array(
792
      '',
793
      'ex!ample.com',
794
      'ex%ample.com',
795
    );
796
797
    foreach ($url_schemes as $scheme) {
798
      foreach ($invalid_ablosule_urls as $url) {
799
        $test_url = $scheme . '://' . $url;
800
        $valid_url = feeds_valid_url($test_url, TRUE);
801
        $this->assertFalse($valid_url, t('@url is NOT a valid url.', array('@url' => $test_url)));
802
      }
803
    }
804
  }
805
}