summaryrefslogtreecommitdiffstatshomepage
path: root/core/modules/migrate/tests/src/Unit/MigrateSourceTest.php
blob: 77e4cf64e64f5915f9cf33680af5b0a3fda901a0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
<?php

declare(strict_types=1);

namespace Drupal\Tests\migrate\Unit;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
use Drupal\Core\KeyValueStore\KeyValueStoreInterface;
use Drupal\migrate\Event\MigrateRollbackEvent;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutable;
use Drupal\migrate\MigrateSkipRowException;
use Drupal\migrate\Plugin\migrate\source\SourcePluginBase;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
use Drupal\migrate\Plugin\MigrateSourceInterface;
use Drupal\migrate\Row;

/**
 * @coversDefaultClass \Drupal\migrate\Plugin\migrate\source\SourcePluginBase
 * @group migrate
 */
class MigrateSourceTest extends MigrateTestCase {

  /**
   * Override the migration config.
   *
   * @var array
   */
  protected $defaultMigrationConfiguration = [
    'id' => 'test_migration',
    'source' => [],
  ];

  /**
   * Test row data.
   *
   * @var array
   */
  protected $row = ['test_sourceid1' => '1', 'timestamp' => 500];

  /**
   * Test source ids.
   *
   * @var array
   */
  protected $sourceIds = ['test_sourceid1' => 'test_sourceid1'];

  /**
   * The migration entity.
   *
   * @var \Drupal\migrate\Plugin\MigrationInterface
   */
  protected $migration;

  /**
   * The migrate executable.
   *
   * @var \Drupal\migrate\MigrateExecutable
   */
  protected $executable;

  /**
   * Gets the source plugin to test.
   *
   * @param array $configuration
   *   (optional) The source configuration. Defaults to an empty array.
   * @param array $migrate_config
   *   (optional) The migration configuration to be used in
   *   parent::getMigration(). Defaults to an empty array.
   * @param int $status
   *   (optional) The default status for the new rows to be imported. Defaults
   *   to MigrateIdMapInterface::STATUS_NEEDS_UPDATE.
   * @param int $high_water_value
   *   (optional) The high water mark to start from, if set.
   *
   * @return \Drupal\migrate\Plugin\MigrateSourceInterface
   *   A mocked source plugin.
   */
  protected function getSource($configuration = [], $migrate_config = [], $status = MigrateIdMapInterface::STATUS_NEEDS_UPDATE, $high_water_value = NULL) {
    $container = new ContainerBuilder();
    \Drupal::setContainer($container);

    $key_value = $this->createMock(KeyValueStoreInterface::class);

    $key_value_factory = $this->createMock(KeyValueFactoryInterface::class);
    $key_value_factory
      ->method('get')
      ->with('migrate:high_water')
      ->willReturn($key_value);
    $container->set('keyvalue', $key_value_factory);

    $container->set('cache.migrate', $this->createMock(CacheBackendInterface::class));

    $this->migrationConfiguration = $this->defaultMigrationConfiguration + $migrate_config;
    $this->migration = parent::getMigration();
    $this->executable = $this->getMigrateExecutable($this->migration);

    // Update the idMap for Source so the default is that the row has already
    // been imported. This allows us to use the highwater mark to decide on the
    // outcome of whether we choose to import the row.
    $id_map_array = ['original_hash' => '', 'hash' => '', 'source_row_status' => $status];
    $this->idMap
      ->expects($this->any())
      ->method('getRowBySource')
      ->willReturn($id_map_array);

    $constructor_args = [$configuration, 'd6_action', [], $this->migration];
    $methods = ['getModuleHandler', 'fields', 'getIds', '__toString', 'prepareRow', 'initializeIterator'];
    $source_plugin = $this->getMockBuilder(SourcePluginBase::class)
      ->onlyMethods($methods)
      ->setConstructorArgs($constructor_args)
      ->getMock();

    $source_plugin
      ->method('fields')
      ->willReturn([]);
    $source_plugin
      ->method('getIds')
      ->willReturn([]);
    $source_plugin
      ->method('__toString')
      ->willReturn('');
    $source_plugin
      ->method('prepareRow')
      ->willReturn(empty($migrate_config['prepare_row_false']));

    $rows = [$this->row];
    if (isset($configuration['high_water_property']) && isset($high_water_value)) {
      $property = $configuration['high_water_property']['name'];
      $rows = array_filter($rows, function (array $row) use ($property, $high_water_value) {
        return $row[$property] >= $high_water_value;
      });
    }
    $iterator = new \ArrayIterator($rows);

    $source_plugin
      ->method('initializeIterator')
      ->willReturn($iterator);

    $module_handler = $this->createMock(ModuleHandlerInterface::class);
    $source_plugin
      ->method('getModuleHandler')
      ->willReturn($module_handler);

    $this->migration
      ->method('getSourcePlugin')
      ->willReturn($source_plugin);

    return $source_plugin;
  }

