Update core 8.3.0

This commit is contained in:
Rob Davies 2017-04-13 15:53:35 +01:00
parent da7a7918f8
commit cd7a898e66
6144 changed files with 132297 additions and 87747 deletions

View file

@ -32,7 +32,7 @@ class DummyDestination extends DestinationBase {
/**
* {@inheritdoc}
*/
public function import(Row $row, array $old_destination_id_values = array()) {
public function import(Row $row, array $old_destination_id_values = []) {
return ['value' => $row->getDestinationProperty('value')];
}

View file

@ -0,0 +1,68 @@
<?php
namespace Drupal\Tests\migrate\Kernel;
/**
* Tests the high water handling.
*
* @covers \Drupal\migrate_sql_test\Plugin\migrate\source\HighWaterTest
* @group migrate
*/
class HighWaterNotJoinableTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['migrate', 'migrate_drupal', 'migrate_sql_test'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['high_water_node'] = [
[
'id' => 1,
'title' => 'Item 1',
'changed' => 1,
],
[
'id' => 2,
'title' => 'Item 2',
'changed' => 2,
],
[
'id' => 3,
'title' => 'Item 3',
'changed' => 3,
],
];
// The expected results.
$tests[0]['expected_data'] = [
[
'id' => 2,
'title' => 'Item 2',
'changed' => 2,
],
[
'id' => 3,
'title' => 'Item 3',
'changed' => 3,
],
];
$tests[0]['expected_count'] = NULL;
$tests[0]['configuration'] = [
'high_water_property' => [
'name' => 'changed',
],
];
$tests[0]['high_water'] = $tests[0]['source_data']['high_water_node'][0]['changed'];
return $tests;
}
}

View file

@ -136,6 +136,64 @@ class HighWaterTest extends MigrateTestBase {
$this->assertNodeDoesNotExist('Item 3');
}
/**
* Tests high water property of SqlBase when rows marked for update.
*/
public function testHighWaterUpdate() {
// Assert all of the nodes have been imported.
$this->assertNodeExists('Item 1');
$this->assertNodeExists('Item 2');
$this->assertNodeExists('Item 3');
// Update Item 1 setting its high_water_property to value that is below
// current high water mark.
$this->sourceDatabase->update('high_water_node')
->fields([
'title' => 'Item 1 updated',
'changed' => 2,
])
->condition('title', 'Item 1')
->execute();
// Update Item 2 setting its high_water_property to value equal to
// current high water mark.
$this->sourceDatabase->update('high_water_node')
->fields([
'title' => 'Item 2 updated',
'changed' => 3,
])
->condition('title', 'Item 2')
->execute();
// Update Item 3 setting its high_water_property to value that is above
// current high water mark.
$this->sourceDatabase->update('high_water_node')
->fields([
'title' => 'Item 3 updated',
'changed' => 4,
])
->condition('title', 'Item 3')
->execute();
// Set all rows as needing an update.
$id_map = $this->getMigration('high_water_test')->getIdMap();
$id_map->prepareUpdate();
$this->executeMigration('high_water_test');
// Item with lower highwater should be updated.
$this->assertNodeExists('Item 1 updated');
$this->assertNodeDoesNotExist('Item 1');
// Item with equal highwater should be updated.
$this->assertNodeExists('Item 2 updated');
$this->assertNodeDoesNotExist('Item 2');
// Item with greater highwater should be updated.
$this->assertNodeExists('Item 3 updated');
$this->assertNodeDoesNotExist('Item 3');
}
/**
* Assert that node with given title exists.
*

View file

@ -40,17 +40,17 @@ class MigrateEventsTest extends KernelTestBase {
parent::setUp();
$this->state = \Drupal::state();
\Drupal::service('event_dispatcher')->addListener(MigrateEvents::MAP_SAVE,
array($this, 'mapSaveEventRecorder'));
[$this, 'mapSaveEventRecorder']);
\Drupal::service('event_dispatcher')->addListener(MigrateEvents::MAP_DELETE,
array($this, 'mapDeleteEventRecorder'));
[$this, 'mapDeleteEventRecorder']);
\Drupal::service('event_dispatcher')->addListener(MigrateEvents::PRE_IMPORT,
array($this, 'preImportEventRecorder'));
[$this, 'preImportEventRecorder']);
\Drupal::service('event_dispatcher')->addListener(MigrateEvents::POST_IMPORT,
array($this, 'postImportEventRecorder'));
[$this, 'postImportEventRecorder']);
\Drupal::service('event_dispatcher')->addListener(MigrateEvents::PRE_ROW_SAVE,
array($this, 'preRowSaveEventRecorder'));
[$this, 'preRowSaveEventRecorder']);
\Drupal::service('event_dispatcher')->addListener(MigrateEvents::POST_ROW_SAVE,
array($this, 'postRowSaveEventRecorder'));
[$this, 'postRowSaveEventRecorder']);
}
/**
@ -129,11 +129,11 @@ class MigrateEventsTest extends KernelTestBase {
* The event name.
*/
public function mapSaveEventRecorder(MigrateMapSaveEvent $event, $name) {
$this->state->set('migrate_events_test.map_save_event', array(
$this->state->set('migrate_events_test.map_save_event', [
'event_name' => $name,
'map' => $event->getMap(),
'fields' => $event->getFields(),
));
]);
}
/**
@ -145,11 +145,11 @@ class MigrateEventsTest extends KernelTestBase {
* The event name.
*/
public function mapDeleteEventRecorder(MigrateMapDeleteEvent $event, $name) {
$this->state->set('migrate_events_test.map_delete_event', array(
$this->state->set('migrate_events_test.map_delete_event', [
'event_name' => $name,
'map' => $event->getMap(),
'source_id' => $event->getSourceId(),
));
]);
}
/**
@ -161,10 +161,10 @@ class MigrateEventsTest extends KernelTestBase {
* The event name.
*/
public function preImportEventRecorder(MigrateImportEvent $event, $name) {
$this->state->set('migrate_events_test.pre_import_event', array(
$this->state->set('migrate_events_test.pre_import_event', [
'event_name' => $name,
'migration' => $event->getMigration(),
));
]);
}
/**
@ -176,10 +176,10 @@ class MigrateEventsTest extends KernelTestBase {
* The event name.
*/
public function postImportEventRecorder(MigrateImportEvent $event, $name) {
$this->state->set('migrate_events_test.post_import_event', array(
$this->state->set('migrate_events_test.post_import_event', [
'event_name' => $name,
'migration' => $event->getMigration(),
));
]);
}
/**
@ -191,11 +191,11 @@ class MigrateEventsTest extends KernelTestBase {
* The event name.
*/
public function preRowSaveEventRecorder(MigratePreRowSaveEvent $event, $name) {
$this->state->set('migrate_events_test.pre_row_save_event', array(
$this->state->set('migrate_events_test.pre_row_save_event', [
'event_name' => $name,
'migration' => $event->getMigration(),
'row' => $event->getRow(),
));
]);
}
/**
@ -207,12 +207,12 @@ class MigrateEventsTest extends KernelTestBase {
* The event name.
*/
public function postRowSaveEventRecorder(MigratePostRowSaveEvent $event, $name) {
$this->state->set('migrate_events_test.post_row_save_event', array(
$this->state->set('migrate_events_test.post_row_save_event', [
'event_name' => $name,
'migration' => $event->getMigration(),
'row' => $event->getRow(),
'destination_id_values' => $event->getDestinationIdValues(),
));
]);
}
}

View file

@ -18,11 +18,8 @@ class MigrateExternalTranslatedTest extends MigrateTestBase {
/**
* {@inheritdoc}
*
* @todo: Remove migrate_drupal when https://www.drupal.org/node/2560795 is
* fixed.
*/
public static $modules = ['system', 'user', 'language', 'node', 'field', 'migrate_drupal', 'migrate_external_translated_test'];
public static $modules = ['system', 'user', 'language', 'node', 'field', 'migrate_external_translated_test'];
/**
* {@inheritdoc}
@ -30,7 +27,7 @@ class MigrateExternalTranslatedTest extends MigrateTestBase {
public function setUp() {
parent::setUp();
$this->installSchema('system', ['sequences']);
$this->installSchema('node', array('node_access'));
$this->installSchema('node', ['node_access']);
$this->installEntitySchema('user');
$this->installEntitySchema('node');

View file

@ -29,7 +29,7 @@ class MigrateInterruptionTest extends KernelTestBase {
protected function setUp() {
parent::setUp();
\Drupal::service('event_dispatcher')->addListener(MigrateEvents::POST_ROW_SAVE,
array($this, 'postRowSaveEventRecorder'));
[$this, 'postRowSaveEventRecorder']);
}
/**

View file

@ -89,7 +89,7 @@ class MigrateMessageTest extends KernelTestBase implements MigrateMessageInterfa
public function testMessagesTeed() {
// Ask to receive any messages sent to the idmap.
\Drupal::service('event_dispatcher')->addListener(MigrateEvents::IDMAP_MESSAGE,
array($this, 'mapMessageRecorder'));
[$this, 'mapMessageRecorder']);
$executable = new MigrateExecutable($this->migration, $this);
$executable->import();
$this->assertIdentical(count($this->messages), 1);

View file

@ -0,0 +1,168 @@
<?php
namespace Drupal\Tests\migrate\Kernel;
use Drupal\migrate\MigrateExecutable;
use Drupal\taxonomy\Entity\Vocabulary;
/**
* Tests rolling back of imports.
*
* @group migrate
*/
class MigrateRollbackEntityConfigTest extends MigrateTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['field', 'taxonomy', 'text', 'language', 'config_translation'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installEntitySchema('taxonomy_vocabulary');
$this->installEntitySchema('taxonomy_term');
$this->installConfig(['taxonomy']);
}
/**
* Tests rolling back configuration entity translations.
*/
public function testConfigEntityRollback() {
// We use vocabularies to demonstrate importing and rolling back
// configuration entities with translations. First, import vocabularies.
$vocabulary_data_rows = [
['id' => '1', 'name' => 'categories', 'weight' => '2'],
['id' => '2', 'name' => 'tags', 'weight' => '1'],
];
$ids = ['id' => ['type' => 'integer']];
$definition = [
'id' => 'vocabularies',
'migration_tags' => ['Import and rollback test'],
'source' => [
'plugin' => 'embedded_data',
'data_rows' => $vocabulary_data_rows,
'ids' => $ids,
],
'process' => [
'vid' => 'id',
'name' => 'name',
'weight' => 'weight',
],
'destination' => ['plugin' => 'entity:taxonomy_vocabulary'],
];
/** @var \Drupal\migrate\Plugin\Migration $vocabulary_migration */
$vocabulary_migration = \Drupal::service('plugin.manager.migration')
->createStubMigration($definition);
$vocabulary_id_map = $vocabulary_migration->getIdMap();
$this->assertTrue($vocabulary_migration->getDestinationPlugin()
->supportsRollback());
// Import and validate vocabulary config entities were created.
$vocabulary_executable = new MigrateExecutable($vocabulary_migration, $this);
$vocabulary_executable->import();
foreach ($vocabulary_data_rows as $row) {
/** @var \Drupal\taxonomy\Entity\Vocabulary $vocabulary */
$vocabulary = Vocabulary::load($row['id']);
$this->assertTrue($vocabulary);
$map_row = $vocabulary_id_map->getRowBySource(['id' => $row['id']]);
$this->assertNotNull($map_row['destid1']);
}
// Second, import translations of the vocabulary name property.
$vocabulary_i18n_data_rows = [
[
'id' => '1',
'name' => '1',
'language' => 'fr',
'property' => 'name',
'translation' => 'fr - categories'
],
[
'id' => '2',
'name' => '2',
'language' => 'fr',
'property' => 'name',
'translation' => 'fr - tags'
],
];
$ids = [
'id' => ['type' => 'integer'],
'language' => ['type' => 'string'],
];
$definition = [
'id' => 'i18n_vocabularies',
'migration_tags' => ['Import and rollback test'],
'source' => [
'plugin' => 'embedded_data',
'data_rows' => $vocabulary_i18n_data_rows,
'ids' => $ids,
'constants' => [
'name' => 'name',
]
],
'process' => [
'vid' => 'id',
'langcode' => 'language',
'property' => 'constants/name',
'translation' => 'translation',
],
'destination' => [
'plugin' => 'entity:taxonomy_vocabulary',
'translations' => 'true',
],
];
$vocabulary_i18n__migration = \Drupal::service('plugin.manager.migration')
->createStubMigration($definition);
$vocabulary_i18n_id_map = $vocabulary_i18n__migration->getIdMap();
$this->assertTrue($vocabulary_i18n__migration->getDestinationPlugin()
->supportsRollback());
// Import and validate vocabulary config entities were created.
$vocabulary_i18n_executable = new MigrateExecutable($vocabulary_i18n__migration, $this);
$vocabulary_i18n_executable->import();
$language_manager = \Drupal::service('language_manager');
foreach ($vocabulary_i18n_data_rows as $row) {
$langcode = $row['language'];
$id = 'taxonomy.vocabulary.' . $row['id'];
/** @var \Drupal\language\Config\LanguageConfigOverride $config_translation */
$config_translation = $language_manager->getLanguageConfigOverride($langcode, $id);
$this->assertSame($row['translation'], $config_translation->get('name'));
$map_row = $vocabulary_i18n_id_map->getRowBySource(['id' => $row['id'], 'language' => $row['language']]);
$this->assertNotNull($map_row['destid1']);
}
// Perform the rollback and confirm the translation was deleted and the map
// table row removed.
$vocabulary_i18n_executable->rollback();
foreach ($vocabulary_i18n_data_rows as $row) {
$langcode = $row['language'];
$id = 'taxonomy.vocabulary.' . $row['id'];
/** @var \Drupal\language\Config\LanguageConfigOverride $config_translation */
$config_translation = $language_manager->getLanguageConfigOverride($langcode, $id);
$this->assertNull($config_translation->get('name'));
$map_row = $vocabulary_i18n_id_map->getRowBySource(['id' => $row['id'], 'language' => $row['language']]);
$this->assertFalse($map_row);
}
// Confirm the original vocabulary still exists.
foreach ($vocabulary_data_rows as $row) {
/** @var \Drupal\taxonomy\Entity\Vocabulary $vocabulary */
$vocabulary = Vocabulary::load($row['id']);
$this->assertTrue($vocabulary);
$map_row = $vocabulary_id_map->getRowBySource(['id' => $row['id']]);
$this->assertNotNull($map_row['destid1']);
}
}
}

