Projet

Général

Profil

Paste
Télécharger (18,6 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / feeds / tests / feeds_scheduler.test @ ed9a13f1

1
<?php
2

    
3
/**
4
 * @file
5
 * Feeds tests.
6
 */
7

    
8
/**
9
 * Test cron scheduling.
10
 */
11
class FeedsSchedulerTestCase extends FeedsWebTestCase {
12

    
13
  /**
14
   * {@inheritdoc}
15
   */
16
  public static function getInfo() {
17
    return array(
18
      'name' => 'Scheduler',
19
      'description' => 'Tests for feeds scheduler.',
20
      'group' => 'Feeds',
21
    );
22
  }
23

    
24
  /**
25
   * Test scheduling of disabled import on cron.
26
   */
27
  public function testSchedulingWithDisabledImporter() {
28
    // Initialize scheduling.
29
    $init = $this->initSyndication();
30

    
31
    // Disable syndication feed so cron doesn't import nodes.
32
    $this->drupalLogin($this->admin_user);
33
    $edit = array(
34
      'syndication' => FALSE,
35
    );
36
    $this->drupalPost('admin/structure/feeds', $edit, 'Save');
37
    $this->drupalLogout();
38
    $this->cronRun();
39
    $this->cronRun();
40

    
41
    // There should be 0 article nodes in the database.
42
    $count = db_query("SELECT COUNT(*) FROM {node} WHERE type = 'article' AND status = 1")->fetchField();
43
    $this->assertEqual($count, 0, 'There are 0 article nodes aggregated.');
44
  }
45

    
46
  /**
47
   * Test scheduling of enabled import on cron.
48
   */
49
  public function testScheduling() {
50
    // Initialize scheduling.
51
    $init = $this->initSyndication();
52
    $time = $init['time'];
53
    $nids = $init['nids'];
54
    $count = $init['count'];
55

    
56
    $this->cronRun();
57
    $this->cronRun();
58
    // There should be feeds_schedule_num X 2 (= 20) feeds updated now.
59
    $schedule = array();
60
    $rows = db_query("SELECT id, last, scheduled FROM {job_schedule} WHERE last > :time", array(':time' => $time));
61
    foreach ($rows as $row) {
62
      $schedule[$row->id] = $row;
63
    }
64
    $this->assertEqual(count($schedule), 20, format_string('20 feeds refreshed on cron (actual: @actual).', array(
65
      '@actual' => count($schedule),
66
    )));
67

    
68
    // There should be 200 article nodes in the database.
69
    $count = db_query("SELECT COUNT(*) FROM {node} WHERE type = 'article' AND status = 1")->fetchField();
70
    $this->assertEqual($count, 200, format_string('There are 200 article nodes aggregated (actual: @actual).', array(
71
      '@actual' => $count,
72
    )));
73

    
74
    // There shouldn't be any items with scheduled = 1 now, if so, this would
75
    // mean they are stuck.
76
    $count = db_query("SELECT COUNT(*) FROM {job_schedule} WHERE scheduled = 1")->fetchField();
77
    $this->assertEqual($count, 0, format_string('All items are unscheduled (schedule flag = 0) (actual: @actual).', array(
78
      '@actual' => $count,
79
    )));
80

    
81
    // Hit cron again twice.
82
    $this->cronRun();
83
    $this->cronRun();
84

    
85
    // The import_period setting of the feed configuration is 1800, there
86
    // shouldn't be any change to the database now.
87
    $equal = TRUE;
88
    $rows = db_query("SELECT id, last, scheduled FROM {job_schedule} WHERE last > :time", array(':time' => $time));
89
    foreach ($rows as $row) {
90
      $equal = $equal && ($row->last == $schedule[$row->id]->last);
91
    }
92
    $this->assertTrue($equal, 'Schedule did not change.');
93

    
94
    // Log back in and set refreshing to as often as possible.
95
    $this->drupalLogin($this->admin_user);
96
    $edit = array(
97
      'import_period' => 0,
98
    );
99
    $this->drupalPost('admin/structure/feeds/syndication/settings', $edit, 'Save');
100
    $this->assertText('Periodic import: as often as possible');
101
    $this->drupalLogout();
102

    
103
    // Hit cron once, this should cause Feeds to reschedule all entries.
104
    $this->cronRun();
105
    $equal = FALSE;
106
    $rows = db_query("SELECT id, last, scheduled FROM {job_schedule} WHERE last > :time", array(':time' => $time));
107
    foreach ($rows as $row) {
108
      $equal = $equal && ($row->last == $schedule[$row->id]->last);
109
      $schedule[$row->id] = $row;
110
    }
111
    $this->assertFalse($equal, 'Every feed schedule time changed.');
112

    
113
    // Hit cron again, 4 times now, every item should change again.
114
    for ($i = 0; $i < 4; $i++) {
115
      $this->cronRun();
116
    }
117
    $equal = FALSE;
118
    $rows = db_query("SELECT id, last, scheduled FROM {job_schedule} WHERE last > :time", array(':time' => $time));
119
    foreach ($rows as $row) {
120
      $equal = $equal && ($row->last == $schedule[$row->id]->last);
121
    }
122
    $this->assertFalse($equal, 'Every feed schedule time changed.');
123

    
124
    // There should be 200 article nodes in the database.
125
    $count = db_query("SELECT COUNT(*) FROM {node} WHERE type = 'article' AND status = 1")->fetchField();
126
    $this->assertEqual($count, 200, 'The total of 200 article nodes has not changed.');
127

    
128
    // Set expire settings, check rescheduling.
129
    $max_last = db_query("SELECT MAX(last) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_import' AND period = 0")->fetchField();
130
    $min_last = db_query("SELECT MIN(last) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_import' AND period = 0")->fetchField();
131
    $this->assertEqual(0, db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_expire'")->fetchField());
132
    $this->drupalLogin($this->admin_user);
133
    $this->setSettings('syndication', 'FeedsNodeProcessor', array('expire' => 86400));
134
    $this->drupalLogout();
135
    sleep(1);
136
    $this->cronRun();
137
    // There should be 20 feeds_source_expire jobs now, and all last fields should be reset.
138
    $this->assertEqual(count($nids), db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_expire' AND last <> 0 AND scheduled = 0 AND period = 3600")->fetchField());
139
    $new_max_last = db_query("SELECT MAX(last) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_import' AND period = 0")->fetchField();
140
    $new_min_last = db_query("SELECT MIN(last) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_import' AND period = 0")->fetchField();
141
    $this->assertNotEqual($new_max_last, $max_last);
142
    $this->assertNotEqual($new_min_last, $min_last);
143
    $this->assertEqual($new_max_last, $new_min_last);
144
    $max_last = $new_max_last;
145
    $min_last = $new_min_last;
146

    
147
    // Set import settings, check rescheduling.
148
    $this->drupalLogin($this->admin_user);
149
    $this->setSettings('syndication', '', array('import_period' => 3600));
150
    $this->drupalLogout();
151
    sleep(1);
152
    $this->cronRun();
153
    $new_max_last = db_query("SELECT MAX(last) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_import' AND period = 3600")->fetchField();
154
    $new_min_last = db_query("SELECT MIN(last) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_import' AND period = 3600")->fetchField();
155
    $this->assertNotEqual($new_max_last, $max_last);
156
    $this->assertNotEqual($new_min_last, $min_last);
157
    $this->assertEqual($new_max_last, $new_min_last);
158
    $this->assertEqual(0, db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_import' AND period <> 3600")->fetchField());
159
    $this->assertEqual(count($nids), db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_expire' AND period = 3600 AND last = :last", array(':last' => $new_min_last))->fetchField());
160

    
161
    // Delete source, delete importer, check schedule.
162
    $this->drupalLogin($this->admin_user);
163
    $nid = array_shift($nids);
164
    $this->drupalPost("node/$nid/delete", array(), t('Delete'));
165
    $this->assertEqual(0, db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_import' AND id = :nid", array(':nid' => $nid))->fetchField());
166
    $this->assertEqual(0, db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_expire' AND id = :nid", array(':nid' => $nid))->fetchField());
167
    $this->assertEqual(count($nids), db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_import'")->fetchField());
168
    $this->assertEqual(count($nids), db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_expire'")->fetchField());
169

    
170
    $this->drupalPost('admin/structure/feeds/syndication/delete', array(), t('Delete'));
171
    $this->assertEqual(count($nids), db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_expire'")->fetchField());
172
    $this->assertEqual(count($nids), db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = 'syndication' AND name = 'feeds_source_import'")->fetchField());
173
  }
174

    
175
  /**
176
   * Test if existing feed nodes get rescheduled upon save.
177
   */
178
  public function testRescheduling() {
179
    $this->initSyndication();
180
    $this->drupalLogin($this->admin_user);
181

    
182
    // Configure to import as often as possible.
183
    $this->setSettings('syndication', NULL, array(
184
      'import_period' => 0,
185
    ));
186

    
187
    // Remove all jobs to simulate the situation that no feed nodes are
188
    // scheduled.
189
    db_truncate('job_schedule')->execute();
190
    // Also prevent feeds from rescheduling by itself as the import_period
191
    // setting was changed.
192
    variable_del('feeds_reschedule');
193

    
194
    // Run cron.
195
    $this->cronRun();
196

    
197
    // Assert that no nodes were created yet.
198
    $count = db_query("SELECT COUNT(*) FROM {node} WHERE type = 'article'")->fetchField();
199
    $this->assertEqual(0, $count, format_string('There are no articles yet (actual: @count).', array(
200
      '@count' => $count,
201
    )));
202

    
203
    // Now reschedule the first feed node by resaving the node.
204
    $this->drupalPost('node/1/edit', array(), t('Save'));
205

    
206
    // And run cron again.
207
    $this->cronRun();
208

    
209
    // Assert that 10 articles were created.
210
    $count = db_query("SELECT COUNT(*) FROM {node} WHERE type = 'article'")->fetchField();
211
    $this->assertEqual(10, $count, format_string('10 articles have been created (actual: @count).', array(
212
      '@count' => $count,
213
    )));
214
  }
215

    
216
  /**
217
   * Tests if the expected next import time is shown for scheduled imports.
218
   */
219
  public function testNextImportTime() {
220
    $this->initSyndication();
221
    $this->drupalLogin($this->admin_user);
222

    
223
    // Set schedule to be 25 minutes in the future.
224
    $next = REQUEST_TIME + 1500;
225
    db_query("UPDATE {job_schedule} SET next = :time", array(
226
      ':time' => $next,
227
    ));
228
    $this->drupalGet('node/1/import');
229
    $this->assertText(format_date($next));
230

    
231
    // Set schedule to import on next cron run.
232
    db_query("UPDATE {job_schedule} SET next = :time", array(
233
      ':time' => REQUEST_TIME,
234
    ));
235
    $this->drupalGet('node/1/import');
236
    $this->assertText('Next import: on next cron run');
237

    
238
    // Now remove all jobs.
239
    db_truncate('job_schedule')->execute();
240

    
241
    // Assert that the import is not scheduled now.
242
    $this->drupalGet('node/1/import');
243
    $this->assertText('Next import: not scheduled');
244
  }
245

    
246
  /**
247
   * Tests if the expected next import time is shown when the import is queued
248
   * via background job.
249
   */
250
  public function testNextImportTimeWhenQueuedViaBackgroundJob() {
251
    // Create an importer that uses a background job to import.
252
    $this->createImporterConfiguration('Node import', 'node');
253
    $edit = array(
254
      'content_type' => '',
255
      'import_on_create' => TRUE,
256
      'process_in_background' => TRUE,
257
    );
258
    $this->drupalPost('admin/structure/feeds/node/settings', $edit, 'Save');
259
    $this->setPlugin('node', 'FeedsFileFetcher');
260
    $this->setPlugin('node', 'FeedsCSVParser');
261
    $mappings = array(
262
      0 => array(
263
        'source' => 'title',
264
        'target' => 'title',
265
      ),
266
    );
267
    $this->addMappings('node', $mappings);
268

    
269
    // Specify a file with many nodes.
270
    $this->importFile('node', $this->absolutePath() . '/tests/feeds/many_nodes.csv', 'Schedule import');
271

    
272
    // Verify that a queue item is created.
273
    $count = db_query("SELECT COUNT(*) FROM {queue} WHERE name = 'feeds_source_import'")->fetchField();
274
    $this->assertEqual(1, $count, format_string('One import item is queued (actual: @count).', array(
275
      '@count' => $count,
276
    )));
277

    
278
    // The page should say that import happens on next cron.
279
    $this->assertText('Next import: on next cron run');
280
  }
281

    
282
  /**
283
   * Tests if the expected next import time is shown when the import is queued
284
   * via Job Scheduler.
285
   */
286
  public function testNextImportTimeWhenQueuedViaJobScheduler() {
287
    $this->initSyndication();
288
    $this->drupalLogin($this->admin_user);
289

    
290
    // Manually dispatch a job.
291
    $job = db_select('job_schedule', NULL, array('fetch' => PDO::FETCH_ASSOC))
292
      ->fields('job_schedule')
293
      ->condition('type', 'syndication')
294
      ->condition('id', 18)
295
      ->execute()
296
      ->fetch();
297
    try {
298
      JobScheduler::get($job['name'])->dispatch($job);
299
      $this->pass('No exceptions occurred while dispatching a feeds job.');
300
    }
301
    catch (Exception $e) {
302
      watchdog_exception('feeds', $e);
303
      $this->fail('No exceptions occurred while dispatching a feeds job.');
304
    }
305

    
306
    // Verify that a queue item is created.
307
    $count = db_query("SELECT COUNT(*) FROM {queue} WHERE name = 'feeds_source_import'")->fetchField();
308
    $this->assertEqual(1, $count, format_string('One import item is queued (actual: @count).', array(
309
      '@count' => $count,
310
    )));
311

    
312
    // The page should say that import happens on next cron.
313
    $this->drupalGet('node/18/import');
314
    $this->assertText('Next import: on next cron run');
315
  }
316

    
317
  /**
318
   * Test batching on cron.
319
   */
320
  public function testBatching() {
321
    // Set up an importer.
322
    $this->createImporterConfiguration('Node import', 'node');
323
    // Set and configure plugins and mappings.
324
    $edit = array(
325
      'content_type' => '',
326
    );
327
    $this->drupalPost('admin/structure/feeds/node/settings', $edit, 'Save');
328
    $this->setPlugin('node', 'FeedsFileFetcher');
329
    $this->setPlugin('node', 'FeedsCSVParser');
330
    $mappings = array(
331
      0 => array(
332
        'source' => 'title',
333
        'target' => 'title',
334
      ),
335
    );
336
    $this->addMappings('node', $mappings);
337

    
338
    // Verify that there are 86 nodes total.
339
    $this->importFile('node', $this->absolutePath() . '/tests/feeds/many_nodes.csv');
340
    $this->assertText('Created 86 nodes');
341

    
342
    // Set queue time to a minimum.
343
    variable_set('feeds_tests_feeds_source_import_queue_time', 1);
344

    
345
    // Run batch twice with two different process limits.
346
    // 50 = FEEDS_PROCESS_LIMIT.
347
    foreach (array(10, 50) as $limit) {
348
      variable_set('feeds_process_limit', $limit);
349

    
350
      db_query("UPDATE {job_schedule} SET next = 0");
351
      $this->drupalPost('import/node/delete-items', array(), 'Delete');
352
      $node_count = db_query("SELECT COUNT(*) FROM {node} WHERE type = 'article'")->fetchField();
353
      $this->assertEqual(0, $node_count);
354

    
355
      // Hit cron for importing, until we have all items or when we are running
356
      // out of cron runs.
357
      $max_runs = ceil(86 / $limit);
358
      $ran = 0;
359
      while ($node_count < 86 && $ran < $max_runs) {
360
        $this->cronRun();
361
        $node_count = db_query("SELECT COUNT(*) FROM {node} WHERE type = 'article'")->fetchField();
362
        $ran++;
363
      }
364

    
365
      // Assert that 86 nodes exist now.
366
      $node_count = db_query("SELECT COUNT(*) FROM {node} WHERE type = 'article'")->fetchField();
367
      $this->assertEqual(86, $node_count, format_string('86 nodes exist after batched importing via cron (actual: @actual).', array(
368
        '@actual' => $node_count,
369
      )));
370

    
371
      // Import should be rescheduled for 1800 seconds.
372
      $this->assertEqual(1800, db_query("SELECT period FROM {job_schedule} WHERE type = 'node' AND id = 0")->fetchField());
373
    }
374

    
375
    // Delete a couple of nodes, then hit cron again. They should not be
376
    // replaced as the minimum update time is 30 minutes.
377
    $nodes = db_query_range("SELECT nid FROM {node} WHERE type = 'article'", 0, 2);
378
    foreach ($nodes as $node) {
379
      $this->drupalPost("node/{$node->nid}/delete", array(), 'Delete');
380
    }
381
    $this->assertEqual(84, db_query("SELECT COUNT(*) FROM {node} WHERE type = 'article'")->fetchField());
382
    $this->cronRun();
383
    $this->assertEqual(84, db_query("SELECT COUNT(*) FROM {node} WHERE type = 'article'")->fetchField());
384
  }
385

    
386
  /**
387
   * Tests if jobs are removed for feeds sources that no longer exist.
388
   */
389
  public function testCleanUpJobsForNonExistingFeeds() {
390
    // Create a fake job.
391
    $job = array(
392
      'type' => 'non_existing_importer',
393
      'id' => 12,
394
      'period' => 0,
395
      'periodic' => TRUE,
396
    );
397
    JobScheduler::get('feeds_source_import')->set($job);
398

    
399
    // Assert that a job exist.
400
    $count = db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = 'non_existing_importer'")->fetchField();
401
    $this->assertEqual(1, $count, 'The fake job was created.');
402

    
403
    // Run cron.
404
    $this->cronRun();
405

    
406
    // Assert that the job has been cleaned up.
407
    $count = db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = 'non_existing_importer'")->fetchField();
408
    $this->assertEqual(0, $count, 'The fake job no longer exists.');
409
  }
410

    
411
  /**
412
   * Initialize scheduling.
413
   */
414
  protected function initSyndication() {
415
    // Create importer configuration.
416
    $this->createImporterConfiguration();
417
    $this->addMappings('syndication',
418
      array(
419
        0 => array(
420
          'source' => 'title',
421
          'target' => 'title',
422
          'unique' => FALSE,
423
        ),
424
        1 => array(
425
          'source' => 'description',
426
          'target' => 'body',
427
        ),
428
        2 => array(
429
          'source' => 'timestamp',
430
          'target' => 'created',
431
        ),
432
        3 => array(
433
          'source' => 'url',
434
          'target' => 'url',
435
          'unique' => TRUE,
436
        ),
437
        4 => array(
438
          'source' => 'guid',
439
          'target' => 'guid',
440
          'unique' => TRUE,
441
        ),
442
      )
443
    );
444

    
445
    // Create 10 feed nodes. Turn off import on create before doing that.
446
    $edit = array(
447
      'import_on_create' => FALSE,
448
    );
449
    $this->drupalPost('admin/structure/feeds/syndication/settings', $edit, 'Save');
450
    $this->assertText('Do not import on submission');
451

    
452
    $nids = $this->createFeedNodes();
453
    // This implicitly tests the import_on_create node setting being 0.
454
    $this->assertTrue($nids[0] == 1 && $nids[1] == 2, 'Node ids sequential.');
455

    
456
    // Check whether feed got properly added to scheduler.
457
    foreach ($nids as $nid) {
458
      $this->assertEqual(1, db_query("SELECT COUNT(*) FROM {job_schedule} WHERE type = 'syndication' AND id = :nid AND name = 'feeds_source_import' AND last <> 0 AND scheduled = 0 AND period = 1800 AND periodic = 1", array(':nid' => $nid))->fetchField());
459
    }
460

    
461
    // Take time for comparisons.
462
    $time = time();
463
    sleep(1);
464

    
465
    // Log out and run cron, no changes.
466
    $this->drupalLogout();
467
    $this->cronRun();
468
    $count = db_query("SELECT COUNT(*) FROM {job_schedule} WHERE last > :time", array(':time' => $time))->fetchField();
469
    $this->assertEqual($count, 0, '0 feeds refreshed on cron.' . $count);
470

    
471
    // Set next time to 0 to simulate updates.
472
    db_query("UPDATE {job_schedule} SET next = 0");
473

    
474
    return array(
475
      'time' => $time,
476
      'nids' => $nids,
477
      'count' => $count,
478
    );
479
  }
480

    
481
}