  /**
   * @covers ::__construct
   */
  public function testHighwaterTrackChangesIncompatible(): void {
    $source_config = ['track_changes' => TRUE, 'high_water_property' => ['name' => 'something']];
    $this->expectException(MigrateException::class);
    $this->getSource($source_config);
  }

  /**
   * Tests that the source count is correct.
   *
   * @covers ::count
   */
  public function testCount(): void {
    // Mock the cache to validate set() receives appropriate arguments.
    $container = new ContainerBuilder();
    $cache = $this->createMock(CacheBackendInterface::class);
    $cache->expects($this->any())->method('set')
      ->with($this->isType('string'), $this->isType('int'), $this->isType('int'));
    $container->set('cache.migrate', $cache);
    \Drupal::setContainer($container);

    // Test that the basic count works.
    $source = $this->getSource();
    $this->assertEquals(1, $source->count());

    // Test caching the count works.
    $source = $this->getSource(['cache_counts' => TRUE]);
    $this->assertEquals(1, $source->count());

    // Test the skip argument.
    $source = $this->getSource(['skip_count' => TRUE]);
    $this->assertEquals(MigrateSourceInterface::NOT_COUNTABLE, $source->count());

    $this->migrationConfiguration['id'] = 'test_migration';
    $migration = $this->getMigration();
    $source = new StubSourceGeneratorPlugin([], '', [], $migration);

    // Test the skipCount property's default value.
    $this->assertEquals(MigrateSourceInterface::NOT_COUNTABLE, $source->count());

    // Test the count value using a generator.
    $source = new StubSourceGeneratorPlugin(['skip_count' => FALSE], '', [], $migration);
    $this->assertEquals(3, $source->count());
  }

  /**
   * Tests that the key can be set for the count cache.
   *
   * @covers ::count
   */
  public function testCountCacheKey(): void {
    // Mock the cache to validate set() receives appropriate arguments.
    $container = new ContainerBuilder();
    $cache = $this->createMock(CacheBackendInterface::class);
    $cache->expects($this->any())->method('set')
      ->with('test_key', $this->isType('int'), $this->isType('int'));
    $container->set('cache.migrate', $cache);
    \Drupal::setContainer($container);

    // Test caching the count with a configured key works.
    $source = $this->getSource(['cache_counts' => TRUE, 'cache_key' => 'test_key']);
    $this->assertEquals(1, $source->count());
  }

  /**
   * Tests that we don't get a row if prepareRow() is false.
   */
  public function testPrepareRowFalse(): void {
    $source = $this->getSource([], ['prepare_row_false' => TRUE]);

    $source->rewind();
    $this->assertNull($source->current(), 'No row is available when prepareRow() is false.');
  }

  /**
   * Tests that $row->needsUpdate() works as expected.
   */
  public function testNextNeedsUpdate(): void {
    $source = $this->getSource();

    // $row->needsUpdate() === TRUE so we get a row.
    $source->rewind();
    $this->assertTrue(is_a($source->current(), 'Drupal\migrate\Row'), '$row->needsUpdate() is TRUE so we got a row.');

    // Test that we don't get a row when the incoming row is marked as imported.
    $source = $this->getSource([], [], MigrateIdMapInterface::STATUS_IMPORTED);
    $source->rewind();
    $this->assertNull($source->current(), 'Row was already imported, should be NULL');
  }

  /**
   * Tests that an outdated highwater mark does not cause a row to be imported.
   */
  public function testOutdatedHighwater(): void {
    $configuration = [
      'high_water_property' => [
        'name' => 'timestamp',
      ],
    ];
    $source = $this->getSource($configuration, [], MigrateIdMapInterface::STATUS_IMPORTED, $this->row['timestamp'] + 1);

    // The current highwater mark is now higher than the row timestamp so no row
    // is expected.
    $source->rewind();
    $this->assertNull($source->current(), 'Original highwater mark is higher than incoming row timestamp.');
  }