View file

@ -135,23 +135,33 @@ abstract class MigrateSourceTestBase extends KernelTestBase {
* value (like FALSE or 'nope'), the source plugin will not be counted.
* @param array $configuration
* (optional) Configuration for the source plugin.
* @param mixed $high_water
* (optional) The value of the high water field.
*
* @dataProvider providerSource
*/
public function testSource(array $source_data, array $expected_data, $expected_count = NULL, array $configuration = []) {
public function testSource(array $source_data, array $expected_data, $expected_count = NULL, array $configuration = [], $high_water = NULL) {
$plugin = $this->getPlugin($configuration);
// All source plugins must define IDs.
$this->assertNotEmpty($plugin->getIds());
// If there is a high water mark, set it in the high water storage.
if (isset($high_water)) {
$this->container
->get('keyvalue')
->get('migrate:high_water')
->set($this->migration->reveal()->id(), $high_water);
}
if (is_null($expected_count)) {
$expected_count = count($expected_data);
}
// If an expected count was given, assert it only if the plugin is
// countable.
if (is_numeric($expected_count)) {
$this->assertInstanceOf('\Countable', $plugin);
$this->assertCount($expected_count, $plugin);
$this->assertInstanceOf('\Iterator', $plugin);
$this->assertSame($expected_count, iterator_count($plugin));
}
$i = 0;

View file

@ -63,12 +63,14 @@ abstract class MigrateSqlSourceTestBase extends MigrateSourceTestBase {
* (optional) How many rows the source plugin is expected to return.
* @param array $configuration
* (optional) Configuration for the source plugin.
* @param mixed $high_water
* (optional) The value of the high water field.
*
* @dataProvider providerSource
*
* @requires extension pdo_sqlite
*/
public function testSource(array $source_data, array $expected_data, $expected_count = NULL, array $configuration = []) {
public function testSource(array $source_data, array $expected_data, $expected_count = NULL, array $configuration = [], $high_water = NULL) {
$plugin = $this->getPlugin($configuration);
// Since we don't yet inject the database connection, we need to use a
@ -78,7 +80,7 @@ abstract class MigrateSqlSourceTestBase extends MigrateSourceTestBase {
$property->setAccessible(TRUE);
$property->setValue($plugin, $this->getDatabase($source_data));
parent::testSource($source_data, $expected_data, $expected_count, $configuration);
parent::testSource($source_data, $expected_data, $expected_count, $configuration, $high_water);
}
}

View file

@ -33,13 +33,13 @@ class MigrateStatusTest extends MigrateTestBase {
$this->assertIdentical($status, MigrationInterface::STATUS_IDLE);
// Test setting and retrieving all known status values.
$status_list = array(
$status_list = [
MigrationInterface::STATUS_IDLE,
MigrationInterface::STATUS_IMPORTING,
MigrationInterface::STATUS_ROLLING_BACK,
MigrationInterface::STATUS_STOPPING,
MigrationInterface::STATUS_DISABLED,
);
];
foreach ($status_list as $status) {
$migration->setStatus($status);
$this->assertIdentical($migration->getStatus(), $status);

View file

@ -47,7 +47,7 @@ abstract class MigrateTestBase extends KernelTestBase implements MigrateMessageI
*/
protected $sourceDatabase;
public static $modules = array('migrate');
public static $modules = ['migrate'];
/**
* {@inheritdoc}
@ -201,7 +201,7 @@ abstract class MigrateTestBase extends KernelTestBase implements MigrateMessageI
*/
public function startCollectingMessages() {
$this->collectMessages = TRUE;
$this->migrateMessages = array();
$this->migrateMessages = [];
}
/**

View file

@ -4,6 +4,9 @@ namespace Drupal\Tests\migrate\Kernel\Plugin;
use Drupal\Core\Database\Database;
use Drupal\KernelTests\KernelTestBase;
use Drupal\migrate\Exception\RequirementsException;
use Drupal\migrate\Plugin\migrate\source\SqlBase;
use Drupal\migrate\Plugin\RequirementsInterface;
/**
* Tests the migration plugin manager.
@ -79,6 +82,31 @@ class MigrationPluginListTest extends KernelTestBase {
// Enable migrate_drupal to test that the plugins can now be discovered.
$this->enableModules(['migrate_drupal']);
// Make sure retrieving these migration plugins in the absence of a database
// connection does not throw any errors.
$migration_plugins = $this->container->get('plugin.manager.migration')->createInstances([]);
// Any database-based source plugins should fail a requirements test in the
// absence of a source database connection (e.g., a connection with the
// 'migrate' key).
$source_plugins = array_map(function ($migration_plugin) { return $migration_plugin->getSourcePlugin(); }, $migration_plugins);
foreach ($source_plugins as $id => $source_plugin) {
if ($source_plugin instanceof RequirementsInterface) {
try {
$source_plugin->checkRequirements();
}
catch (RequirementsException $e) {
unset($source_plugins[$id]);
}
}
}
// Without a connection defined, no database-based plugins should be
// returned.
foreach ($source_plugins as $id => $source_plugin) {
$this->assertNotInstanceOf(SqlBase::class, $source_plugin);
}
// Set up a migrate database connection so that plugin discovery works.
// Clone the current connection and replace the current prefix.
$connection_info = Database::getConnectionInfo('migrate');

View file

@ -30,7 +30,7 @@ class SqlBaseTest extends MigrateTestBase {
$target = 'test_db_target';
$key = 'test_migrate_connection';
$config = array('target' => $target, 'key' => $key);
$config = ['target' => $target, 'key' => $key];
$sql_base->setConfiguration($config);
Database::addConnectionInfo($key, $target, Database::getConnectionInfo('default')['default']);
@ -44,7 +44,7 @@ class SqlBaseTest extends MigrateTestBase {
$target = 'test_db_target2';
$key = 'test_migrate_connection2';
$database = Database::getConnectionInfo('default')['default'];
$config = array('target' => $target, 'key' => $key, 'database' => $database);
$config = ['target' => $target, 'key' => $key, 'database' => $database];
$sql_base->setConfiguration($config);
// Call getDatabase() to get the connection defined.

View file

@ -1,218 +0,0 @@
<?php
namespace Drupal\Tests\migrate\Kernel\process;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\KernelTests\KernelTestBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Plugin\migrate\process\FileCopy;
use Drupal\migrate\Row;
/**
* Tests the copy_file process plugin.
*
* @group migrate
*/
class CopyFileTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['migrate', 'system'];
/**
* The file system service.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->fileSystem = $this->container->get('file_system');
$this->container->get('stream_wrapper_manager')->registerWrapper('temporary', 'Drupal\Core\StreamWrapper\TemporaryStream', StreamWrapperInterface::LOCAL_NORMAL);
}
/**
* Test successful imports/copies.
*/
public function testSuccessfulCopies() {
$file = $this->createUri(NULL, NULL, 'temporary');
$file_absolute = $this->fileSystem->realpath($file);
$data_sets = [
// Test a local to local copy.
[
$this->root . '/core/modules/simpletest/files/image-test.jpg',
'public://file1.jpg'
],
// Test a temporary file using an absolute path.
[
$file_absolute,
'temporary://test.jpg'
],
// Test a temporary file using a relative path.
[
$file_absolute,
'temporary://core/modules/simpletest/files/test.jpg'
],
];
foreach ($data_sets as $data) {
list($source_path, $destination_path) = $data;
$actual_destination = $this->doImport($source_path, $destination_path);
$message = sprintf('File %s exists', $destination_path);
$this->assertFileExists($destination_path, $message);
// Make sure we didn't accidentally do a move.
$this->assertFileExists($source_path, $message);
$this->assertSame($actual_destination, $destination_path, 'The import returned the copied filename.');
}
}
/**
* Test successful file reuse.
*/
public function testSuccessfulReuse() {
$source_path = $this->root . '/core/modules/simpletest/files/image-test.jpg';
$destination_path = 'public://file1.jpg';
$file_reuse = file_unmanaged_copy($source_path, $destination_path);
$timestamp = (new \SplFileInfo($file_reuse))->getMTime();
$this->assertInternalType('int', $timestamp);
// We need to make sure the modified timestamp on the file is sooner than
// the attempted migration.
sleep(1);
$configuration = ['reuse' => TRUE];
$this->doImport($source_path, $destination_path, $configuration);
clearstatcache(TRUE, $destination_path);
$modified_timestamp = (new \SplFileInfo($destination_path))->getMTime();
$this->assertEquals($timestamp, $modified_timestamp);
$configuration = ['reuse' => FALSE];
$this->doImport($source_path, $destination_path, $configuration);
clearstatcache(TRUE, $destination_path);
$modified_timestamp = (new \SplFileInfo($destination_path))->getMTime();
$this->assertGreaterThan($timestamp, $modified_timestamp);
}
/**
* Test successful moves.
*/
public function testSuccessfulMoves() {
$file_1 = $this->createUri(NULL, NULL, 'temporary');
$file_1_absolute = $this->fileSystem->realpath($file_1);
$file_2 = $this->createUri(NULL, NULL, 'temporary');
$file_2_absolute = $this->fileSystem->realpath($file_2);
$local_file = $this->createUri(NULL, NULL, 'public');
$data_sets = [
// Test a local to local copy.
[
$local_file,
'public://file1.jpg'
],
// Test a temporary file using an absolute path.
[
$file_1_absolute,
'temporary://test.jpg'
],
// Test a temporary file using a relative path.
[
$file_2_absolute,
'temporary://core/modules/simpletest/files/test.jpg'
],
];
foreach ($data_sets as $data) {
list($source_path, $destination_path) = $data;
$actual_destination = $this->doImport($source_path, $destination_path, ['move' => TRUE]);
$message = sprintf('File %s exists', $destination_path);
$this->assertFileExists($destination_path, $message);
$message = sprintf('File %s does not exist', $source_path);
$this->assertFileNotExists($source_path, $message);
$this->assertSame($actual_destination, $destination_path, 'The importer returned the moved filename.');
}
}
/**
* Test that non-existent files throw an exception.
*
* @expectedException \Drupal\migrate\MigrateException
*
* @expectedExceptionMessage File '/non/existent/file' does not exist
*/
public function testNonExistentSourceFile() {
$source = '/non/existent/file';
$this->doImport($source, 'public://wontmatter.jpg');
}
/**
* Test the 'rename' overwrite mode.
*/
public function testRenameFile() {
$source = $this->createUri(NULL, NULL, 'temporary');
$destination = $this->createUri('foo.txt', NULL, 'public');
$expected_destination = 'public://foo_0.txt';
$actual_destination = $this->doImport($source, $destination, ['rename' => TRUE]);
$this->assertFileExists($expected_destination, 'File was renamed on import');
$this->assertSame($actual_destination, $expected_destination, 'The importer returned the renamed filename.');
}
/**
* Do an import using the destination.
*
* @param string $source_path
* Source path to copy from.
* @param string $destination_path
* The destination path to copy to.
* @param array $configuration
* Process plugin configuration settings.
*
* @throws \Drupal\migrate\MigrateException
*/
protected function doImport($source_path, $destination_path, $configuration = []) {
$plugin = FileCopy::create($this->container, $configuration, 'file_copy', []);
$executable = $this->prophesize(MigrateExecutableInterface::class)->reveal();
$row = new Row();
$result = $plugin->transform([$source_path, $destination_path], $executable, $row, 'foobaz');
// Return the imported file Uri.
return $result;
}
/**
* Create a file and return the URI of it.
*
* @param $filepath
* Optional string specifying the file path. If none is provided then a
* randomly named file will be created in the site's files directory.
* @param $contents
* Optional contents to save into the file. If a NULL value is provided an
* arbitrary string will be used.
* @param $scheme
* Optional string indicating the stream scheme to use. Drupal core includes
* public, private, and temporary. The public wrapper is the default.
* @return
* File URI.
*/
protected function createUri($filepath = NULL, $contents = NULL, $scheme = NULL) {
if (!isset($filepath)) {
// Prefix with non-latin characters to ensure that all file-related
// tests work with international filenames.
$filepath = 'Файл для тестирования ' . $this->randomMachineName();
}
if (empty($scheme)) {
$scheme = file_default_scheme();
}
$filepath = $scheme . '://' . $filepath;
if (empty($contents)) {
$contents = "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.";
}
file_put_contents($filepath, $contents);
$this->assertFileExists($filepath, t('The test file exists on the disk.'));
return $filepath;
}
}

View file

@ -74,6 +74,32 @@ class FileCopyTest extends FileTestBase {
}
}
/**
* Test successful file reuse.
*/
public function testSuccessfulReuse() {
$source_path = $this->root . '/core/modules/simpletest/files/image-test.jpg';
$destination_path = 'public://file1.jpg';
$file_reuse = file_unmanaged_copy($source_path, $destination_path);
$timestamp = (new \SplFileInfo($file_reuse))->getMTime();
$this->assertInternalType('int', $timestamp);
// We need to make sure the modified timestamp on the file is sooner than
// the attempted migration.
sleep(1);
$configuration = ['reuse' => TRUE];
$this->doTransform($source_path, $destination_path, $configuration);
clearstatcache(TRUE, $destination_path);
$modified_timestamp = (new \SplFileInfo($destination_path))->getMTime();
$this->assertEquals($timestamp, $modified_timestamp);
$configuration = ['reuse' => FALSE];
$this->doTransform($source_path, $destination_path, $configuration);
clearstatcache(TRUE, $destination_path);
$modified_timestamp = (new \SplFileInfo($destination_path))->getMTime();
$this->assertGreaterThan($timestamp, $modified_timestamp);
}
/**
* Test successful moves.
*/
@ -113,13 +139,10 @@ class FileCopyTest extends FileTestBase {
/**
* Test that non-existent files throw an exception.
*
* @expectedException \Drupal\migrate\MigrateException
*
* @expectedExceptionMessage File '/non/existent/file' does not exist
*/
public function testNonExistentSourceFile() {
$source = '/non/existent/file';
$this->setExpectedException(MigrateException::class, "File '/non/existent/file' does not exist");
$this->doTransform($source, 'public://wontmatter.jpg');
}

View file

@ -259,7 +259,7 @@ class RouteTest extends KernelTestBase {
* @param array|string $value
* Source link path information.
*
* @return array $actual
* @return array
* The route information based on the source link_path.
*/
protected function doTransform($value) {

View file

@ -34,18 +34,18 @@ class RequirementsExceptionTest extends UnitTestCase {
* Provides a list of requirements to test.
*/
public function getRequirementsProvider() {
return array(
array(
return [
[
'requirements: random_jackson_pivot.',
'Single Requirement',
array('requirements' => $this->missingRequirements[0]),
),
array(
['requirements' => $this->missingRequirements[0]],
],
[
'requirements: random_jackson_pivot. requirements: 51_Eridani_b.',
'Multiple Requirements',
array('requirements' => $this->missingRequirements),
),
);
['requirements' => $this->missingRequirements],
],
];
}
}

View file

@ -35,9 +35,9 @@ class MigrateExecutableMemoryExceededTest extends MigrateTestCase {
*
* @var array
*/
protected $migrationConfiguration = array(
protected $migrationConfiguration = [
'id' => 'test',
);
];
/**
* The php.ini memory_limit value.

View file

@ -3,6 +3,7 @@
namespace Drupal\Tests\migrate\Unit;
use Drupal\Component\Utility\Html;
use Drupal\migrate\Plugin\MigrateProcessInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
use Drupal\migrate\MigrateException;
@ -40,9 +41,9 @@ class MigrateExecutableTest extends MigrateTestCase {
*
* @var array
*/
protected $migrationConfiguration = array(
protected $migrationConfiguration = [
'id' => 'test',
);
];
/**
* {@inheritdoc}
@ -91,12 +92,12 @@ class MigrateExecutableTest extends MigrateTestCase {
$row->expects($this->once())
->method('getSourceIdValues')
->will($this->returnValue(array('id' => 'test')));
->will($this->returnValue(['id' => 'test']));
$this->idMap->expects($this->once())
->method('lookupDestinationId')
->with(array('id' => 'test'))
->will($this->returnValue(array('test')));
->with(['id' => 'test'])
->will($this->returnValue(['test']));
$source->expects($this->once())
->method('current')
@ -106,13 +107,13 @@ class MigrateExecutableTest extends MigrateTestCase {
$this->migration->expects($this->once())
->method('getProcessPlugins')
->will($this->returnValue(array()));
->will($this->returnValue([]));
$destination = $this->getMock('Drupal\migrate\Plugin\MigrateDestinationInterface');
$destination->expects($this->once())
->method('import')
->with($row, array('test'))
->will($this->returnValue(array('id' => 'test')));
->with($row, ['test'])
->will($this->returnValue(['id' => 'test']));
$this->migration
->method('getDestinationPlugin')
@ -133,12 +134,12 @@ class MigrateExecutableTest extends MigrateTestCase {
$row->expects($this->once())
->method('getSourceIdValues')
->will($this->returnValue(array('id' => 'test')));
->will($this->returnValue(['id' => 'test']));
$this->idMap->expects($this->once())
->method('lookupDestinationId')
->with(array('id' => 'test'))
->will($this->returnValue(array('test')));
->with(['id' => 'test'])
->will($this->returnValue(['test']));
$source->expects($this->once())
->method('current')
@ -148,12 +149,12 @@ class MigrateExecutableTest extends MigrateTestCase {
$this->migration->expects($this->once())
->method('getProcessPlugins')
->will($this->returnValue(array()));
->will($this->returnValue([]));
$destination = $this->getMock('Drupal\migrate\Plugin\MigrateDestinationInterface');
$destination->expects($this->once())
->method('import')
->with($row, array('test'))
->with($row, ['test'])
->will($this->returnValue(TRUE));
$this->migration
@ -178,7 +179,7 @@ class MigrateExecutableTest extends MigrateTestCase {
$row->expects($this->once())
->method('getSourceIdValues')
->will($this->returnValue(array('id' => 'test')));
->will($this->returnValue(['id' => 'test']));
$source->expects($this->once())
->method('current')
@ -188,13 +189,13 @@ class MigrateExecutableTest extends MigrateTestCase {
$this->migration->expects($this->once())
->method('getProcessPlugins')
->will($this->returnValue(array()));
->will($this->returnValue([]));
$destination = $this->getMock('Drupal\migrate\Plugin\MigrateDestinationInterface');
$destination->expects($this->once())
->method('import')
->with($row, array('test'))
->will($this->returnValue(array()));
->with($row, ['test'])
->will($this->returnValue([]));
$this->migration
->method('getDestinationPlugin')
@ -202,7 +203,7 @@ class MigrateExecutableTest extends MigrateTestCase {
$this->idMap->expects($this->once())
->method('saveIdMapping')
->with($row, array(), MigrateIdMapInterface::STATUS_FAILED, NULL);
->with($row, [], MigrateIdMapInterface::STATUS_FAILED, NULL);
$this->idMap->expects($this->once())
->method('messageCount')
@ -213,8 +214,8 @@ class MigrateExecutableTest extends MigrateTestCase {
$this->idMap->expects($this->once())
->method('lookupDestinationId')
->with(array('id' => 'test'))
->will($this->returnValue(array('test')));
->with(['id' => 'test'])
->will($this->returnValue(['test']));
$this->message->expects($this->once())
->method('display')
@ -238,7 +239,7 @@ class MigrateExecutableTest extends MigrateTestCase {
$row->expects($this->once())
->method('getSourceIdValues')
->will($this->returnValue(array('id' => 'test')));
->will($this->returnValue(['id' => 'test']));
$source->expects($this->once())
->method('current')
@ -248,12 +249,12 @@ class MigrateExecutableTest extends MigrateTestCase {
$this->migration->expects($this->once())
->method('getProcessPlugins')
->will($this->returnValue(array()));
->will($this->returnValue([]));
$destination = $this->getMock('Drupal\migrate\Plugin\MigrateDestinationInterface');
$destination->expects($this->once())
->method('import')
->with($row, array('test'))
->with($row, ['test'])
->will($this->throwException(new MigrateException($exception_message)));
$this->migration
@ -262,15 +263,15 @@ class MigrateExecutableTest extends MigrateTestCase {
$this->idMap->expects($this->once())
->method('saveIdMapping')
->with($row, array(), MigrateIdMapInterface::STATUS_FAILED, NULL);
->with($row, [], MigrateIdMapInterface::STATUS_FAILED, NULL);
$this->idMap->expects($this->once())
->method('saveMessage');
$this->idMap->expects($this->once())
->method('lookupDestinationId')
->with(array('id' => 'test'))
->will($this->returnValue(array('test')));
->with(['id' => 'test'])
->will($this->returnValue(['test']));
$this->assertSame(MigrationInterface::RESULT_COMPLETED, $this->executable->import());
}
@ -290,7 +291,7 @@ class MigrateExecutableTest extends MigrateTestCase {
$row->expects($this->once())
->method('getSourceIdValues')
->willReturn(array('id' => 'test'));
->willReturn(['id' => 'test']);
$source->expects($this->once())
->method('current')
@ -312,7 +313,7 @@ class MigrateExecutableTest extends MigrateTestCase {
$this->idMap->expects($this->once())
->method('saveIdMapping')
->with($row, array(), MigrateIdMapInterface::STATUS_FAILED, NULL);
->with($row, [], MigrateIdMapInterface::STATUS_FAILED, NULL);
$this->idMap->expects($this->once())
->method('saveMessage');
@ -336,7 +337,7 @@ class MigrateExecutableTest extends MigrateTestCase {
$row->expects($this->once())
->method('getSourceIdValues')
->will($this->returnValue(array('id' => 'test')));
->will($this->returnValue(['id' => 'test']));
$source->expects($this->once())
->method('current')
@ -346,12 +347,12 @@ class MigrateExecutableTest extends MigrateTestCase {
$this->migration->expects($this->once())
->method('getProcessPlugins')
->will($this->returnValue(array()));
->will($this->returnValue([]));
$destination = $this->getMock('Drupal\migrate\Plugin\MigrateDestinationInterface');
$destination->expects($this->once())
->method('import')
->with($row, array('test'))
->with($row, ['test'])
->will($this->throwException(new \Exception($exception_message)));
$this->migration
@ -360,15 +361,15 @@ class MigrateExecutableTest extends MigrateTestCase {
$this->idMap->expects($this->once())
->method('saveIdMapping')
->with($row, array(), MigrateIdMapInterface::STATUS_FAILED, NULL);
->with($row, [], MigrateIdMapInterface::STATUS_FAILED, NULL);
$this->idMap->expects($this->once())
->method('saveMessage');
$this->idMap->expects($this->once())
->method('lookupDestinationId')
->with(array('id' => 'test'))
->will($this->returnValue(array('test')));
->with(['id' => 'test'])
->will($this->returnValue(['test']));
$this->message->expects($this->once())
->method('display')
@ -381,15 +382,15 @@ class MigrateExecutableTest extends MigrateTestCase {
* Tests the processRow method.
*/
public function testProcessRow() {
$expected = array(
$expected = [
'test' => 'test destination',
'test1' => 'test1 destination'
);
];
foreach ($expected as $key => $value) {
$plugins[$key][0] = $this->getMock('Drupal\migrate\Plugin\MigrateProcessInterface');
$plugins[$key][0]->expects($this->once())
->method('getPluginDefinition')
->will($this->returnValue(array()));
->will($this->returnValue([]));
$plugins[$key][0]->expects($this->once())
->method('transform')
->will($this->returnValue($value));
@ -413,10 +414,29 @@ class MigrateExecutableTest extends MigrateTestCase {
$this->migration->expects($this->once())
->method('getProcessPlugins')
->with(NULL)
->will($this->returnValue(array('test' => array())));
->will($this->returnValue(['test' => []]));
$row = new Row();
$this->executable->processRow($row);
$this->assertSame($row->getDestination(), array());
$this->assertSame($row->getDestination(), []);
}
/**
* Tests the processRow pipeline exception.
*/
public function testProcessRowPipelineException() {
$row = new Row();
$plugin = $this->prophesize(MigrateProcessInterface::class);
$plugin->getPluginDefinition()->willReturn(['handle_multiples' => FALSE]);
$plugin->transform(NULL, $this->executable, $row, 'destination_id')
->willReturn('transform_return_string');
$plugin->multiple()->willReturn(TRUE);
$plugin->getPluginId()->willReturn('plugin_id');
$plugin = $plugin->reveal();
$plugins['destination_id'] = [$plugin, $plugin];
$this->migration->method('getProcessPlugins')->willReturn($plugins);
$this->setExpectedException(MigrateException::class, 'Pipeline failed at plugin_id plugin for destination destination_id: transform_return_string received instead of an array,');
$this->executable->processRow($row);
}
/**

View file

@ -12,6 +12,7 @@ use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
use Drupal\Core\KeyValueStore\KeyValueStoreInterface;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutable;
use Drupal\migrate\MigrateSkipRowException;
use Drupal\migrate\Plugin\migrate\source\SourcePluginBase;
@ -149,10 +150,10 @@ class MigrateSourceTest extends MigrateTestCase {
/**
* @covers ::__construct
* @expectedException \Drupal\migrate\MigrateException
*/
public function testHighwaterTrackChangesIncompatible() {
$source_config = ['track_changes' => TRUE, 'high_water_property' => ['name' => 'something']];
$this->setExpectedException(MigrateException::class);
$this->getSource($source_config);
}
@ -166,7 +167,7 @@ class MigrateSourceTest extends MigrateTestCase {
$container = new ContainerBuilder();
$cache = $this->getMock(CacheBackendInterface::class);
$cache->expects($this->any())->method('set')
->with($this->isType('string'), $this->isType('int'), $this->isType('int'));
->with($this->isType('string'), $this->isType('int'), $this->isType('int'));
$container->set('cache.migrate', $cache);
\Drupal::setContainer($container);
@ -204,7 +205,7 @@ class MigrateSourceTest extends MigrateTestCase {
$container = new ContainerBuilder();
$cache = $this->getMock(CacheBackendInterface::class);
$cache->expects($this->any())->method('set')
->with('test_key', $this->isType('int'), $this->isType('int'));
->with('test_key', $this->isType('int'), $this->isType('int'));
$container->set('cache.migrate', $cache);
\Drupal::setContainer($container);

View file

@ -16,63 +16,70 @@ class MigrateSqlIdMapEnsureTablesTest extends MigrateTestCase {
*
* @var array
*/
protected $migrationConfiguration = array(
protected $migrationConfiguration = [
'id' => 'sql_idmap_test',
);
];
/**
* Tests the ensureTables method when the tables do not exist.
*/
public function testEnsureTablesNotExist() {
$fields['source_ids_hash'] = Array(
$fields['source_ids_hash'] = [
'type' => 'varchar',
'length' => 64,
'not null' => 1,
'description' => 'Hash of source ids. Used as primary key'
);
$fields['sourceid1'] = array(
];
$fields['sourceid1'] = [
'type' => 'int',
'not null' => TRUE,
);
$fields['destid1'] = array(
];
$fields['sourceid2'] = [
'type' => 'int',
'not null' => TRUE,
];
$fields['destid1'] = [
'type' => 'varchar',
'length' => 255,
'not null' => FALSE,
);
$fields['source_row_status'] = array(
];
$fields['source_row_status'] = [
'type' => 'int',
'size' => 'tiny',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => MigrateIdMapInterface::STATUS_IMPORTED,
'description' => 'Indicates current status of the source row',
);
$fields['rollback_action'] = array(
];
$fields['rollback_action'] = [
'type' => 'int',
'size' => 'tiny',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => MigrateIdMapInterface::ROLLBACK_DELETE,
'description' => 'Flag indicating what to do for this item on rollback',
);
$fields['last_imported'] = array(
];
$fields['last_imported'] = [
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => 'UNIX timestamp of the last time this row was imported',
);
$fields['hash'] = array(
];
$fields['hash'] = [
'type' => 'varchar',
'length' => '64',
'not null' => FALSE,
'description' => 'Hash of source row data, for detecting changes',
);
$map_table_schema = array(
];
$map_table_schema = [
'description' => 'Mappings from source identifier value(s) to destination identifier value(s).',
'fields' => $fields,
'primary key' => array('source_ids_hash'),
);
'primary key' => ['source_ids_hash'],
'indexes' => [
'source' => ['sourceid1', 'sourceid2'],
],
];
$schema = $this->getMockBuilder('Drupal\Core\Database\Schema')
->disableOriginalConstructor()
->getMock();
@ -84,34 +91,34 @@ class MigrateSqlIdMapEnsureTablesTest extends MigrateTestCase {
->method('createTable')
->with('migrate_map_sql_idmap_test', $map_table_schema);
// Now do the message table.
$fields = array();
$fields['msgid'] = array(
$fields = [];
$fields['msgid'] = [
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
);
$fields['source_ids_hash'] = Array(
];
$fields['source_ids_hash'] = [
'type' => 'varchar',
'length' => 64,
'not null' => 1,
'description' => 'Hash of source ids. Used as primary key'
);
$fields['level'] = array(
];
$fields['level'] = [
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 1,
);
$fields['message'] = array(
];
$fields['message'] = [
'type' => 'text',
'size' => 'medium',
'not null' => TRUE,
);
$table_schema = array(
];
$table_schema = [
'description' => 'Messages generated during a migration process',
'fields' => $fields,
'primary key' => array('msgid'),
);
'primary key' => ['msgid'],
];
$schema->expects($this->at(2))
->method('tableExists')
@ -140,14 +147,14 @@ class MigrateSqlIdMapEnsureTablesTest extends MigrateTestCase {
->method('fieldExists')
->with('migrate_map_sql_idmap_test', 'rollback_action')
->will($this->returnValue(FALSE));
$field_schema = array(
$field_schema = [
'type' => 'int',
'size' => 'tiny',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => 'Flag indicating what to do for this item on rollback',
);
];
$schema->expects($this->at(2))
->method('addField')
->with('migrate_map_sql_idmap_test', 'rollback_action', $field_schema);
@ -155,12 +162,12 @@ class MigrateSqlIdMapEnsureTablesTest extends MigrateTestCase {
->method('fieldExists')
->with('migrate_map_sql_idmap_test', 'hash')
->will($this->returnValue(FALSE));
$field_schema = array(
$field_schema = [
'type' => 'varchar',
'length' => '64',
'not null' => FALSE,
'description' => 'Hash of source row data, for detecting changes',
);
];
$schema->expects($this->at(4))
->method('addField')
->with('migrate_map_sql_idmap_test', 'hash', $field_schema);
@ -168,12 +175,12 @@ class MigrateSqlIdMapEnsureTablesTest extends MigrateTestCase {
->method('fieldExists')
->with('migrate_map_sql_idmap_test', 'source_ids_hash')
->will($this->returnValue(FALSE));
$field_schema = array(
$field_schema = [
'type' => 'varchar',
'length' => '64',
'not null' => TRUE,
'description' => 'Hash of source ids. Used as primary key',
);
];
$schema->expects($this->at(6))
->method('addField')
->with('migrate_map_sql_idmap_test', 'source_ids_hash', $field_schema);
@ -201,28 +208,31 @@ class MigrateSqlIdMapEnsureTablesTest extends MigrateTestCase {
$plugin = $this->getMock('Drupal\migrate\Plugin\MigrateSourceInterface');
$plugin->expects($this->any())
->method('getIds')
->willReturn(array(
'source_id_property' => array(
->willReturn([
'source_id_property' => [
'type' => 'integer',
),
));
],
'source_id_property_2' => [
'type' => 'integer',
],
]);
$migration->expects($this->any())
->method('getSourcePlugin')
->willReturn($plugin);
$plugin = $this->getMock('Drupal\migrate\Plugin\MigrateSourceInterface');
$plugin->expects($this->any())
->method('getIds')
->willReturn(array(
'destination_id_property' => array(
->willReturn([
'destination_id_property' => [
'type' => 'string',
),
));
],
]);
$migration->expects($this->any())
->method('getDestinationPlugin')
->willReturn($plugin);
/** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher */
$event_dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
$map = new TestSqlIdMap($database, array(), 'sql', array(), $migration, $event_dispatcher);
$map = new TestSqlIdMap($database, [], 'sql', [], $migration, $event_dispatcher);
$map->getDatabase();
}

View file

@ -130,11 +130,11 @@ class MigrateSqlIdMapTest extends MigrateTestCase {
* - hash
*/
protected function idMapDefaults() {
$defaults = array(
$defaults = [
'source_row_status' => MigrateIdMapInterface::STATUS_IMPORTED,
'rollback_action' => MigrateIdMapInterface::ROLLBACK_DELETE,
'hash' => '',
);
];
// By default, the PDO SQLite driver strongly prefers to return strings
// from SELECT queries. Even for columns that don't store strings. Even
// if the connection's STRINGIFY_FETCHES attribute is FALSE. This can cause
@ -157,9 +157,9 @@ class MigrateSqlIdMapTest extends MigrateTestCase {
* - updating work.
*/
public function testSaveIdMapping() {
$source = array(
$source = [
'source_id_property' => 'source_value',
);
];
$row = new Row($source, ['source_id_property' => []]);
$id_map = $this->getIdMap();
$id_map->saveIdMapping($row, ['destination_id_property' => 2]);

View file

@ -33,7 +33,7 @@ abstract class MigrateSqlSourceTestCase extends MigrateTestCase {
*
* @var array
*/
protected $databaseContents = array();
protected $databaseContents = [];
/**
* The plugin class under test.
@ -60,7 +60,7 @@ abstract class MigrateSqlSourceTestCase extends MigrateTestCase {
*
* @var array
*/
protected $expectedResults = array();
protected $expectedResults = [];
/**
* Expected count of source rows.
@ -106,13 +106,16 @@ abstract class MigrateSqlSourceTestCase extends MigrateTestCase {
\Drupal::setContainer($container);
$migration = $this->getMigration();
$migration->expects($this->any())
->method('getHighWater')
->will($this->returnValue(static::ORIGINAL_HIGH_WATER));
// Set the high water value.
\Drupal::keyValue('migrate:high_water')
->expects($this->any())
->method('get')
->willReturn(static::ORIGINAL_HIGH_WATER);
// Setup the plugin.
$plugin_class = static::PLUGIN_CLASS;
$plugin = new $plugin_class($this->migrationConfiguration['source'], $this->migrationConfiguration['source']['plugin'], array(), $migration, $state, $entity_manager);
$plugin = new $plugin_class($this->migrationConfiguration['source'], $this->migrationConfiguration['source']['plugin'], [], $migration, $state, $entity_manager);
// Do some reflection to set the database and moduleHandler.
$plugin_reflection = new \ReflectionClass($plugin);
@ -122,7 +125,7 @@ abstract class MigrateSqlSourceTestCase extends MigrateTestCase {
$module_handler_property->setAccessible(TRUE);
// Set the database and the module handler onto our plugin.
$database_property->setValue($plugin, $this->getDatabase($this->databaseContents + array('test_map' => array())));
$database_property->setValue($plugin, $this->getDatabase($this->databaseContents + ['test_map' => []]));
$module_handler_property->setValue($plugin, $module_handler);
$plugin->setStringTranslation($this->getStringTranslationStub());

View file

@ -27,9 +27,6 @@ class MigrationTest extends UnitTestCase {
* Tests checking requirements for source plugins.
*
* @covers ::checkRequirements
*
* @expectedException \Drupal\migrate\Exception\RequirementsException
* @expectedExceptionMessage Missing source requirement
*/
public function testRequirementsForSourcePlugin() {
$migration = new TestMigration();
@ -43,6 +40,7 @@ class MigrationTest extends UnitTestCase {
$migration->setSourcePlugin($source_plugin);
$migration->setDestinationPlugin($destination_plugin);
$this->setExpectedException(RequirementsException::class, 'Missing source requirement');
$migration->checkRequirements();
}
@ -50,9 +48,6 @@ class MigrationTest extends UnitTestCase {
* Tests checking requirements for destination plugins.
*
* @covers ::checkRequirements
*
* @expectedException \Drupal\migrate\Exception\RequirementsException
* @expectedExceptionMessage Missing destination requirement
*/
public function testRequirementsForDestinationPlugin() {
$migration = new TestMigration();
@ -66,6 +61,7 @@ class MigrationTest extends UnitTestCase {
$migration->setSourcePlugin($source_plugin);
$migration->setDestinationPlugin($destination_plugin);
$this->setExpectedException(RequirementsException::class, 'Missing destination requirement');
$migration->checkRequirements();
}
@ -73,9 +69,6 @@ class MigrationTest extends UnitTestCase {
* Tests checking requirements for destination plugins.
*
* @covers ::checkRequirements
*
* @expectedException \Drupal\migrate\Exception\RequirementsException
* @expectedExceptionMessage Missing migrations test_a, test_c
*/
public function testRequirementsForMigrations() {
$migration = new TestMigration();
@ -112,6 +105,7 @@ class MigrationTest extends UnitTestCase {
->with(['test_a', 'test_b', 'test_c', 'test_d'])
->willReturn(['test_b' => $migration_b, 'test_c' => $migration_c, 'test_d' => $migration_d]);
$this->setExpectedException(RequirementsException::class, 'Missing migrations test_a, test_c');
$migration->checkRequirements();
}

View file

@ -13,6 +13,7 @@ use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldTypePluginManagerInterface;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\migrate\destination\EntityContentBase;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
@ -84,8 +85,6 @@ class EntityContentBaseTest extends UnitTestCase {
* Test row skipping when we can't get an entity to save.
*
* @covers ::import
* @expectedException \Drupal\migrate\MigrateException
* @expectedExceptionMessage Unable to get entity
*/
public function testImportEntityLoadFailure() {
$bundles = [];
@ -96,14 +95,12 @@ class EntityContentBaseTest extends UnitTestCase {
$this->entityManager->reveal(),
$this->prophesize(FieldTypePluginManagerInterface::class)->reveal());
$destination->setEntity(FALSE);
$this->setExpectedException(MigrateException::class, 'Unable to get entity');
$destination->import(new Row());
}
/**
* Test that translation destination fails for untranslatable entities.
*
* @expectedException \Drupal\migrate\MigrateException
* @expectedExceptionMessage This entity type does not support translation
*/
public function testUntranslatable() {
// An entity type without a language.
@ -125,6 +122,7 @@ class EntityContentBaseTest extends UnitTestCase {
$this->entityManager->reveal(),
$this->prophesize(FieldTypePluginManagerInterface::class)->reveal()
);
$this->setExpectedException(MigrateException::class, 'This entity type does not support translation');
$destination->getIds();
}

View file

@ -17,19 +17,19 @@ class RowTest extends UnitTestCase {
*
* @var array
*/
protected $testSourceIds = array(
protected $testSourceIds = [
'nid' => 'Node ID',
);
];
/**
* The test values.
*
* @var array
*/
protected $testValues = array(
protected $testValues = [
'nid' => 1,
'title' => 'node 1',
);
];
/**
* The test hash.
@ -50,7 +50,7 @@ class RowTest extends UnitTestCase {
*/
public function testRowWithoutData() {
$row = new Row();
$this->assertSame(array(), $row->getSource(), 'Empty row');
$this->assertSame([], $row->getSource(), 'Empty row');
}
/**
@ -65,28 +65,25 @@ class RowTest extends UnitTestCase {
* Tests object creation: multiple source IDs.
*/
public function testRowWithMultipleSourceIds() {
$multi_source_ids = $this->testSourceIds + array('vid' => 'Node revision');
$multi_source_ids_values = $this->testValues + array('vid' => 1);
$multi_source_ids = $this->testSourceIds + ['vid' => 'Node revision'];
$multi_source_ids_values = $this->testValues + ['vid' => 1];
$row = new Row($multi_source_ids_values, $multi_source_ids);
$this->assertSame($multi_source_ids_values, $row->getSource(), 'Row with data, multifield id.');
}
/**
* Tests object creation: invalid values.
*
* @expectedException \Exception
*/
public function testRowWithInvalidData() {
$invalid_values = array(
$invalid_values = [
'title' => 'node X',
);
];
$this->setExpectedException(\Exception::class);
$row = new Row($invalid_values, $this->testSourceIds);
}
/**
* Tests source immutability after freeze.
*
* @expectedException \Exception
*/
public function testSourceFreeze() {
$row = new Row($this->testValues, $this->testSourceIds);
@ -96,18 +93,17 @@ class RowTest extends UnitTestCase {
$row->rehash();
$this->assertSame($this->testHashMod, $row->getHash(), 'Hash changed correctly.');
$row->freezeSource();
$this->setExpectedException(\Exception::class);
$row->setSourceProperty('title', 'new title');
}
/**
* Tests setting on a frozen row.
*
* @expectedException \Exception
* @expectedExceptionMessage The source is frozen and can't be changed any more
*/
public function testSetFrozenRow() {
$row = new Row($this->testValues, $this->testSourceIds);
$row->freezeSource();
$this->setExpectedException(\Exception::class, "The source is frozen and can't be changed any more");
$row->setSourceProperty('title', 'new title');
}
@ -123,11 +119,11 @@ class RowTest extends UnitTestCase {
$this->assertSame($this->testHash, $row->getHash(), 'Correct hash even doing it twice.');
// Set the map to needs update.
$test_id_map = array(
$test_id_map = [
'original_hash' => '',
'hash' => '',
'source_row_status' => MigrateIdMapInterface::STATUS_NEEDS_UPDATE,
);
];
$row->setIdMap($test_id_map);
$this->assertTrue($row->needsUpdate());
@ -143,30 +139,30 @@ class RowTest extends UnitTestCase {
$this->assertSame(64, strlen($row->getHash()));
// Set the map to successfully imported.
$test_id_map = array(
$test_id_map = [
'original_hash' => '',
'hash' => '',
'source_row_status' => MigrateIdMapInterface::STATUS_IMPORTED,
);
];
$row->setIdMap($test_id_map);
$this->assertFalse($row->needsUpdate());
// Set the same hash value and ensure it was not changed.
$random = $this->randomMachineName();
$test_id_map = array(
$test_id_map = [
'original_hash' => $random,
'hash' => $random,
'source_row_status' => MigrateIdMapInterface::STATUS_NEEDS_UPDATE,
);
];
$row->setIdMap($test_id_map);
$this->assertFalse($row->changed());
// Set different has values to ensure it is marked as changed.
$test_id_map = array(
$test_id_map = [
'original_hash' => $this->randomMachineName(),
'hash' => $this->randomMachineName(),
'source_row_status' => MigrateIdMapInterface::STATUS_NEEDS_UPDATE,
);
];
$row->setIdMap($test_id_map);
$this->assertTrue($row->changed());
}
@ -179,11 +175,11 @@ class RowTest extends UnitTestCase {
*/
public function testGetSetIdMap() {
$row = new Row($this->testValues, $this->testSourceIds);
$test_id_map = array(
$test_id_map = [
'original_hash' => '',
'hash' => '',
'source_row_status' => MigrateIdMapInterface::STATUS_NEEDS_UPDATE,
);
];
$row->setIdMap($test_id_map);
$this->assertEquals($test_id_map, $row->getIdMap());
}
@ -193,7 +189,7 @@ class RowTest extends UnitTestCase {
*/
public function testSourceIdValues() {
$row = new Row($this->testValues, $this->testSourceIds);
$this->assertSame(array('nid' => $this->testValues['nid']), $row->getSourceIdValues());
$this->assertSame(['nid' => $this->testValues['nid']], $row->getSourceIdValues());
}
/**
@ -219,7 +215,7 @@ class RowTest extends UnitTestCase {
// Set a destination.
$row->setDestinationProperty('nid', 2);
$this->assertTrue($row->hasDestinationProperty('nid'));
$this->assertEquals(array('nid' => 2), $row->getDestination());
$this->assertEquals(['nid' => 2], $row->getDestination());
}
/**

View file

@ -55,21 +55,21 @@ class TestSqlIdMap extends Sql implements \Iterator {
*/
protected function getFieldSchema(array $id_definition) {
if (!isset($id_definition['type'])) {
return array();
return [];
}
switch ($id_definition['type']) {
case 'integer':
return array(
return [
'type' => 'int',
'not null' => TRUE,
);
];
case 'string':
return array(
return [
'type' => 'varchar',
'length' => 255,
'not null' => FALSE,
);
];
default:
throw new MigrateException($id_definition['type'] . ' not supported');

View file

@ -16,9 +16,9 @@ class ConfigTest extends UnitTestCase {
* Test the import method.
*/
public function testImport() {
$source = array(
$source = [
'test' => 'x',
);
];
$migration = $this->getMockBuilder('Drupal\migrate\Plugin\Migration')
->disableOriginalConstructor()
->getMock();
@ -54,7 +54,7 @@ class ConfigTest extends UnitTestCase {
->method('getLanguageConfigOverride')
->with('fr', 'd8_config')
->will($this->returnValue($config));
$destination = new Config(array('config_name' => 'd8_config'), 'd8_config', array('pluginId' => 'd8_config'), $migration, $config_factory, $language_manager);
$destination = new Config(['config_name' => 'd8_config'], 'd8_config', ['pluginId' => 'd8_config'], $migration, $config_factory, $language_manager);
$destination_id = $destination->import($row);
$this->assertEquals($destination_id, ['d8_config']);
}
@ -63,9 +63,9 @@ class ConfigTest extends UnitTestCase {
* Test the import method.
*/
public function testLanguageImport() {
$source = array(
$source = [
'langcode' => 'mi',
);
];
$migration = $this->getMockBuilder(MigrationInterface::class)
->disableOriginalConstructor()
->getMock();
@ -104,7 +104,7 @@ class ConfigTest extends UnitTestCase {
->method('getLanguageConfigOverride')
->with('mi', 'd8_config')
->will($this->returnValue($config));
$destination = new Config(array('config_name' => 'd8_config', 'translations' => 'true'), 'd8_config', array('pluginId' => 'd8_config'), $migration, $config_factory, $language_manager);
$destination = new Config(['config_name' => 'd8_config', 'translations' => 'true'], 'd8_config', ['pluginId' => 'd8_config'], $migration, $config_factory, $language_manager);
$destination_id = $destination->import($row);
$this->assertEquals($destination_id, ['d8_config', 'mi']);
}

View file

@ -212,7 +212,7 @@ class EntityRevision extends RealEntityRevision {
/**
* Allow public access for testing.
*/
public function save(ContentEntityInterface $entity, array $old_destination_id_values = array()) {
public function save(ContentEntityInterface $entity, array $old_destination_id_values = []) {
return parent::save($entity, $old_destination_id_values);
}

View file

@ -22,13 +22,13 @@ class PerComponentEntityDisplayTest extends MigrateTestCase {
* Tests the entity display import method.
*/
public function testImport() {
$values = array(
$values = [
'entity_type' => 'entity_type_test',
'bundle' => 'bundle_test',
'view_mode' => 'view_mode_test',
'field_name' => 'field_name_test',
'options' => array('test setting'),
);
'options' => ['test setting'],
];
$row = new Row();
foreach ($values as $key => $value) {
$row->setDestinationProperty($key, $value);
@ -38,14 +38,14 @@ class PerComponentEntityDisplayTest extends MigrateTestCase {
->getMock();
$entity->expects($this->once())
->method('setComponent')
->with('field_name_test', array('test setting'))
->with('field_name_test', ['test setting'])
->will($this->returnSelf());
$entity->expects($this->once())
->method('save')
->with();
$plugin = new TestPerComponentEntityDisplay($entity);
$this->assertSame($plugin->import($row), array('entity_type_test', 'bundle_test', 'view_mode_test', 'field_name_test'));
$this->assertSame($plugin->getTestValues(), array('entity_type_test', 'bundle_test', 'view_mode_test'));
$this->assertSame($plugin->import($row), ['entity_type_test', 'bundle_test', 'view_mode_test', 'field_name_test']);
$this->assertSame($plugin->getTestValues(), ['entity_type_test', 'bundle_test', 'view_mode_test']);
}
}

View file

@ -22,13 +22,13 @@ class PerComponentEntityFormDisplayTest extends MigrateTestCase {
* Tests the entity display import method.
*/
public function testImport() {
$values = array(
$values = [
'entity_type' => 'entity_type_test',
'bundle' => 'bundle_test',
'form_mode' => 'form_mode_test',
'field_name' => 'field_name_test',
'options' => array('test setting'),
);
'options' => ['test setting'],
];
$row = new Row();
foreach ($values as $key => $value) {
$row->setDestinationProperty($key, $value);
@ -38,14 +38,14 @@ class PerComponentEntityFormDisplayTest extends MigrateTestCase {
->getMock();
$entity->expects($this->once())
->method('setComponent')
->with('field_name_test', array('test setting'))
->with('field_name_test', ['test setting'])
->will($this->returnSelf());
$entity->expects($this->once())
->method('save')
->with();
$plugin = new TestPerComponentEntityFormDisplay($entity);
$this->assertSame($plugin->import($row), array('entity_type_test', 'bundle_test', 'form_mode_test', 'field_name_test'));
$this->assertSame($plugin->getTestValues(), array('entity_type_test', 'bundle_test', 'form_mode_test'));
$this->assertSame($plugin->import($row), ['entity_type_test', 'bundle_test', 'form_mode_test', 'field_name_test']);
$this->assertSame($plugin->getTestValues(), ['entity_type_test', 'bundle_test', 'form_mode_test']);
}
}

View file

@ -37,7 +37,7 @@ class CallbackTest extends MigrateProcessTestCase {
* Test callback with a class method as callable.
*/
public function testCallbackWithClassMethod() {
$this->plugin->setCallable(array('\Drupal\Component\Utility\Unicode', 'strtolower'));
$this->plugin->setCallable(['\Drupal\Component\Utility\Unicode', 'strtolower']);
$value = $this->plugin->transform('FooBar', $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame($value, 'foobar');
}

View file

@ -7,6 +7,7 @@
namespace Drupal\Tests\migrate\Unit\process;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Plugin\migrate\process\Concat;
/**
@ -28,16 +29,15 @@ class ConcatTest extends MigrateProcessTestCase {
* Test concat works without a delimiter.
*/
public function testConcatWithoutDelimiter() {
$value = $this->plugin->transform(array('foo', 'bar'), $this->migrateExecutable, $this->row, 'destinationproperty');
$value = $this->plugin->transform(['foo', 'bar'], $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame($value, 'foobar');
}
/**
* Test concat fails properly on non-arrays.
*
* @expectedException \Drupal\migrate\MigrateException
*/
public function testConcatWithNonArray() {
$this->setExpectedException(MigrateException::class);
$this->plugin->transform('foo', $this->migrateExecutable, $this->row, 'destinationproperty');
}
@ -46,7 +46,7 @@ class ConcatTest extends MigrateProcessTestCase {
*/
public function testConcatWithDelimiter() {
$this->plugin->setDelimiter('_');
$value = $this->plugin->transform(array('foo', 'bar'), $this->migrateExecutable, $this->row, 'destinationproperty');
$value = $this->plugin->transform(['foo', 'bar'], $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame($value, 'foo_bar');
}

View file

@ -2,6 +2,8 @@
namespace Drupal\Tests\migrate\Unit\process;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\migrate\Plugin\migrate\process\DedupeEntity;
use Drupal\Component\Utility\Unicode;
@ -21,20 +23,20 @@ class DedupeEntityTest extends MigrateProcessTestCase {
protected $entityQuery;
/**
* The mock entity query factory.
* The mocked entity type manager.
*
* @var \Drupal\Core\Entity\Query\QueryFactory|\PHPUnit_Framework_MockObject_MockObject
* @var \Drupal\Core\Entity\EntityTypeManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $entityQueryFactory;
protected $entityTypeManager;
/**
* The migration configuration, initialized to set the ID to test.
*
* @var array
*/
protected $migrationConfiguration = array(
protected $migrationConfiguration = [
'id' => 'test',
);
];
/**
* {@inheritdoc}
@ -43,12 +45,16 @@ class DedupeEntityTest extends MigrateProcessTestCase {
$this->entityQuery = $this->getMockBuilder('Drupal\Core\Entity\Query\QueryInterface')
->disableOriginalConstructor()
->getMock();
$this->entityQueryFactory = $this->getMockBuilder('Drupal\Core\Entity\Query\QueryFactory')
->disableOriginalConstructor()
->getMock();
$this->entityQueryFactory->expects($this->any())
->method('get')
->will($this->returnValue($this->entityQuery));
$this->entityTypeManager = $this->getMock(EntityTypeManagerInterface::class);
$storage = $this->getMock(EntityStorageInterface::class);
$storage->expects($this->any())
->method('getQuery')
->willReturn($this->entityQuery);
$this->entityTypeManager->expects($this->any())
->method('getStorage')
->with('test_entity_type')
->willReturn($storage);
parent::setUp();
}
@ -58,16 +64,16 @@ class DedupeEntityTest extends MigrateProcessTestCase {
* @dataProvider providerTestDedupe
*/
public function testDedupe($count, $postfix = '', $start = NULL, $length = NULL) {
$configuration = array(
$configuration = [
'entity_type' => 'test_entity_type',
'field' => 'test_field',
);
];
if ($postfix) {
$configuration['postfix'] = $postfix;
}
$configuration['start'] = isset($start) ? $start : NULL;
$configuration['length'] = isset($length) ? $length : NULL;
$plugin = new DedupeEntity($configuration, 'dedupe_entity', array(), $this->getMigration(), $this->entityQueryFactory);
$plugin = new DedupeEntity($configuration, 'dedupe_entity', [], $this->getMigration(), $this->entityTypeManager);
$this->entityQueryExpects($count);
$value = $this->randomMachineName(32);
$actual = $plugin->transform($value, $this->migrateExecutable, $this->row, 'testproperty');
@ -80,12 +86,12 @@ class DedupeEntityTest extends MigrateProcessTestCase {
* Tests that invalid start position throws an exception.
*/
public function testDedupeEntityInvalidStart() {
$configuration = array(
$configuration = [
'entity_type' => 'test_entity_type',
'field' => 'test_field',
'start' => 'foobar',
);
$plugin = new DedupeEntity($configuration, 'dedupe_entity', array(), $this->getMigration(), $this->entityQueryFactory);
];
$plugin = new DedupeEntity($configuration, 'dedupe_entity', [], $this->getMigration(), $this->entityTypeManager);
$this->setExpectedException('Drupal\migrate\MigrateException', 'The start position configuration key should be an integer. Omit this key to capture from the beginning of the string.');
$plugin->transform('test_start', $this->migrateExecutable, $this->row, 'testproperty');
}
@ -94,12 +100,12 @@ class DedupeEntityTest extends MigrateProcessTestCase {
* Tests that invalid length option throws an exception.
*/
public function testDedupeEntityInvalidLength() {
$configuration = array(
$configuration = [
'entity_type' => 'test_entity_type',
'field' => 'test_field',
'length' => 'foobar',
);
$plugin = new DedupeEntity($configuration, 'dedupe_entity', array(), $this->getMigration(), $this->entityQueryFactory);
];
$plugin = new DedupeEntity($configuration, 'dedupe_entity', [], $this->getMigration(), $this->entityTypeManager);
$this->setExpectedException('Drupal\migrate\MigrateException', 'The character length configuration key should be an integer. Omit this key to capture the entire string.');
$plugin->transform('test_length', $this->migrateExecutable, $this->row, 'testproperty');
}
@ -108,40 +114,40 @@ class DedupeEntityTest extends MigrateProcessTestCase {
* Data provider for testDedupe().
*/
public function providerTestDedupe() {
return array(
return [
// Tests no duplication.
array(0),
[0],
// Tests no duplication and start position.
array(0, NULL, 10),
[0, NULL, 10],
// Tests no duplication, start position, and length.
array(0, NULL, 5, 10),
[0, NULL, 5, 10],
// Tests no duplication and length.
array(0, NULL, NULL, 10),
[0, NULL, NULL, 10],
// Tests duplication.
array(3),
[3],
// Tests duplication and start position.
array(3, NULL, 10),
[3, NULL, 10],
// Tests duplication, start position, and length.
array(3, NULL, 5, 10),
[3, NULL, 5, 10],
// Tests duplication and length.
array(3, NULL, NULL, 10),
[3, NULL, NULL, 10],
// Tests no duplication and postfix.
array(0, '_'),
[0, '_'],
// Tests no duplication, postfix, and start position.
array(0, '_', 5),
[0, '_', 5],
// Tests no duplication, postfix, start position, and length.
array(0, '_', 5, 10),
[0, '_', 5, 10],
// Tests no duplication, postfix, and length.
array(0, '_', NULL, 10),
[0, '_', NULL, 10],
// Tests duplication and postfix.
array(2, '_'),
[2, '_'],
// Tests duplication, postfix, and start position.
array(2, '_', 5),
[2, '_', 5],
// Tests duplication, postfix, start position, and length.
array(2, '_', 5, 10),
[2, '_', 5, 10],
// Tests duplication, postfix, and length.
array(2, '_', NULL, 10),
);
[2, '_', NULL, 10],
];
}
/**
@ -166,12 +172,12 @@ class DedupeEntityTest extends MigrateProcessTestCase {
* Test deduplicating only migrated entities.
*/
public function testDedupeMigrated() {
$configuration = array(
$configuration = [
'entity_type' => 'test_entity_type',
'field' => 'test_field',
'migrated' => TRUE,
);
$plugin = new DedupeEntity($configuration, 'dedupe_entity', array(), $this->getMigration(), $this->entityQueryFactory);
];
$plugin = new DedupeEntity($configuration, 'dedupe_entity', [], $this->getMigration(), $this->entityTypeManager);
// Setup the entityQuery used in DedupeEntity::exists. The map, $map, is
// an array consisting of the four input parameters to the query condition

View file

@ -2,6 +2,7 @@
namespace Drupal\Tests\migrate\Unit\process;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Plugin\migrate\process\Explode;
use Drupal\migrate\Plugin\migrate\process\Concat;
@ -53,23 +54,65 @@ class ExplodeTest extends MigrateProcessTestCase {
/**
* Test explode fails properly on non-strings.
*
* @expectedException \Drupal\migrate\MigrateException
*
* @expectedExceptionMessage is not a string
*/
public function testExplodeWithNonString() {
$this->setExpectedException(MigrateException::class, 'is not a string');
$this->plugin->transform(['foo'], $this->migrateExecutable, $this->row, 'destinationproperty');
}
/**
* Tests that explode works on non-strings but with strict set to FALSE.
*
* @dataProvider providerExplodeWithNonStrictAndEmptySource
*/
public function testExplodeWithNonStrictAndEmptySource($value, $expected) {
$plugin = new Explode(['delimiter' => '|', 'strict' => FALSE], 'map', []);
$processed = $plugin->transform($value, $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame($expected, $processed);
}
/**
* Data provider for ::testExplodeWithNonStrictAndEmptySource().
*/
public function providerExplodeWithNonStrictAndEmptySource() {
return [
'normal_string' => ['a|b|c', ['a', 'b', 'c']],
'integer_cast_to_string' => [123, ['123']],
'zero_integer_cast_to_string' => [0, ['0']],
'true_cast_to_string' => [TRUE, ['1']],
'null_empty_array' => [NULL, []],
'false_empty_array' => [FALSE, []],
'empty_string_empty_array' => ['', []],
];
}
/**
* Tests that explode raises an exception when the value cannot be casted to
* string.
*/
public function testExplodeWithNonStrictAndNonCastable() {
$plugin = new Explode(['delimiter' => '|', 'strict' => FALSE], 'map', []);
$this->setExpectedException(MigrateException::class, 'cannot be casted to a string');
$processed = $plugin->transform(['foo'], $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame(['foo'], $processed);
}
/**
* Tests that explode with an empty string and strict check returns a
* non-empty array.
*/
public function testExplodeWithStrictAndEmptyString() {
$plugin = new Explode(['delimiter' => '|'], 'map', []);
$processed = $plugin->transform('', $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame([''], $processed);
}
/**
* Test explode fails with empty delimiter.
*
* @expectedException \Drupal\migrate\MigrateException
*
* @expectedExceptionMessage delimiter is empty
*/
public function testExplodeWithEmptyDelimiter() {
$this->setExpectedException(MigrateException::class, 'delimiter is empty');
$plugin = new Explode(['delimiter' => ''], 'map', []);
$plugin->transform('foo,bar', $this->migrateExecutable, $this->row, 'destinationproperty');
}

View file

@ -2,6 +2,7 @@
namespace Drupal\Tests\migrate\Unit\process;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Plugin\migrate\process\Extract;
/**
@ -14,8 +15,8 @@ class ExtractTest extends MigrateProcessTestCase {
* {@inheritdoc}
*/
protected function setUp() {
$configuration['index'] = array('foo');
$this->plugin = new Extract($configuration, 'map', array());
$configuration['index'] = ['foo'];
$this->plugin = new Extract($configuration, 'map', []);
parent::setUp();
}
@ -23,28 +24,24 @@ class ExtractTest extends MigrateProcessTestCase {
* Tests successful extraction.
*/
public function testExtract() {
$value = $this->plugin->transform(array('foo' => 'bar'), $this->migrateExecutable, $this->row, 'destinationproperty');
$value = $this->plugin->transform(['foo' => 'bar'], $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame($value, 'bar');
}
/**
* Tests invalid input.
*
* @expectedException \Drupal\migrate\MigrateException
* @expectedExceptionMessage Input should be an array.
*/
public function testExtractFromString() {
$this->setExpectedException(MigrateException::class, 'Input should be an array.');
$this->plugin->transform('bar', $this->migrateExecutable, $this->row, 'destinationproperty');
}
/**
* Tests unsuccessful extraction.
*
* @expectedException \Drupal\migrate\MigrateException
* @expectedExceptionMessage Array index missing, extraction failed.
*/
public function testExtractFail() {
$this->plugin->transform(array('bar' => 'foo'), $this->migrateExecutable, $this->row, 'destinationproperty');
$this->setExpectedException(MigrateException::class, 'Array index missing, extraction failed.');
$this->plugin->transform(['bar' => 'foo'], $this->migrateExecutable, $this->row, 'destinationproperty');
}
/**

View file

@ -15,9 +15,9 @@ class FlattenTest extends MigrateProcessTestCase {
* Test that various array flatten operations work properly.
*/
public function testFlatten() {
$plugin = new Flatten(array(), 'flatten', array());
$flattened = $plugin->transform(array(1, 2, array(3, 4, array(5)), array(), array(7, 8)), $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame($flattened, array(1, 2, 3, 4, 5, 7, 8));
$plugin = new Flatten([], 'flatten', []);
$flattened = $plugin->transform([1, 2, [3, 4, [5]], [], [7, 8]], $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame($flattened, [1, 2, 3, 4, 5, 7, 8]);
}
}

View file

@ -41,16 +41,16 @@ class GetTest extends MigrateProcessTestCase {
* Tests the Get plugin when source is an array.
*/
public function testTransformSourceArray() {
$map = array(
$map = [
'test1' => 'source_value1',
'test2' => 'source_value2',
);
$this->plugin->setSource(array('test1', 'test2'));
];
$this->plugin->setSource(['test1', 'test2']);
$this->row->expects($this->exactly(2))
->method('getSourceProperty')
->will($this->returnCallback(function ($argument) use ($map) { return $map[$argument]; } ));
$value = $this->plugin->transform(NULL, $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame($value, array('source_value1', 'source_value2'));
$this->assertSame($value, ['source_value1', 'source_value2']);
}
/**
@ -70,18 +70,18 @@ class GetTest extends MigrateProcessTestCase {
* Tests the Get plugin when source is an array pointing to destination.
*/
public function testTransformSourceArrayAt() {
$map = array(
$map = [
'test1' => 'source_value1',
'@test2' => 'source_value2',
'@test3' => 'source_value3',
'test4' => 'source_value4',
);
$this->plugin->setSource(array('test1', '@@test2', '@@test3', 'test4'));
];
$this->plugin->setSource(['test1', '@@test2', '@@test3', 'test4']);
$this->row->expects($this->exactly(4))
->method('getSourceProperty')
->will($this->returnCallback(function ($argument) use ($map) { return $map[$argument]; } ));
$value = $this->plugin->transform(NULL, $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame($value, array('source_value1', 'source_value2', 'source_value3', 'source_value4'));
$this->assertSame($value, ['source_value1', 'source_value2', 'source_value3', 'source_value4']);
}
/**

View file

@ -25,9 +25,9 @@ class IteratorTest extends MigrateTestCase {
/**
* @var array
*/
protected $migrationConfiguration = array(
protected $migrationConfiguration = [
'id' => 'test',
);
];
/**
* Tests the iterator process plugin.
@ -35,24 +35,24 @@ class IteratorTest extends MigrateTestCase {
public function testIterator() {
$migration = $this->getMigration();
// Set up the properties for the iterator.
$configuration = array(
'process' => array(
$configuration = [
'process' => [
'foo' => 'source_foo',
'id' => 'source_id',
),
],
'key' => '@id',
);
$plugin = new Iterator($configuration, 'iterator', array());
];
$plugin = new Iterator($configuration, 'iterator', []);
// Manually create the plugins. Migration::getProcessPlugins does this
// normally but the plugin system is not available.
foreach ($configuration['process'] as $destination => $source) {
$iterator_plugins[$destination][] = new Get(array('source' => $source), 'get', array());
$iterator_plugins[$destination][] = new Get(['source' => $source], 'get', []);
}
$migration->expects($this->at(1))
->method('getProcessPlugins')
->will($this->returnValue($iterator_plugins));
// Set up the key plugins.
$key_plugin['key'][] = new Get(array('source' => '@id'), 'get', array());
$key_plugin['key'][] = new Get(['source' => '@id'], 'get', []);
$migration->expects($this->at(2))
->method('getProcessPlugins')
->will($this->returnValue($key_plugin));
@ -60,12 +60,12 @@ class IteratorTest extends MigrateTestCase {
$migrate_executable = new MigrateExecutable($migration, $this->getMock('Drupal\migrate\MigrateMessageInterface'), $event_dispatcher);
// The current value of the pipeline.
$current_value = array(
array(
$current_value = [
[
'source_foo' => 'test',
'source_id' => 42,
),
);
],
];
// This is not used but the interface requires it, so create an empty row.
$row = new Row();

View file

@ -53,7 +53,7 @@ class MachineNameTest extends MigrateProcessTestCase {
->with($human_name)
->will($this->returnValue($human_name_ascii . 'aeo'));
$plugin = new MachineName(array(), 'machine_name', array(), $this->transliteration);
$plugin = new MachineName([], 'machine_name', [], $this->transliteration);
$value = $plugin->transform($human_name, $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertEquals($expected_result, $value);
}

View file

@ -3,6 +3,7 @@
namespace Drupal\Tests\migrate\Unit\process;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\migrate\MigrateSkipProcessException;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\migrate\process\Migration;
use Drupal\migrate\Plugin\MigrateDestinationInterface;
@ -89,8 +90,6 @@ class MigrationTest extends MigrateProcessTestCase {
/**
* Tests that processing is skipped when the input value is empty.
*
* @expectedException \Drupal\migrate\MigrateSkipProcessException
*/
public function testSkipOnEmpty() {
$migration_plugin = $this->prophesize(MigrationInterface::class);
@ -102,6 +101,7 @@ class MigrationTest extends MigrateProcessTestCase {
];
$migration_plugin->id()->willReturn(uniqid());
$migration = new Migration($configuration, 'migration', [], $migration_plugin->reveal(), $migration_plugin_manager->reveal(), $process_plugin_manager->reveal());
$this->setExpectedException(MigrateSkipProcessException::class);
$migration->transform(0, $this->migrateExecutable, $this->row, 'foo');
}

View file

@ -1,6 +1,8 @@
<?php
namespace Drupal\Tests\migrate\Unit\process;
use Drupal\migrate\MigrateSkipProcessException;
use Drupal\migrate\MigrateSkipRowException;
use Drupal\migrate\Plugin\migrate\process\SkipOnEmpty;
/**
@ -13,10 +15,10 @@ class SkipOnEmptyTest extends MigrateProcessTestCase {
/**
* @covers ::process
* @expectedException \Drupal\migrate\MigrateSkipProcessException
*/
public function testProcessSkipsOnEmpty() {
$configuration['method'] = 'process';
$this->setExpectedException(MigrateSkipProcessException::class);
(new SkipOnEmpty($configuration, 'skip_on_empty', []))
->transform('', $this->migrateExecutable, $this->row, 'destinationproperty');
}
@ -33,10 +35,10 @@ class SkipOnEmptyTest extends MigrateProcessTestCase {
/**
* @covers ::row
* @expectedException \Drupal\migrate\MigrateSkipRowException
*/
public function testRowSkipsOnEmpty() {
$configuration['method'] = 'row';
$this->setExpectedException(MigrateSkipRowException::class);
(new SkipOnEmpty($configuration, 'skip_on_empty', []))
->transform('', $this->migrateExecutable, $this->row, 'destinationproperty');
}

View file

@ -2,6 +2,8 @@
namespace Drupal\Tests\migrate\Unit\process;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateSkipRowException;
use Drupal\migrate\Plugin\migrate\process\StaticMap;
/**
@ -16,7 +18,7 @@ class StaticMapTest extends MigrateProcessTestCase {
*/
protected function setUp() {
$configuration['map']['foo']['bar'] = 'baz';
$this->plugin = new StaticMap($configuration, 'map', array());
$this->plugin = new StaticMap($configuration, 'map', []);
parent::setUp();
}
@ -25,33 +27,31 @@ class StaticMapTest extends MigrateProcessTestCase {
*/
public function testMapWithSourceString() {
$value = $this->plugin->transform('foo', $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame($value, array('bar' => 'baz'));
$this->assertSame($value, ['bar' => 'baz']);
}
/**
* Tests map when the source is a list.
*/
public function testMapWithSourceList() {
$value = $this->plugin->transform(array('foo', 'bar'), $this->migrateExecutable, $this->row, 'destinationproperty');
$value = $this->plugin->transform(['foo', 'bar'], $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame($value, 'baz');
}
/**
* Tests when the source is empty.
*
* @expectedException \Drupal\migrate\MigrateException
*/
public function testMapwithEmptySource() {
$this->plugin->transform(array(), $this->migrateExecutable, $this->row, 'destinationproperty');
$this->setExpectedException(MigrateException::class);
$this->plugin->transform([], $this->migrateExecutable, $this->row, 'destinationproperty');
}
/**
* Tests when the source is invalid.
*
* @expectedException \Drupal\migrate\MigrateSkipRowException
*/
public function testMapwithInvalidSource() {
$this->plugin->transform(array('bar'), $this->migrateExecutable, $this->row, 'destinationproperty');
$this->setExpectedException(MigrateSkipRowException::class);
$this->plugin->transform(['bar'], $this->migrateExecutable, $this->row, 'destinationproperty');
}
/**
@ -60,8 +60,8 @@ class StaticMapTest extends MigrateProcessTestCase {
public function testMapWithInvalidSourceWithADefaultValue() {
$configuration['map']['foo']['bar'] = 'baz';
$configuration['default_value'] = 'test';
$this->plugin = new StaticMap($configuration, 'map', array());
$value = $this->plugin->transform(array('bar'), $this->migrateExecutable, $this->row, 'destinationproperty');
$this->plugin = new StaticMap($configuration, 'map', []);
$value = $this->plugin->transform(['bar'], $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame($value, 'test');
}
@ -72,22 +72,20 @@ class StaticMapTest extends MigrateProcessTestCase {
$configuration['map']['foo']['bar'] = 'baz';
$configuration['default_value'] = NULL;
$this->plugin = new StaticMap($configuration, 'map', []);
$value = $this->plugin->transform(array('bar'), $this->migrateExecutable, $this->row, 'destinationproperty');
$value = $this->plugin->transform(['bar'], $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertNull($value);
}
/**
* Tests when the source is invalid and bypass is enabled.
*
* @expectedException \Drupal\migrate\MigrateException
* @expectedExceptionMessage Setting both default_value and bypass is invalid.
*/
public function testMapWithInvalidSourceAndBypass() {
$configuration['map']['foo']['bar'] = 'baz';
$configuration['default_value'] = 'test';
$configuration['bypass'] = TRUE;
$this->plugin = new StaticMap($configuration, 'map', array());
$this->plugin->transform(array('bar'), $this->migrateExecutable, $this->row, 'destinationproperty');
$this->plugin = new StaticMap($configuration, 'map', []);
$this->setExpectedException(MigrateException::class, 'Setting both default_value and bypass is invalid.');
$this->plugin->transform(['bar'], $this->migrateExecutable, $this->row, 'destinationproperty');
}
}

View file

@ -2,6 +2,7 @@
namespace Drupal\Tests\migrate\Unit\process;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Plugin\migrate\process\Substr;
/**
@ -55,37 +56,31 @@ class SubstrTest extends MigrateProcessTestCase {
/**
* Tests invalid input type.
*
* @expectedException \Drupal\migrate\MigrateException
* @expectedExceptionMessage The input value must be a string.
*/
public function testSubstrFail() {
$configuration = [];
$this->plugin = new Substr($configuration, 'map', []);
$this->setExpectedException(MigrateException::class, 'The input value must be a string.');
$this->plugin->transform(['Captain Janeway'], $this->migrateExecutable, $this->row, 'destinationproperty');
}
/**
* Tests that the start parameter is an integer.
*
* @expectedException \Drupal\migrate\MigrateException
* @expectedExceptionMessage The start position configuration value should be an integer. Omit this key to capture from the beginning of the string.
*/
public function testStartIsString() {
$configuration['start'] = '2';
$this->plugin = new Substr($configuration, 'map', []);
$this->setExpectedException(MigrateException::class, 'The start position configuration value should be an integer. Omit this key to capture from the beginning of the string.');
$this->plugin->transform(['foo'], $this->migrateExecutable, $this->row, 'destinationproperty');
}
/**
* Tests that the length parameter is an integer.
*
* @expectedException \Drupal\migrate\MigrateException
* @expectedExceptionMessage The character length configuration value should be an integer. Omit this key to capture from the start position to the end of the string.
*/
public function testLengthIsString() {
$configuration['length'] = '1';
$this->plugin = new Substr($configuration, 'map', []);
$this->setExpectedException(MigrateException::class, 'The character length configuration value should be an integer. Omit this key to capture from the start position to the end of the string.');
$this->plugin->transform(['foo'], $this->migrateExecutable, $this->row, 'destinationproperty');
}

View file

@ -28,14 +28,14 @@ class UrlEncodeTest extends MigrateTestCase {
* An array of URLs to test.
*/
public function urlDataProvider() {
return array(
'A URL with no characters requiring encoding' => array('http://example.com/normal_url.html', 'http://example.com/normal_url.html'),
'The definitive use case - encoding spaces in URLs' => array('http://example.com/url with spaces.html', 'http://example.com/url%20with%20spaces.html'),
'Definitive use case 2 - spaces in directories' => array('http://example.com/dir with spaces/foo.html', 'http://example.com/dir%20with%20spaces/foo.html'),
'Local filespecs without spaces should not be transformed' => array('/tmp/normal.txt', '/tmp/normal.txt'),
'Local filespecs with spaces should not be transformed' => array('/tmp/with spaces.txt', '/tmp/with spaces.txt'),
'Make sure URL characters (:, ?, &) are not encoded but others are.' => array('https://example.com/?a=b@c&d=e+f%', 'https://example.com/?a%3Db%40c&d%3De%2Bf%25'),
);
return [
'A URL with no characters requiring encoding' => ['http://example.com/normal_url.html', 'http://example.com/normal_url.html'],
'The definitive use case - encoding spaces in URLs' => ['http://example.com/url with spaces.html', 'http://example.com/url%20with%20spaces.html'],
'Definitive use case 2 - spaces in directories' => ['http://example.com/dir with spaces/foo.html', 'http://example.com/dir%20with%20spaces/foo.html'],
'Local filespecs without spaces should not be transformed' => ['/tmp/normal.txt', '/tmp/normal.txt'],
'Local filespecs with spaces should not be transformed' => ['/tmp/with spaces.txt', '/tmp/with spaces.txt'],
'Make sure URL characters (:, ?, &) are not encoded but others are.' => ['https://example.com/?a=b@c&d=e+f%', 'https://example.com/?a%3Db%40c&d%3De%2Bf%25'],
];
}
/**