  /**
   * Tests that a highwater mark newer than our saved one imports a row.
   *
   * @throws \Exception
   */
  public function testNewHighwater(): void {
    $configuration = [
      'high_water_property' => [
        'name' => 'timestamp',
      ],
    ];
    // Set a highwater property field for source. Now we should have a row
    // because the row timestamp is greater than the current highwater mark.
    $source = $this->getSource($configuration, [], MigrateIdMapInterface::STATUS_IMPORTED, $this->row['timestamp'] - 1);

    $source->rewind();
    $this->assertInstanceOf(Row::class, $source->current());
  }

  /**
   * Tests basic row preparation.
   *
   * @covers ::prepareRow
   */
  public function testPrepareRow(): void {
    $this->migrationConfiguration['id'] = 'test_migration';

    // Get a new migration with an id.
    $migration = $this->getMigration();
    $source = new StubSourcePlugin([], '', [], $migration);
    $row = new Row();

    $module_handler = $this->prophesize(ModuleHandlerInterface::class);
    $module_handler->invokeAll('migrate_prepare_row', [$row, $source, $migration])
      ->willReturn([TRUE, TRUE])
      ->shouldBeCalled();
    $module_handler->invokeAll('migrate_' . $migration->id() . '_prepare_row', [$row, $source, $migration])
      ->willReturn([TRUE, TRUE])
      ->shouldBeCalled();
    $source->setModuleHandler($module_handler->reveal());

    // Ensure we don't log this to the mapping table.
    $this->idMap->expects($this->never())
      ->method('saveIdMapping');

    $this->assertTrue($source->prepareRow($row));

    // Track_changes...
    $source = new StubSourcePlugin(['track_changes' => TRUE], '', [], $migration);
    $row2 = $this->prophesize(Row::class);
    $row2->rehash()
      ->shouldBeCalled();
    $module_handler->invokeAll('migrate_prepare_row', [$row2, $source, $migration])
      ->willReturn([TRUE, TRUE])
      ->shouldBeCalled();
    $module_handler->invokeAll('migrate_' . $migration->id() . '_prepare_row', [$row2, $source, $migration])
      ->willReturn([TRUE, TRUE])
      ->shouldBeCalled();
    $source->setModuleHandler($module_handler->reveal());
    $this->assertTrue($source->prepareRow($row2->reveal()));
  }

  /**
   * Tests that global prepare hooks can skip rows.
   *
   * @covers ::prepareRow
   */
  public function testPrepareRowGlobalPrepareSkip(): void {
    $this->migrationConfiguration['id'] = 'test_migration';

    $migration = $this->getMigration();
    $source = new StubSourcePlugin([], '', [], $migration);
    $row = new Row();

    $module_handler = $this->prophesize(ModuleHandlerInterface::class);
    // Return a failure from a prepare row hook.
    $module_handler->invokeAll('migrate_prepare_row', [$row, $source, $migration])
      ->willReturn([TRUE, FALSE, TRUE])
      ->shouldBeCalled();
    $module_handler->invokeAll('migrate_' . $migration->id() . '_prepare_row', [$row, $source, $migration])
      ->willReturn([TRUE, TRUE])
      ->shouldBeCalled();
    $source->setModuleHandler($module_handler->reveal());

    $this->idMap->expects($this->once())
      ->method('saveIdMapping')
      ->with($row, [], MigrateIdMapInterface::STATUS_IGNORED);

    $this->assertFalse($source->prepareRow($row));
  }

  /**
   * Tests that migrate specific prepare hooks can skip rows.
   *
   * @covers ::prepareRow
   */
  public function testPrepareRowMigratePrepareSkip(): void {
    $this->migrationConfiguration['id'] = 'test_migration';

    $migration = $this->getMigration();
    $source = new StubSourcePlugin([], '', [], $migration);
    $row = new Row();

    $module_handler = $this->prophesize(ModuleHandlerInterface::class);
    // Return a failure from a prepare row hook.
    $module_handler->invokeAll('migrate_prepare_row', [$row, $source, $migration])
      ->willReturn([TRUE, TRUE])
      ->shouldBeCalled();
    $module_handler->invokeAll('migrate_' . $migration->id() . '_prepare_row', [$row, $source, $migration])
      ->willReturn([TRUE, FALSE, TRUE])
      ->shouldBeCalled();
    $source->setModuleHandler($module_handler->reveal());

    $this->idMap->expects($this->once())
      ->method('saveIdMapping')
      ->with($row, [], MigrateIdMapInterface::STATUS_IGNORED);

    $this->assertFalse($source->prepareRow($row));
  }

  /**
   * Tests that a skip exception during prepare hooks correctly skips.
   *
   * @covers ::prepareRow
   */
  public function testPrepareRowPrepareException(): void {
    $this->migrationConfiguration['id'] = 'test_migration';

    $migration = $this->getMigration();
    $source = new StubSourcePlugin([], '', [], $migration);
    $row = new Row();

    $module_handler = $this->prophesize(ModuleHandlerInterface::class);
    // Return a failure from a prepare row hook.
    $module_handler->invokeAll('migrate_prepare_row', [$row, $source, $migration])
      ->willReturn([TRUE, TRUE])
      ->shouldBeCalled();
    $module_handler->invokeAll('migrate_' . $migration->id() . '_prepare_row', [$row, $source, $migration])
      ->willThrow(new MigrateSkipRowException())
      ->shouldBeCalled();
    $source->setModuleHandler($module_handler->reveal());

    // This will only be called on the first prepare because the second
    // explicitly avoids it.
    $this->idMap->expects($this->once())
      ->method('saveIdMapping')
      ->with($row, [], MigrateIdMapInterface::STATUS_IGNORED);
    $this->assertFalse($source->prepareRow($row));

    // Throw an exception the second time that avoids mapping.
    $e = new MigrateSkipRowException('', FALSE);
    $module_handler->invokeAll('migrate_' . $migration->id() . '_prepare_row', [$row, $source, $migration])
      ->willThrow($e)
      ->shouldBeCalled();
    $this->assertFalse($source->prepareRow($row));
  }

  /**
   * Tests that default values are preserved for several source methods.
   */
  public function testDefaultPropertiesValues(): void {
    $this->migrationConfiguration['id'] = 'test_migration';
    $migration = $this->getMigration();
    $source = new StubSourceGeneratorPlugin([], '', [], $migration);

    // Test the default value of the skipCount Value.
    $this->assertTrue($source->getSkipCount());
    $this->assertTrue($source->getCacheCounts());
    $this->assertTrue($source->getTrackChanges());
  }

  /**
   * Gets a mock executable for the test.
   *
   * @param \Drupal\migrate\Plugin\MigrationInterface $migration
   *   The migration entity.
   *
   * @return \Drupal\migrate\MigrateExecutable
   *   The migrate executable.
   */
  protected function getMigrateExecutable($migration) {
    /** @var \Drupal\migrate\MigrateMessageInterface $message */
    $message = $this->createMock('Drupal\migrate\MigrateMessageInterface');
    /** @var \Symfony\Contracts\EventDispatcher\EventDispatcherInterface $event_dispatcher */
    $event_dispatcher = $this->createMock('Symfony\Contracts\EventDispatcher\EventDispatcherInterface');
    return new MigrateExecutable($migration, $message, $event_dispatcher);
  }

  /**
   * @covers ::preRollback
   */
  public function testPreRollback(): void {
    $this->migrationConfiguration['id'] = 'test_migration';
    $plugin_id = 'test_migration';
    $migration = $this->getMigration();

    // Verify that preRollback() sets the high water mark to NULL.
    $key_value = $this->createMock(KeyValueStoreInterface::class);
    $key_value->expects($this->once())
      ->method('set')
      ->with($plugin_id, NULL);
    $key_value_factory = $this->createMock(KeyValueFactoryInterface::class);
    $key_value_factory->expects($this->once())
      ->method('get')
      ->with('migrate:high_water')
      ->willReturn($key_value);
    $container = new ContainerBuilder();
    $container->set('keyvalue', $key_value_factory);
    \Drupal::setContainer($container);

    $source = new StubSourceGeneratorPlugin([], $plugin_id, [], $migration);
    $source->preRollback(new MigrateRollbackEvent($migration));
  }

}

/**
 * Defines a stubbed source plugin with a generator as iterator.
 *
 * This stub overwrites the $skipCount, $cacheCounts, and $trackChanges
 * properties.
 */
class StubSourceGeneratorPlugin extends StubSourcePlugin {

  /**
   * {@inheritdoc}
   */
  protected $skipCount = TRUE;

  /**
   * {@inheritdoc}
   */
  protected $cacheCounts = TRUE;

  /**
   * {@inheritdoc}
   */
  protected $trackChanges = TRUE;

  /**
   * Return the skipCount value.
   */
  public function getSkipCount() {
    return $this->skipCount;
  }

  /**
   * Return the cacheCounts value.
   */
  public function getCacheCounts() {
    return $this->cacheCounts;
  }

  /**
   * Return the trackChanges value.
   */
  public function getTrackChanges() {
    return $this->trackChanges;
  }

  /**
   * {@inheritdoc}
   */
  protected function initializeIterator(): \Generator {
    yield 'foo';
    yield 'bar';
    yield 'iggy';
  }

}