Update to Drupal 8.1.0. For more information, see https://www.drupal.org/drupal-8.1.0-release-notes
This commit is contained in:
parent
b11a755ba8
commit
c0a0d5a94c
6920 changed files with 64395 additions and 57312 deletions
|
@ -1,10 +1,5 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\file_module_test\Form\FileModuleTestForm.
|
||||
*/
|
||||
|
||||
namespace Drupal\file_module_test\Form;
|
||||
|
||||
use Drupal\Core\Form\FormBase;
|
||||
|
|
|
@ -1,8 +1,4 @@
|
|||
<?php
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\file_test\FileTestAccessControlHandler.
|
||||
*/
|
||||
|
||||
namespace Drupal\file_test;
|
||||
|
||||
|
|
|
@ -1,8 +1,4 @@
|
|||
<?php
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\file_test\Form\FileTestForm.
|
||||
*/
|
||||
|
||||
namespace Drupal\file_test\Form;
|
||||
|
||||
|
|
|
@ -1,10 +1,5 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\file_test\StreamWrapper\DummyReadOnlyStreamWrapper.
|
||||
*/
|
||||
|
||||
namespace Drupal\file_test\StreamWrapper;
|
||||
|
||||
use Drupal\Core\StreamWrapper\LocalReadOnlyStream;
|
||||
|
|
|
@ -1,10 +1,5 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\file_test\StreamWrapper\DummyRemoteStreamWrapper.
|
||||
*/
|
||||
|
||||
namespace Drupal\file_test\StreamWrapper;
|
||||
|
||||
use Drupal\Core\StreamWrapper\PublicStream;
|
||||
|
|
|
@ -1,10 +1,5 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\file_test\StreamWrapper\DummyStreamWrapper.
|
||||
*/
|
||||
|
||||
namespace Drupal\file_test\StreamWrapper;
|
||||
|
||||
use Drupal\Core\StreamWrapper\LocalStream;
|
||||
|
|
144
core/modules/file/tests/src/Kernel/CopyTest.php
Normal file
144
core/modules/file/tests/src/Kernel/CopyTest.php
Normal file
|
@ -0,0 +1,144 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests the file copy function.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class CopyTest extends FileManagedUnitTestBase {
|
||||
/**
|
||||
* Test file copying in the normal, base case.
|
||||
*/
|
||||
function testNormal() {
|
||||
$contents = $this->randomMachineName(10);
|
||||
$source = $this->createFile(NULL, $contents);
|
||||
$desired_uri = 'public://' . $this->randomMachineName();
|
||||
|
||||
// Clone the object so we don't have to worry about the function changing
|
||||
// our reference copy.
|
||||
$result = file_copy(clone $source, $desired_uri, FILE_EXISTS_ERROR);
|
||||
|
||||
// Check the return status and that the contents changed.
|
||||
$this->assertTrue($result, 'File copied successfully.');
|
||||
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of file were copied correctly.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('copy', 'insert'));
|
||||
|
||||
$this->assertDifferentFile($source, $result);
|
||||
$this->assertEqual($result->getFileUri(), $desired_uri, 'The copied file entity has the desired filepath.');
|
||||
$this->assertTrue(file_exists($source->getFileUri()), 'The original file still exists.');
|
||||
$this->assertTrue(file_exists($result->getFileUri()), 'The copied file exists.');
|
||||
|
||||
// Reload the file from the database and check that the changes were
|
||||
// actually saved.
|
||||
$this->assertFileUnchanged($result, File::load($result->id()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test renaming when copying over a file that already exists.
|
||||
*/
|
||||
function testExistingRename() {
|
||||
// Setup a file to overwrite.
|
||||
$contents = $this->randomMachineName(10);
|
||||
$source = $this->createFile(NULL, $contents);
|
||||
$target = $this->createFile();
|
||||
$this->assertDifferentFile($source, $target);
|
||||
|
||||
// Clone the object so we don't have to worry about the function changing
|
||||
// our reference copy.
|
||||
$result = file_copy(clone $source, $target->getFileUri(), FILE_EXISTS_RENAME);
|
||||
|
||||
// Check the return status and that the contents changed.
|
||||
$this->assertTrue($result, 'File copied successfully.');
|
||||
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of file were copied correctly.');
|
||||
$this->assertNotEqual($result->getFileUri(), $source->getFileUri(), 'Returned file path has changed from the original.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('copy', 'insert'));
|
||||
|
||||
// Load all the affected files to check the changes that actually made it
|
||||
// to the database.
|
||||
$loaded_source = File::load($source->id());
|
||||
$loaded_target = File::load($target->id());
|
||||
$loaded_result = File::load($result->id());
|
||||
|
||||
// Verify that the source file wasn't changed.
|
||||
$this->assertFileUnchanged($source, $loaded_source);
|
||||
|
||||
// Verify that what was returned is what's in the database.
|
||||
$this->assertFileUnchanged($result, $loaded_result);
|
||||
|
||||
// Make sure we end up with three distinct files afterwards.
|
||||
$this->assertDifferentFile($loaded_source, $loaded_target);
|
||||
$this->assertDifferentFile($loaded_target, $loaded_result);
|
||||
$this->assertDifferentFile($loaded_source, $loaded_result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test replacement when copying over a file that already exists.
|
||||
*/
|
||||
function testExistingReplace() {
|
||||
// Setup a file to overwrite.
|
||||
$contents = $this->randomMachineName(10);
|
||||
$source = $this->createFile(NULL, $contents);
|
||||
$target = $this->createFile();
|
||||
$this->assertDifferentFile($source, $target);
|
||||
|
||||
// Clone the object so we don't have to worry about the function changing
|
||||
// our reference copy.
|
||||
$result = file_copy(clone $source, $target->getFileUri(), FILE_EXISTS_REPLACE);
|
||||
|
||||
// Check the return status and that the contents changed.
|
||||
$this->assertTrue($result, 'File copied successfully.');
|
||||
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of file were overwritten.');
|
||||
$this->assertDifferentFile($source, $result);
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('load', 'copy', 'update'));
|
||||
|
||||
// Load all the affected files to check the changes that actually made it
|
||||
// to the database.
|
||||
$loaded_source = File::load($source->id());
|
||||
$loaded_target = File::load($target->id());
|
||||
$loaded_result = File::load($result->id());
|
||||
|
||||
// Verify that the source file wasn't changed.
|
||||
$this->assertFileUnchanged($source, $loaded_source);
|
||||
|
||||
// Verify that what was returned is what's in the database.
|
||||
$this->assertFileUnchanged($result, $loaded_result);
|
||||
|
||||
// Target file was reused for the result.
|
||||
$this->assertFileUnchanged($loaded_target, $loaded_result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that copying over an existing file fails when FILE_EXISTS_ERROR is
|
||||
* specified.
|
||||
*/
|
||||
function testExistingError() {
|
||||
$contents = $this->randomMachineName(10);
|
||||
$source = $this->createFile();
|
||||
$target = $this->createFile(NULL, $contents);
|
||||
$this->assertDifferentFile($source, $target);
|
||||
|
||||
// Clone the object so we don't have to worry about the function changing
|
||||
// our reference copy.
|
||||
$result = file_copy(clone $source, $target->getFileUri(), FILE_EXISTS_ERROR);
|
||||
|
||||
// Check the return status and that the contents were not changed.
|
||||
$this->assertFalse($result, 'File copy failed.');
|
||||
$this->assertEqual($contents, file_get_contents($target->getFileUri()), 'Contents of file were not altered.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array());
|
||||
|
||||
$this->assertFileUnchanged($source, File::load($source->id()));
|
||||
$this->assertFileUnchanged($target, File::load($target->id()));
|
||||
}
|
||||
}
|
71
core/modules/file/tests/src/Kernel/DeleteTest.php
Normal file
71
core/modules/file/tests/src/Kernel/DeleteTest.php
Normal file
|
@ -0,0 +1,71 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests the file delete function.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class DeleteTest extends FileManagedUnitTestBase {
|
||||
/**
|
||||
* Tries deleting a normal file (as opposed to a directory, symlink, etc).
|
||||
*/
|
||||
function testUnused() {
|
||||
$file = $this->createFile();
|
||||
|
||||
// Check that deletion removes the file and database record.
|
||||
$this->assertTrue(is_file($file->getFileUri()), 'File exists.');
|
||||
$file->delete();
|
||||
$this->assertFileHooksCalled(array('delete'));
|
||||
$this->assertFalse(file_exists($file->getFileUri()), 'Test file has actually been deleted.');
|
||||
$this->assertFalse(File::load($file->id()), 'File was removed from the database.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries deleting a file that is in use.
|
||||
*/
|
||||
function testInUse() {
|
||||
$file = $this->createFile();
|
||||
$file_usage = $this->container->get('file.usage');
|
||||
$file_usage->add($file, 'testing', 'test', 1);
|
||||
$file_usage->add($file, 'testing', 'test', 1);
|
||||
|
||||
$file_usage->delete($file, 'testing', 'test', 1);
|
||||
$usage = $file_usage->listUsage($file);
|
||||
$this->assertEqual($usage['testing']['test'], array(1 => 1), 'Test file is still in use.');
|
||||
$this->assertTrue(file_exists($file->getFileUri()), 'File still exists on the disk.');
|
||||
$this->assertTrue(File::load($file->id()), 'File still exists in the database.');
|
||||
|
||||
// Clear out the call to hook_file_load().
|
||||
file_test_reset();
|
||||
|
||||
$file_usage->delete($file, 'testing', 'test', 1);
|
||||
$usage = $file_usage->listUsage($file);
|
||||
$this->assertFileHooksCalled(array('load', 'update'));
|
||||
$this->assertTrue(empty($usage), 'File usage data was removed.');
|
||||
$this->assertTrue(file_exists($file->getFileUri()), 'File still exists on the disk.');
|
||||
$file = File::load($file->id());
|
||||
$this->assertTrue($file, 'File still exists in the database.');
|
||||
$this->assertTrue($file->isTemporary(), 'File is temporary.');
|
||||
file_test_reset();
|
||||
|
||||
// Call file_cron() to clean up the file. Make sure the changed timestamp
|
||||
// of the file is older than the system.file.temporary_maximum_age
|
||||
// configuration value.
|
||||
db_update('file_managed')
|
||||
->fields(array(
|
||||
'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1),
|
||||
))
|
||||
->condition('fid', $file->id())
|
||||
->execute();
|
||||
\Drupal::service('cron')->run();
|
||||
|
||||
// file_cron() loads
|
||||
$this->assertFileHooksCalled(array('delete'));
|
||||
$this->assertFalse(file_exists($file->getFileUri()), 'File has been deleted after its last usage was removed.');
|
||||
$this->assertFalse(File::load($file->id()), 'File was removed from the database.');
|
||||
}
|
||||
}
|
142
core/modules/file/tests/src/Kernel/FileItemTest.php
Normal file
142
core/modules/file/tests/src/Kernel/FileItemTest.php
Normal file
|
@ -0,0 +1,142 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel;
|
||||
|
||||
use Drupal\Core\Field\FieldItemInterface;
|
||||
use Drupal\Core\Field\FieldItemListInterface;
|
||||
use Drupal\Core\Field\FieldStorageDefinitionInterface;
|
||||
use Drupal\entity_test\Entity\EntityTest;
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests using entity fields of the file field type.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class FileItemTest extends FieldKernelTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('file');
|
||||
|
||||
/**
|
||||
* Created file entity.
|
||||
*
|
||||
* @var \Drupal\file\Entity\File
|
||||
*/
|
||||
protected $file;
|
||||
|
||||
/**
|
||||
* Directory where the sample files are stored.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $directory;
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->installEntitySchema('file');
|
||||
$this->installSchema('file', array('file_usage'));
|
||||
|
||||
FieldStorageConfig::create(array(
|
||||
'field_name' => 'file_test',
|
||||
'entity_type' => 'entity_test',
|
||||
'type' => 'file',
|
||||
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
|
||||
))->save();
|
||||
$this->directory = $this->getRandomGenerator()->name(8);
|
||||
FieldConfig::create([
|
||||
'entity_type' => 'entity_test',
|
||||
'field_name' => 'file_test',
|
||||
'bundle' => 'entity_test',
|
||||
'settings' => array('file_directory' => $this->directory),
|
||||
])->save();
|
||||
file_put_contents('public://example.txt', $this->randomMachineName());
|
||||
$this->file = File::create([
|
||||
'uri' => 'public://example.txt',
|
||||
]);
|
||||
$this->file->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests using entity fields of the file field type.
|
||||
*/
|
||||
public function testFileItem() {
|
||||
// Check that the selection handler was automatically assigned to
|
||||
// 'default:file'.
|
||||
$field_definition = FieldConfig::load('entity_test.entity_test.file_test');
|
||||
$handler_id = $field_definition->getSetting('handler');
|
||||
$this->assertEqual($handler_id, 'default:file');
|
||||
|
||||
// Create a test entity with the
|
||||
$entity = EntityTest::create();
|
||||
$entity->file_test->target_id = $this->file->id();
|
||||
$entity->file_test->display = 1;
|
||||
$entity->file_test->description = $description = $this->randomMachineName();
|
||||
$entity->name->value = $this->randomMachineName();
|
||||
$entity->save();
|
||||
|
||||
$entity = entity_load('entity_test', $entity->id());
|
||||
$this->assertTrue($entity->file_test instanceof FieldItemListInterface, 'Field implements interface.');
|
||||
$this->assertTrue($entity->file_test[0] instanceof FieldItemInterface, 'Field item implements interface.');
|
||||
$this->assertEqual($entity->file_test->target_id, $this->file->id());
|
||||
$this->assertEqual($entity->file_test->display, 1);
|
||||
$this->assertEqual($entity->file_test->description, $description);
|
||||
$this->assertEqual($entity->file_test->entity->getFileUri(), $this->file->getFileUri());
|
||||
$this->assertEqual($entity->file_test->entity->url(), $url = file_create_url($this->file->getFileUri()));
|
||||
$this->assertEqual($entity->file_test->entity->id(), $this->file->id());
|
||||
$this->assertEqual($entity->file_test->entity->uuid(), $this->file->uuid());
|
||||
|
||||
// Make sure the computed files reflects updates to the file.
|
||||
file_put_contents('public://example-2.txt', $this->randomMachineName());
|
||||
$file2 = File::create([
|
||||
'uri' => 'public://example-2.txt',
|
||||
]);
|
||||
$file2->save();
|
||||
|
||||
$entity->file_test->target_id = $file2->id();
|
||||
$this->assertEqual($entity->file_test->entity->id(), $file2->id());
|
||||
$this->assertEqual($entity->file_test->entity->getFileUri(), $file2->getFileUri());
|
||||
|
||||
// Test the deletion of an entity having an entity reference field targeting
|
||||
// a non-existing entity.
|
||||
$file2->delete();
|
||||
$entity->delete();
|
||||
|
||||
// Test the generateSampleValue() method.
|
||||
$entity = EntityTest::create();
|
||||
$entity->file_test->generateSampleItems();
|
||||
$this->entityValidateAndSave($entity);
|
||||
// Verify that the sample file was stored in the correct directory.
|
||||
$uri = $entity->file_test->entity->getFileUri();
|
||||
$this->assertEqual($this->directory, dirname(file_uri_target($uri)));
|
||||
|
||||
// Make sure the computed files reflects updates to the file.
|
||||
file_put_contents('public://example-3.txt', $this->randomMachineName());
|
||||
// Test unsaved file entity.
|
||||
$file3 = File::create([
|
||||
'uri' => 'public://example-3.txt',
|
||||
]);
|
||||
$display = entity_get_display('entity_test', 'entity_test', 'default');
|
||||
$display->setComponent('file_test', [
|
||||
'label' => 'above',
|
||||
'type' => 'file_default',
|
||||
'weight' => 1,
|
||||
])->save();
|
||||
$entity = EntityTest::create();
|
||||
$entity->file_test = array('entity' => $file3);
|
||||
$uri = $file3->getFileUri();
|
||||
$output = entity_view($entity, 'default');
|
||||
\Drupal::service('renderer')->renderRoot($output);
|
||||
$this->assertTrue(!empty($entity->file_test->entity));
|
||||
$this->assertEqual($entity->file_test->entity->getFileUri(), $uri);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,10 +1,5 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Tests\file\Kernel\FileItemValidationTest.
|
||||
*/
|
||||
|
||||
namespace Drupal\Tests\file\Kernel;
|
||||
|
||||
use Drupal\entity_test\Entity\EntityTest;
|
||||
|
|
213
core/modules/file/tests/src/Kernel/FileManagedUnitTestBase.php
Normal file
213
core/modules/file/tests/src/Kernel/FileManagedUnitTestBase.php
Normal file
|
@ -0,0 +1,213 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\file\FileInterface;
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
use Drupal\user\Entity\User;
|
||||
|
||||
/**
|
||||
* Base class for file unit tests that use the file_test module to test uploads and
|
||||
* hooks.
|
||||
*/
|
||||
abstract class FileManagedUnitTestBase extends KernelTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('file_test', 'file', 'system', 'field', 'user');
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
// Clear out any hook calls.
|
||||
file_test_reset();
|
||||
|
||||
$this->installConfig(array('system'));
|
||||
$this->installEntitySchema('file');
|
||||
$this->installEntitySchema('user');
|
||||
$this->installSchema('file', array('file_usage'));
|
||||
|
||||
// Make sure that a user with uid 1 exists, self::createFile() relies on
|
||||
// it.
|
||||
$user = User::create(['uid' => 1, 'name' => $this->randomMachineName()]);
|
||||
$user->enforceIsNew();
|
||||
$user->save();
|
||||
\Drupal::currentUser()->setAccount($user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that all of the specified hook_file_* hooks were called once, other
|
||||
* values result in failure.
|
||||
*
|
||||
* @param array $expected
|
||||
* Array with string containing with the hook name, e.g. 'load', 'save',
|
||||
* 'insert', etc.
|
||||
*/
|
||||
function assertFileHooksCalled($expected) {
|
||||
\Drupal::state()->resetCache();
|
||||
|
||||
// Determine which hooks were called.
|
||||
$actual = array_keys(array_filter(file_test_get_all_calls()));
|
||||
|
||||
// Determine if there were any expected that were not called.
|
||||
$uncalled = array_diff($expected, $actual);
|
||||
if (count($uncalled)) {
|
||||
$this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled))));
|
||||
}
|
||||
else {
|
||||
$this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', array('%expected' => empty($expected) ? '(none)' : implode(', ', $expected))));
|
||||
}
|
||||
|
||||
// Determine if there were any unexpected calls.
|
||||
$unexpected = array_diff($actual, $expected);
|
||||
if (count($unexpected)) {
|
||||
$this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', array('%unexpected' => empty($unexpected) ? '(none)' : implode(', ', $unexpected))));
|
||||
}
|
||||
else {
|
||||
$this->assertTrue(TRUE, 'No unexpected hooks were called.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that a hook_file_* hook was called a certain number of times.
|
||||
*
|
||||
* @param string $hook
|
||||
* String with the hook name, e.g. 'load', 'save', 'insert', etc.
|
||||
* @param int $expected_count
|
||||
* Optional integer count.
|
||||
* @param string $message
|
||||
* Optional translated string message.
|
||||
*/
|
||||
function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
|
||||
$actual_count = count(file_test_get_calls($hook));
|
||||
|
||||
if (!isset($message)) {
|
||||
if ($actual_count == $expected_count) {
|
||||
$message = format_string('hook_file_@name was called correctly.', array('@name' => $hook));
|
||||
}
|
||||
elseif ($expected_count == 0) {
|
||||
$message = \Drupal::translation()->formatPlural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', array('@name' => $hook, '@count' => $actual_count));
|
||||
}
|
||||
else {
|
||||
$message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', array('@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count));
|
||||
}
|
||||
}
|
||||
$this->assertEqual($actual_count, $expected_count, $message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that two files have the same values (except timestamp).
|
||||
*
|
||||
* @param \Drupal\file\FileInterface $before
|
||||
* File object to compare.
|
||||
* @param \Drupal\file\FileInterface $after
|
||||
* File object to compare.
|
||||
*/
|
||||
function assertFileUnchanged(FileInterface $before, FileInterface $after) {
|
||||
$this->assertEqual($before->id(), $after->id(), t('File id is the same: %file1 == %file2.', array('%file1' => $before->id(), '%file2' => $after->id())), 'File unchanged');
|
||||
$this->assertEqual($before->getOwner()->id(), $after->getOwner()->id(), t('File owner is the same: %file1 == %file2.', array('%file1' => $before->getOwner()->id(), '%file2' => $after->getOwner()->id())), 'File unchanged');
|
||||
$this->assertEqual($before->getFilename(), $after->getFilename(), t('File name is the same: %file1 == %file2.', array('%file1' => $before->getFilename(), '%file2' => $after->getFilename())), 'File unchanged');
|
||||
$this->assertEqual($before->getFileUri(), $after->getFileUri(), t('File path is the same: %file1 == %file2.', array('%file1' => $before->getFileUri(), '%file2' => $after->getFileUri())), 'File unchanged');
|
||||
$this->assertEqual($before->getMimeType(), $after->getMimeType(), t('File MIME type is the same: %file1 == %file2.', array('%file1' => $before->getMimeType(), '%file2' => $after->getMimeType())), 'File unchanged');
|
||||
$this->assertEqual($before->getSize(), $after->getSize(), t('File size is the same: %file1 == %file2.', array('%file1' => $before->getSize(), '%file2' => $after->getSize())), 'File unchanged');
|
||||
$this->assertEqual($before->isPermanent(), $after->isPermanent(), t('File status is the same: %file1 == %file2.', array('%file1' => $before->isPermanent(), '%file2' => $after->isPermanent())), 'File unchanged');
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that two files are not the same by comparing the fid and filepath.
|
||||
*
|
||||
* @param \Drupal\file\FileInterface $file1
|
||||
* File object to compare.
|
||||
* @param \Drupal\file\FileInterface $file2
|
||||
* File object to compare.
|
||||
*/
|
||||
function assertDifferentFile(FileInterface $file1, FileInterface $file2) {
|
||||
$this->assertNotEqual($file1->id(), $file2->id(), t('Files have different ids: %file1 != %file2.', array('%file1' => $file1->id(), '%file2' => $file2->id())), 'Different file');
|
||||
$this->assertNotEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have different paths: %file1 != %file2.', array('%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri())), 'Different file');
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that two files are the same by comparing the fid and filepath.
|
||||
*
|
||||
* @param \Drupal\file\FileInterface $file1
|
||||
* File object to compare.
|
||||
* @param \Drupal\file\FileInterface $file2
|
||||
* File object to compare.
|
||||
*/
|
||||
function assertSameFile(FileInterface $file1, FileInterface $file2) {
|
||||
$this->assertEqual($file1->id(), $file2->id(), t('Files have the same ids: %file1 == %file2.', array('%file1' => $file1->id(), '%file2-fid' => $file2->id())), 'Same file');
|
||||
$this->assertEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have the same path: %file1 == %file2.', array('%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri())), 'Same file');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a file and save it to the files table and assert that it occurs
|
||||
* correctly.
|
||||
*
|
||||
* @param string $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 string $contents
|
||||
* Optional contents to save into the file. If a NULL value is provided an
|
||||
* arbitrary string will be used.
|
||||
* @param string $scheme
|
||||
* Optional string indicating the stream scheme to use. Drupal core includes
|
||||
* public, private, and temporary. The public wrapper is the default.
|
||||
* @return \Drupal\file\FileInterface
|
||||
* File entity.
|
||||
*/
|
||||
function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
|
||||
// Don't count hook invocations caused by creating the file.
|
||||
\Drupal::state()->set('file_test.count_hook_invocations', FALSE);
|
||||
$file = File::create([
|
||||
'uri' => $this->createUri($filepath, $contents, $scheme),
|
||||
'uid' => 1,
|
||||
]);
|
||||
$file->save();
|
||||
// Write the record directly rather than using the API so we don't invoke
|
||||
// the hooks.
|
||||
$this->assertTrue($file->id() > 0, 'The file was added to the database.', 'Create test file');
|
||||
|
||||
\Drupal::state()->set('file_test.count_hook_invocations', TRUE);
|
||||
return $file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a file and returns its URI.
|
||||
*
|
||||
* @param string $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 string $contents
|
||||
* Optional contents to save into the file. If a NULL value is provided an
|
||||
* arbitrary string will be used.
|
||||
* @param string $scheme
|
||||
* Optional string indicating the stream scheme to use. Drupal core includes
|
||||
* public, private, and temporary. The public wrapper is the default.
|
||||
*
|
||||
* @return string
|
||||
* File URI.
|
||||
*/
|
||||
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 (!isset($scheme)) {
|
||||
$scheme = file_default_scheme();
|
||||
}
|
||||
$filepath = $scheme . '://' . $filepath;
|
||||
|
||||
if (!isset($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->assertTrue(is_file($filepath), t('The test file exists on the disk.'), 'Create test file');
|
||||
return $filepath;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,168 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Formatter;
|
||||
|
||||
use Drupal\Core\Entity\Entity\EntityViewDisplay;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
|
||||
/**
|
||||
* Tests the default file formatter.
|
||||
*
|
||||
* @group field
|
||||
*/
|
||||
class FileEntityFormatterTest extends KernelTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = ['file', 'user'];
|
||||
|
||||
/**
|
||||
* The files.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $files;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->installEntitySchema('file');
|
||||
|
||||
$this->files = [];
|
||||
file_put_contents('public://file.png', str_repeat('t', 10));
|
||||
$file = File::create([
|
||||
'uri' => 'public://file.png',
|
||||
'filename' => 'file.png',
|
||||
]);
|
||||
$file->save();
|
||||
$this->files[] = $file;
|
||||
|
||||
file_put_contents('public://file.tar', str_repeat('t', 200));
|
||||
$file = File::create([
|
||||
'uri' => 'public://file.tar',
|
||||
'filename' => 'file.tar',
|
||||
]);
|
||||
$file->save();
|
||||
$this->files[] = $file;
|
||||
|
||||
file_put_contents('public://file.tar.gz', str_repeat('t', 40000));
|
||||
$file = File::create([
|
||||
'uri' => 'public://file.tar.gz',
|
||||
'filename' => 'file.tar.gz',
|
||||
]);
|
||||
$file->save();
|
||||
$this->files[] = $file;
|
||||
|
||||
file_put_contents('public://file', str_repeat('t', 8000000));
|
||||
$file = File::create([
|
||||
'uri' => 'public://file',
|
||||
'filename' => 'file',
|
||||
]);
|
||||
$file->save();
|
||||
$this->files[] = $file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the file_link field formatter.
|
||||
*/
|
||||
public function testFormatterFileLink() {
|
||||
$entity_display = EntityViewDisplay::create([
|
||||
'targetEntityType' => 'file',
|
||||
'bundle' => 'file',
|
||||
]);
|
||||
$entity_display->setComponent('filename', ['type' => 'file_link']);
|
||||
|
||||
$build = $entity_display->buildMultiple($this->files)[0]['filename'][0];
|
||||
$this->assertEqual('file.png', $build['#title']);
|
||||
$this->assertEqual(Url::fromUri(file_create_url('public://file.png')), $build['#url']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the file_link field formatter.
|
||||
*/
|
||||
public function testFormatterFileUri() {
|
||||
$entity_display = EntityViewDisplay::create([
|
||||
'targetEntityType' => 'file',
|
||||
'bundle' => 'file',
|
||||
]);
|
||||
$entity_display->setComponent('uri', ['type' => 'file_uri']);
|
||||
|
||||
$build = $entity_display->buildMultiple($this->files)[0]['uri'][0];
|
||||
$this->assertEqual('public://file.png', $build['#markup']);
|
||||
|
||||
$entity_display->setComponent('uri', ['type' => 'file_uri', 'settings' => ['file_download_path' => TRUE]]);
|
||||
$build = $entity_display->buildMultiple($this->files)[0]['uri'][0];
|
||||
$this->assertEqual(file_create_url('public://file.png'), $build['#markup']);
|
||||
|
||||
$entity_display->setComponent('uri', ['type' => 'file_uri', 'settings' => ['file_download_path' => TRUE, 'link_to_file' => TRUE]]);
|
||||
$build = $entity_display->buildMultiple($this->files)[0]['uri'][0];
|
||||
$this->assertEqual(file_create_url('public://file.png'), $build['#title']);
|
||||
$this->assertEqual(Url::fromUri(file_create_url('public://file.png')), $build['#url']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the file_extension field formatter.
|
||||
*/
|
||||
public function testFormatterFileExtension() {
|
||||
$entity_display = EntityViewDisplay::create([
|
||||
'targetEntityType' => 'file',
|
||||
'bundle' => 'file',
|
||||
]);
|
||||
$entity_display->setComponent('filename', ['type' => 'file_extension']);
|
||||
|
||||
$expected = ['png', 'tar', 'gz', ''];
|
||||
foreach (array_values($this->files) as $i => $file) {
|
||||
$build = $entity_display->build($file);
|
||||
$this->assertEqual($expected[$i], $build['filename'][0]['#markup']);
|
||||
}
|
||||
|
||||
$entity_display->setComponent('filename', ['type' => 'file_extension', 'settings' => ['extension_detect_tar' => TRUE]]);
|
||||
|
||||
$expected = ['png', 'tar', 'tar.gz', ''];
|
||||
foreach (array_values($this->files) as $i => $file) {
|
||||
$build = $entity_display->build($file);
|
||||
$this->assertEqual($expected[$i], $build['filename'][0]['#markup']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the file_extension field formatter.
|
||||
*/
|
||||
public function testFormatterFileMime() {
|
||||
$entity_display = EntityViewDisplay::create([
|
||||
'targetEntityType' => 'file',
|
||||
'bundle' => 'file',
|
||||
]);
|
||||
$entity_display->setComponent('filemime', ['type' => 'file_filemime', 'settings' => ['filemime_image' => TRUE]]);
|
||||
|
||||
foreach (array_values($this->files) as $i => $file) {
|
||||
$build = $entity_display->build($file);
|
||||
$this->assertEqual('image__file_icon', $build['filemime'][0]['#theme']);
|
||||
$this->assertEqual(spl_object_hash($file), spl_object_hash($build['filemime'][0]['#file']));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the file_size field formatter.
|
||||
*/
|
||||
public function testFormatterFileSize() {
|
||||
$entity_display = EntityViewDisplay::create([
|
||||
'targetEntityType' => 'file',
|
||||
'bundle' => 'file',
|
||||
]);
|
||||
$entity_display->setComponent('filesize', ['type' => 'file_size']);
|
||||
|
||||
$expected = ['10 bytes', '200 bytes', '39.06 KB', '7.63 MB'];
|
||||
foreach (array_values($this->files) as $i => $file) {
|
||||
$build = $entity_display->build($file);
|
||||
$this->assertEqual($expected[$i], $build['filesize'][0]['#markup']);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
100
core/modules/file/tests/src/Kernel/LoadTest.php
Normal file
100
core/modules/file/tests/src/Kernel/LoadTest.php
Normal file
|
@ -0,0 +1,100 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests \Drupal\file\Entity\File::load().
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class LoadTest extends FileManagedUnitTestBase {
|
||||
/**
|
||||
* Try to load a non-existent file by fid.
|
||||
*/
|
||||
function testLoadMissingFid() {
|
||||
$this->assertFalse(File::load(-1), 'Try to load an invalid fid fails.');
|
||||
$this->assertFileHooksCalled(array());
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to load a non-existent file by URI.
|
||||
*/
|
||||
function testLoadMissingFilepath() {
|
||||
$files = entity_load_multiple_by_properties('file', array('uri' => 'foobar://misc/druplicon.png'));
|
||||
$this->assertFalse(reset($files), "Try to load a file that doesn't exist in the database fails.");
|
||||
$this->assertFileHooksCalled(array());
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to load a non-existent file by status.
|
||||
*/
|
||||
function testLoadInvalidStatus() {
|
||||
$files = entity_load_multiple_by_properties('file', array('status' => -99));
|
||||
$this->assertFalse(reset($files), 'Trying to load a file with an invalid status fails.');
|
||||
$this->assertFileHooksCalled(array());
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a single file and ensure that the correct values are returned.
|
||||
*/
|
||||
function testSingleValues() {
|
||||
// Create a new file entity from scratch so we know the values.
|
||||
$file = $this->createFile('druplicon.txt', NULL, 'public');
|
||||
$by_fid_file = File::load($file->id());
|
||||
$this->assertFileHookCalled('load');
|
||||
$this->assertTrue(is_object($by_fid_file), '\Drupal\file\Entity\File::load() returned an object.');
|
||||
$this->assertEqual($by_fid_file->id(), $file->id(), 'Loading by fid got the same fid.', 'File');
|
||||
$this->assertEqual($by_fid_file->getFileUri(), $file->getFileUri(), 'Loading by fid got the correct filepath.', 'File');
|
||||
$this->assertEqual($by_fid_file->getFilename(), $file->getFilename(), 'Loading by fid got the correct filename.', 'File');
|
||||
$this->assertEqual($by_fid_file->getMimeType(), $file->getMimeType(), 'Loading by fid got the correct MIME type.', 'File');
|
||||
$this->assertEqual($by_fid_file->isPermanent(), $file->isPermanent(), 'Loading by fid got the correct status.', 'File');
|
||||
$this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
|
||||
}
|
||||
|
||||
/**
|
||||
* This will test loading file data from the database.
|
||||
*/
|
||||
function testMultiple() {
|
||||
// Create a new file entity.
|
||||
$file = $this->createFile('druplicon.txt', NULL, 'public');
|
||||
|
||||
// Load by path.
|
||||
file_test_reset();
|
||||
$by_path_files = entity_load_multiple_by_properties('file', array('uri' => $file->getFileUri()));
|
||||
$this->assertFileHookCalled('load');
|
||||
$this->assertEqual(1, count($by_path_files), 'entity_load_multiple_by_properties() returned an array of the correct size.');
|
||||
$by_path_file = reset($by_path_files);
|
||||
$this->assertTrue($by_path_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
|
||||
$this->assertEqual($by_path_file->id(), $file->id(), 'Loading by filepath got the correct fid.', 'File');
|
||||
|
||||
// Load by fid.
|
||||
file_test_reset();
|
||||
$by_fid_files = File::loadMultiple(array($file->id()));
|
||||
$this->assertFileHooksCalled(array());
|
||||
$this->assertEqual(1, count($by_fid_files), '\Drupal\file\Entity\File::loadMultiple() returned an array of the correct size.');
|
||||
$by_fid_file = reset($by_fid_files);
|
||||
$this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
|
||||
$this->assertEqual($by_fid_file->getFileUri(), $file->getFileUri(), 'Loading by fid got the correct filepath.', 'File');
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a single file and ensure that the correct values are returned.
|
||||
*/
|
||||
public function testUuidValues() {
|
||||
// Create a new file entity from scratch so we know the values.
|
||||
$file = $this->createFile('druplicon.txt', NULL, 'public');
|
||||
$file->save();
|
||||
file_test_reset();
|
||||
|
||||
$by_uuid_file = \Drupal::entityManager()->loadEntityByUuid('file', $file->uuid());
|
||||
$this->assertFileHookCalled('load');
|
||||
$this->assertTrue(is_object($by_uuid_file), '\Drupal::entityManager()->loadEntityByUuid() returned a file object.');
|
||||
if (is_object($by_uuid_file)) {
|
||||
$this->assertEqual($by_uuid_file->id(), $file->id(), 'Loading by UUID got the same fid.', 'File');
|
||||
$this->assertTrue($by_uuid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
278
core/modules/file/tests/src/Kernel/Migrate/EntityFileTest.php
Normal file
278
core/modules/file/tests/src/Kernel/Migrate/EntityFileTest.php
Normal file
|
@ -0,0 +1,278 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Tests\file\Kernel\Migrate\EntityFileTest.
|
||||
*/
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Migrate;
|
||||
|
||||
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
|
||||
use Drupal\migrate\Row;
|
||||
use Drupal\file\Plugin\migrate\destination\EntityFile;
|
||||
use Drupal\Core\Entity\ContentEntityInterface;
|
||||
use Drupal\entity_test\Entity\EntityTest;
|
||||
use Drupal\migrate\MigrateException;
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
|
||||
/**
|
||||
* Tests the entity file destination plugin.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class EntityFileTest extends KernelTestBase {
|
||||
|
||||
/**
|
||||
* Modules to install.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system', 'entity_test', 'user', 'file');
|
||||
|
||||
/**
|
||||
* @var \Drupal\Tests\file\Kernel\Migrate\TestEntityFile $destination
|
||||
*/
|
||||
protected $destination;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
\Drupal::getContainer()->get('stream_wrapper_manager')->registerWrapper('public', 'Drupal\Core\StreamWrapper\PublicStream', StreamWrapperInterface::NORMAL);
|
||||
$this->destination = new TestEntityFile([]);
|
||||
$this->installEntitySchema('file');
|
||||
|
||||
file_put_contents('/tmp/test-file.jpg', '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test successful imports/copies.
|
||||
*/
|
||||
public function testSuccessfulCopies() {
|
||||
foreach ($this->localFileDataProvider() as $data) {
|
||||
list($row_values, $destination_path, $expected, $source_base_path) = $data;
|
||||
|
||||
$this->doImport($row_values, $destination_path, $source_base_path);
|
||||
$message = $expected ? sprintf('File %s exists', $destination_path) : sprintf('File %s does not exist', $destination_path);
|
||||
$this->assertIdentical($expected, is_file($destination_path), $message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The data provider for testing the file destination.
|
||||
*
|
||||
* @return array
|
||||
* An array of file permutations to test.
|
||||
*/
|
||||
protected function localFileDataProvider() {
|
||||
return [
|
||||
// Test a local to local copy.
|
||||
[['filepath' => 'core/modules/simpletest/files/image-test.jpg'], 'public://file1.jpg', TRUE, $this->root . '/'],
|
||||
// Test a temporary file using an absolute path.
|
||||
[['filepath' => '/tmp/test-file.jpg'], 'temporary://test.jpg', TRUE, ''],
|
||||
// Test a temporary file using a relative path.
|
||||
[['filepath' => 'test-file.jpg'], 'temporary://core/modules/simpletest/files/test.jpg', TRUE, '/tmp/'],
|
||||
// Test a remote path to local.
|
||||
[['filepath' => 'core/modules/simpletest/files/image-test.jpg'], 'public://remote-file.jpg', TRUE, $this->root . '/'],
|
||||
// Test a remote path to local inside a folder that doesn't exist.
|
||||
[['filepath' => 'core/modules/simpletest/files/image-test.jpg'], 'public://folder/remote-file.jpg', TRUE, $this->root . '/'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that non-existent files throw an exception.
|
||||
*/
|
||||
public function testNonExistentSourceFile() {
|
||||
$destination = '/non/existent/file';
|
||||
try {
|
||||
// If this test passes, doImport() will raise a MigrateException and
|
||||
// we'll never reach fail().
|
||||
$this->doImport(['filepath' => $destination], 'public://wontmatter.jpg');
|
||||
$this->fail('Expected Drupal\migrate\MigrateException when importing ' . $destination);
|
||||
}
|
||||
catch (MigrateException $e) {
|
||||
$this->assertIdentical($e->getMessage(), "File '$destination' does not exist.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests various invocations of the writeFile() method.
|
||||
*/
|
||||
public function testWriteFile() {
|
||||
$plugin = $this->destination;
|
||||
$method = new \ReflectionMethod($plugin, 'writeFile');
|
||||
$method->setAccessible(TRUE);
|
||||
|
||||
touch('temporary://baz.txt');
|
||||
|
||||
// Moving an actual file should return TRUE.
|
||||
$plugin->configuration['move'] = TRUE;
|
||||
$this->assertTrue($method->invoke($plugin, 'temporary://baz.txt', 'public://foo.txt'));
|
||||
|
||||
// Trying to move a non-existent file should return FALSE.
|
||||
$this->assertFalse($method->invoke($plugin, 'temporary://invalid.txt', 'public://invalid.txt'));
|
||||
|
||||
// Copying over a file that already exists should replace the existing file.
|
||||
$plugin->configuration['move'] = FALSE;
|
||||
touch('temporary://baz.txt');
|
||||
$this->assertTrue($method->invoke($plugin, 'temporary://baz.txt', 'public://foo.txt'));
|
||||
// Copying over a file that already exists should rename the resulting file
|
||||
// if FILE_EXISTS_RENAME is specified.
|
||||
$method->invoke($plugin, 'temporary://baz.txt', 'public://foo.txt', FILE_EXISTS_RENAME);
|
||||
$this->assertTrue(file_exists('public://foo_0.txt'));
|
||||
|
||||
// Trying to copy a non-existent file should return FALSE.
|
||||
$this->assertFalse($method->invoke($plugin, 'temporary://invalid.txt', 'public://invalid.txt'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests various invocations of the getOverwriteMode() method.
|
||||
*/
|
||||
public function testGetOverwriteMode() {
|
||||
$plugin = $this->destination;
|
||||
$method = new \ReflectionMethod($plugin, 'getOverwriteMode');
|
||||
$method->setAccessible(TRUE);
|
||||
|
||||
$row = new Row([], []);
|
||||
// If the plugin is not configured to rename the destination file, we should
|
||||
// always get FILE_EXISTS_REPLACE.
|
||||
$this->assertIdentical(FILE_EXISTS_REPLACE, $method->invoke($plugin, $row));
|
||||
|
||||
// When the plugin IS configured to rename the destination file, it should
|
||||
// return FILE_EXISTS_RENAME if the destination entity already exists,
|
||||
// and FILE_EXISTS_REPLACE otherwise.
|
||||
$plugin->configuration['rename'] = TRUE;
|
||||
$plugin->storage = \Drupal::entityManager()->getStorage('file');
|
||||
/** @var \Drupal\file\FileInterface $file */
|
||||
$file = $plugin->storage->create();
|
||||
touch('public://foo.txt');
|
||||
$file->setFileUri('public://foo.txt');
|
||||
$file->save();
|
||||
$row->setDestinationProperty($plugin->storage->getEntityType()->getKey('id'), $file->id());
|
||||
$this->assertIdentical(FILE_EXISTS_RENAME, $method->invoke($plugin, $row));
|
||||
unlink('public://foo.txt');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests various invocations of the getDirectory() method.
|
||||
*/
|
||||
public function testGetDirectory() {
|
||||
$plugin = $this->destination;
|
||||
$method = new \ReflectionMethod($plugin, 'getDirectory');
|
||||
$method->setAccessible(TRUE);
|
||||
|
||||
$this->assertSame('public://foo', $method->invoke($plugin, 'public://foo/baz.txt'));
|
||||
$this->assertSame('/path/to', $method->invoke($plugin, '/path/to/foo.txt'));
|
||||
// A directory like public:// (no path) needs to resolve to a physical path.
|
||||
$fs = \Drupal::getContainer()->get('file_system');
|
||||
$this->assertSame($fs->realpath('public://'), $method->invoke($plugin, 'public://foo.txt'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests various invocations of the isLocationUnchanged() method.
|
||||
*/
|
||||
public function testIsLocationUnchanged() {
|
||||
$plugin = $this->destination;
|
||||
$method = new \ReflectionMethod($plugin, 'isLocationUnchanged');
|
||||
$method->setAccessible(TRUE);
|
||||
|
||||
$temporary_file = '/tmp/foo.txt';
|
||||
touch($temporary_file);
|
||||
$this->assertTrue($method->invoke($plugin, $temporary_file, 'temporary://foo.txt'));
|
||||
unlink($temporary_file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests various invocations of the isLocalUri() method.
|
||||
*/
|
||||
public function testIsLocalUri() {
|
||||
$plugin = $this->destination;
|
||||
$method = new \ReflectionMethod($plugin, 'isLocalUri');
|
||||
$method->setAccessible(TRUE);
|
||||
|
||||
$this->assertTrue($method->invoke($plugin, 'public://foo.txt'));
|
||||
$this->assertTrue($method->invoke($plugin, 'public://path/to/foo.txt'));
|
||||
$this->assertTrue($method->invoke($plugin, 'temporary://foo.txt'));
|
||||
$this->assertTrue($method->invoke($plugin, 'temporary://path/to/foo.txt'));
|
||||
$this->assertTrue($method->invoke($plugin, 'foo.txt'));
|
||||
$this->assertTrue($method->invoke($plugin, '/path/to/files/foo.txt'));
|
||||
$this->assertTrue($method->invoke($plugin, 'relative/path/to/foo.txt'));
|
||||
$this->assertFalse($method->invoke($plugin, 'http://www.example.com/foo.txt'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Do an import using the destination.
|
||||
*
|
||||
* @param array $row_values
|
||||
* An array of row values.
|
||||
* @param string $destination_path
|
||||
* The destination path to copy to.
|
||||
* @param string $source_base_path
|
||||
* The source base path.
|
||||
* @return array
|
||||
* An array of saved entities ids.
|
||||
*
|
||||
* @throws \Drupal\migrate\MigrateException
|
||||
*/
|
||||
protected function doImport($row_values, $destination_path, $source_base_path = '') {
|
||||
$row = new Row($row_values, []);
|
||||
$row->setDestinationProperty('uri', $destination_path);
|
||||
$this->destination->configuration['source_base_path'] = $source_base_path;
|
||||
|
||||
// Importing asserts there are no errors, then we just check the file has
|
||||
// been copied into place.
|
||||
return $this->destination->import($row, array());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class TestEntityFile extends EntityFile {
|
||||
|
||||
/**
|
||||
* This is needed to be passed to $this->save().
|
||||
*
|
||||
* @var \Drupal\Core\Entity\ContentEntityInterface
|
||||
*/
|
||||
public $mockEntity;
|
||||
|
||||
/**
|
||||
* Make this public for easy writing during tests.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $configuration;
|
||||
|
||||
/**
|
||||
* @var \Drupal\Core\Entity\EntityStorageInterface
|
||||
*/
|
||||
public $storage;
|
||||
|
||||
public function __construct($configuration = []) {
|
||||
$configuration += array(
|
||||
'source_base_path' => '',
|
||||
'source_path_property' => 'filepath',
|
||||
'destination_path_property' => 'uri',
|
||||
'move' => FALSE,
|
||||
'urlencode' => FALSE,
|
||||
);
|
||||
$this->configuration = $configuration;
|
||||
// We need a mock entity to be passed to save to prevent strict exceptions.
|
||||
$this->mockEntity = EntityTest::create();
|
||||
$this->streamWrapperManager = \Drupal::getContainer()->get('stream_wrapper_manager');
|
||||
$this->fileSystem = \Drupal::getContainer()->get('file_system');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function getEntity(Row $row, array $old_destination_id_values) {
|
||||
return $this->mockEntity;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function save(ContentEntityInterface $entity, array $old_destination_id_values = array()) {}
|
||||
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Migrate;
|
||||
|
||||
use Drupal\Tests\migrate_drupal\Kernel\MigrateDrupalTestBase;
|
||||
use Drupal\migrate_drupal\Tests\StubTestTrait;
|
||||
|
||||
/**
|
||||
* Test stub creation for file entities.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class MigrateFileStubTest extends MigrateDrupalTestBase {
|
||||
|
||||
use StubTestTrait;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = ['file'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->installEntitySchema('file');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests creation of file stubs.
|
||||
*/
|
||||
public function testStub() {
|
||||
$this->performStubTest('file');
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Migrate\d6;
|
||||
|
||||
/**
|
||||
* Helper for setting up a file migration test.
|
||||
*/
|
||||
trait FileMigrationTestTrait {
|
||||
|
||||
/**
|
||||
* Setup and execute d6_file migration.
|
||||
*/
|
||||
protected function setUpMigratedFiles() {
|
||||
$this->installEntitySchema('file');
|
||||
$this->installConfig(['file']);
|
||||
|
||||
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
|
||||
$migration_plugin_manager = $this->container->get('plugin.manager.migration');
|
||||
|
||||
/** @var \Drupal\migrate\Plugin\migration $migration */
|
||||
$migration = $migration_plugin_manager->createInstance('d6_file');
|
||||
$source = $migration->getSourceConfiguration();
|
||||
$source['site_path'] = 'core/modules/simpletest';
|
||||
$migration->set('source', $source);
|
||||
$this->executeMigration($migration);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Migrate\d6;
|
||||
|
||||
use Drupal\config\Tests\SchemaCheckTestTrait;
|
||||
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
|
||||
|
||||
/**
|
||||
* Upgrade variables to file.settings.yml.
|
||||
*
|
||||
* @group migrate_drupal_6
|
||||
*/
|
||||
class MigrateFileConfigsTest extends MigrateDrupal6TestBase {
|
||||
|
||||
use SchemaCheckTestTrait;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->executeMigration('d6_file_settings');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests migration of file variables to file.settings.yml.
|
||||
*/
|
||||
public function testFileSettings() {
|
||||
$config = $this->config('file.settings');
|
||||
$this->assertIdentical('textfield', $config->get('description.type'));
|
||||
$this->assertIdentical(128, $config->get('description.length'));
|
||||
$this->assertIdentical('sites/default/files/icons', $config->get('icon.directory'));
|
||||
$this->assertConfigSchema(\Drupal::service('config.typed'), 'file.settings', $config->get());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,148 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Migrate\d6;
|
||||
|
||||
use Drupal\Component\Utility\Random;
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\file\FileInterface;
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
use Drupal\Core\Database\Database;
|
||||
use Drupal\Tests\migrate\Kernel\MigrateDumpAlterInterface;
|
||||
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
|
||||
|
||||
/**
|
||||
* file migration.
|
||||
*
|
||||
* @group migrate_drupal_6
|
||||
*/
|
||||
class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlterInterface {
|
||||
|
||||
use FileMigrationTestTrait;
|
||||
|
||||
/**
|
||||
* The filename of a file used to test temporary file migration.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected static $tempFilename;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->setUpMigratedFiles();
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts a file entity.
|
||||
*
|
||||
* @param int $fid
|
||||
* The file ID.
|
||||
* @param string $name
|
||||
* The expected file name.
|
||||
* @param int $size
|
||||
* The expected file size.
|
||||
* @param string $uri
|
||||
* The expected file URI.
|
||||
* @param string $type
|
||||
* The expected MIME type.
|
||||
* @param int $uid
|
||||
* The expected file owner ID.
|
||||
*/
|
||||
protected function assertEntity($fid, $name, $size, $uri, $type, $uid) {
|
||||
/** @var \Drupal\file\FileInterface $file */
|
||||
$file = File::load($fid);
|
||||
$this->assertTrue($file instanceof FileInterface);
|
||||
$this->assertIdentical($name, $file->getFilename());
|
||||
$this->assertIdentical($size, $file->getSize());
|
||||
$this->assertIdentical($uri, $file->getFileUri());
|
||||
$this->assertIdentical($type, $file->getMimeType());
|
||||
$this->assertIdentical($uid, $file->getOwnerId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the Drupal 6 files to Drupal 8 migration.
|
||||
*/
|
||||
public function testFiles() {
|
||||
$this->assertEntity(1, 'Image1.png', '39325', 'public://image-1.png', 'image/png', '1');
|
||||
$this->assertEntity(2, 'Image2.jpg', '1831', 'public://image-2.jpg', 'image/jpeg', '1');
|
||||
$this->assertEntity(3, 'Image-test.gif', '183', 'public://image-test.gif', 'image/jpeg', '1');
|
||||
$this->assertEntity(5, 'html-1.txt', '24', 'public://html-1.txt', 'text/plain', '1');
|
||||
|
||||
// Test that we can re-import and also test with file_directory_path set.
|
||||
$migration_plugin_manager = $this->container->get('plugin.manager.migration');
|
||||
\Drupal::database()
|
||||
->truncate($migration_plugin_manager->createInstance('d6_file')->getIdMap()->mapTableName())
|
||||
->execute();
|
||||
|
||||
// Update the file_directory_path.
|
||||
Database::getConnection('default', 'migrate')
|
||||
->update('variable')
|
||||
->fields(array('value' => serialize('files/test')))
|
||||
->condition('name', 'file_directory_path')
|
||||
->execute();
|
||||
Database::getConnection('default', 'migrate')
|
||||
->update('variable')
|
||||
->fields(array('value' => serialize(file_directory_temp())))
|
||||
->condition('name', 'file_directory_temp')
|
||||
->execute();
|
||||
|
||||
$migration = $migration_plugin_manager->createInstance('d6_file');
|
||||
$this->executeMigration($migration);
|
||||
|
||||
$file = File::load(2);
|
||||
$this->assertIdentical('public://core/modules/simpletest/files/image-2.jpg', $file->getFileUri());
|
||||
|
||||
// Ensure that a temporary file has been migrated.
|
||||
$file = File::load(6);
|
||||
$this->assertIdentical('temporary://' . static::getUniqueFilename(), $file->getFileUri());
|
||||
|
||||
// File 7, created in static::migrateDumpAlter(), shares a path with
|
||||
// file 5, which means it should be skipped entirely.
|
||||
$this->assertNull(File::load(7));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* A filename based upon the test.
|
||||
*/
|
||||
public static function getUniqueFilename() {
|
||||
return static::$tempFilename;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function migrateDumpAlter(KernelTestBase $test) {
|
||||
// Creates a random filename and updates the source database.
|
||||
$random = new Random();
|
||||
$temp_directory = file_directory_temp();
|
||||
file_prepare_directory($temp_directory, FILE_CREATE_DIRECTORY);
|
||||
static::$tempFilename = $test->getDatabasePrefix() . $random->name() . '.jpg';
|
||||
$file_path = $temp_directory . '/' . static::$tempFilename;
|
||||
file_put_contents($file_path, '');
|
||||
|
||||
$db = Database::getConnection('default', 'migrate');
|
||||
|
||||
$db->update('files')
|
||||
->condition('fid', 6)
|
||||
->fields(array(
|
||||
'filename' => static::$tempFilename,
|
||||
'filepath' => $file_path,
|
||||
))
|
||||
->execute();
|
||||
|
||||
$file = (array) $db->select('files')
|
||||
->fields('files')
|
||||
->condition('fid', 5)
|
||||
->execute()
|
||||
->fetchObject();
|
||||
unset($file['fid']);
|
||||
$db->insert('files')->fields($file)->execute();
|
||||
|
||||
return static::$tempFilename;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Migrate\d6;
|
||||
|
||||
use Drupal\Core\Entity\Entity\EntityViewDisplay;
|
||||
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
|
||||
|
||||
/**
|
||||
* Upload entity display.
|
||||
*
|
||||
* @group migrate_drupal_6
|
||||
*/
|
||||
class MigrateUploadEntityDisplayTest extends MigrateDrupal6TestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->migrateFields();
|
||||
$this->executeMigration('d6_upload_entity_display');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the Drupal 6 upload settings to Drupal 8 entity display migration.
|
||||
*/
|
||||
public function testUploadEntityDisplay() {
|
||||
$display = EntityViewDisplay::load('node.page.default');
|
||||
$component = $display->getComponent('upload');
|
||||
$this->assertIdentical('file_default', $component['type']);
|
||||
|
||||
$display = EntityViewDisplay::load('node.story.default');
|
||||
$component = $display->getComponent('upload');
|
||||
$this->assertIdentical('file_default', $component['type']);
|
||||
|
||||
// Assure this doesn't exist.
|
||||
$display = EntityViewDisplay::load('node.article.default');
|
||||
$component = $display->getComponent('upload');
|
||||
$this->assertTrue(is_null($component));
|
||||
|
||||
$this->assertIdentical(array('node', 'page', 'default', 'upload'), $this->getMigration('d6_upload_entity_display')->getIdMap()->lookupDestinationID(array('page')));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Migrate\d6;
|
||||
|
||||
use Drupal\Core\Entity\Entity\EntityFormDisplay;
|
||||
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
|
||||
|
||||
/**
|
||||
* Upload form entity display.
|
||||
*
|
||||
* @group migrate_drupal_6
|
||||
*/
|
||||
class MigrateUploadEntityFormDisplayTest extends MigrateDrupal6TestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->migrateFields();
|
||||
$this->executeMigration('d6_upload_entity_form_display');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the Drupal 6 upload settings to Drupal 8 entity form display migration.
|
||||
*/
|
||||
public function testUploadEntityFormDisplay() {
|
||||
$display = EntityFormDisplay::load('node.page.default');
|
||||
$component = $display->getComponent('upload');
|
||||
$this->assertIdentical('file_generic', $component['type']);
|
||||
|
||||
$display = EntityFormDisplay::load('node.story.default');
|
||||
$component = $display->getComponent('upload');
|
||||
$this->assertIdentical('file_generic', $component['type']);
|
||||
|
||||
// Assure this doesn't exist.
|
||||
$display = EntityFormDisplay::load('node.article.default');
|
||||
$component = $display->getComponent('upload');
|
||||
$this->assertTrue(is_null($component));
|
||||
|
||||
$this->assertIdentical(array('node', 'page', 'default', 'upload'), $this->getMigration('d6_upload_entity_form_display')->getIdMap()->lookupDestinationID(array('page')));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Migrate\d6;
|
||||
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
|
||||
|
||||
/**
|
||||
* Uploads migration.
|
||||
*
|
||||
* @group migrate_drupal_6
|
||||
*/
|
||||
class MigrateUploadFieldTest extends MigrateDrupal6TestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->migrateFields();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the Drupal 6 upload settings to Drupal 8 field migration.
|
||||
*/
|
||||
public function testUpload() {
|
||||
$field_storage = FieldStorageConfig::load('node.upload');
|
||||
$this->assertIdentical('node.upload', $field_storage->id());
|
||||
$this->assertIdentical(array('node', 'upload'), $this->getMigration('d6_upload_field')->getIdMap()->lookupDestinationID(array('')));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Migrate\d6;
|
||||
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
|
||||
|
||||
/**
|
||||
* Upload field instance migration.
|
||||
*
|
||||
* @group migrate_drupal_6
|
||||
*/
|
||||
class MigrateUploadInstanceTest extends MigrateDrupal6TestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->migrateFields();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the Drupal 6 upload settings to Drupal 8 field instance migration.
|
||||
*/
|
||||
public function testUploadFieldInstance() {
|
||||
$field = FieldConfig::load('node.page.upload');
|
||||
$settings = $field->getSettings();
|
||||
$this->assertIdentical('node.page.upload', $field->id());
|
||||
$this->assertIdentical('jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp', $settings['file_extensions']);
|
||||
$this->assertIdentical('1MB', $settings['max_filesize']);
|
||||
$this->assertIdentical(TRUE, $settings['description_field']);
|
||||
|
||||
$field = FieldConfig::load('node.story.upload');
|
||||
$this->assertIdentical('node.story.upload', $field->id());
|
||||
|
||||
// Shouldn't exist.
|
||||
$field = FieldConfig::load('node.article.upload');
|
||||
$this->assertTrue(is_null($field));
|
||||
|
||||
$this->assertIdentical(array('node', 'page', 'upload'), $this->getMigration('d6_upload_field_instance')->getIdMap()->lookupDestinationID(array('page')));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,82 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Migrate\d6;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
|
||||
use Drupal\node\Entity\Node;
|
||||
|
||||
/**
|
||||
* Migrate association data between nodes and files.
|
||||
*
|
||||
* @group migrate_drupal_6
|
||||
*/
|
||||
class MigrateUploadTest extends MigrateDrupal6TestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->installEntitySchema('file');
|
||||
$this->installEntitySchema('node');
|
||||
$this->installSchema('file', ['file_usage']);
|
||||
$this->installSchema('node', ['node_access']);
|
||||
|
||||
$id_mappings = array('d6_file' => array());
|
||||
// Create new file entities.
|
||||
for ($i = 1; $i <= 3; $i++) {
|
||||
$file = File::create(array(
|
||||
'fid' => $i,
|
||||
'uid' => 1,
|
||||
'filename' => 'druplicon.txt',
|
||||
'uri' => "public://druplicon-$i.txt",
|
||||
'filemime' => 'text/plain',
|
||||
'created' => 1,
|
||||
'changed' => 1,
|
||||
'status' => FILE_STATUS_PERMANENT,
|
||||
));
|
||||
$file->enforceIsNew();
|
||||
file_put_contents($file->getFileUri(), 'hello world');
|
||||
|
||||
// Save it, inserting a new record.
|
||||
$file->save();
|
||||
$id_mappings['d6_file'][] = array(array($i), array($i));
|
||||
}
|
||||
$this->prepareMigrations($id_mappings);
|
||||
|
||||
$this->migrateContent();
|
||||
// Since we are only testing a subset of the file migration, do not check
|
||||
// that the full file migration has been run.
|
||||
$migration = $this->getMigration('d6_upload');
|
||||
$migration->set('requirements', []);
|
||||
$this->executeMigration($migration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test upload migration from Drupal 6 to Drupal 8.
|
||||
*/
|
||||
function testUpload() {
|
||||
$this->container->get('entity.manager')
|
||||
->getStorage('node')
|
||||
->resetCache([1, 2]);
|
||||
|
||||
$nodes = Node::loadMultiple([1, 2]);
|
||||
$node = $nodes[1];
|
||||
$this->assertIdentical(1, count($node->upload));
|
||||
$this->assertIdentical('1', $node->upload[0]->target_id);
|
||||
$this->assertIdentical('file 1-1-1', $node->upload[0]->description);
|
||||
$this->assertIdentical(FALSE, $node->upload[0]->isDisplayed());
|
||||
|
||||
$node = $nodes[2];
|
||||
$this->assertIdentical(2, count($node->upload));
|
||||
$this->assertIdentical('3', $node->upload[0]->target_id);
|
||||
$this->assertIdentical('file 2-3-3', $node->upload[0]->description);
|
||||
$this->assertIdentical(FALSE, $node->upload[0]->isDisplayed());
|
||||
$this->assertIdentical('2', $node->upload[1]->target_id);
|
||||
$this->assertIdentical(TRUE, $node->upload[1]->isDisplayed());
|
||||
$this->assertIdentical('file 2-3-2', $node->upload[1]->description);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,93 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Migrate\d7;
|
||||
|
||||
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\file\FileInterface;
|
||||
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
|
||||
|
||||
/**
|
||||
* Migrates all files in the file_managed table.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class MigrateFileTest extends MigrateDrupal7TestBase {
|
||||
|
||||
static $modules = ['file'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->installEntitySchema('file');
|
||||
$this->container->get('stream_wrapper_manager')->registerWrapper('public', 'Drupal\Core\StreamWrapper\PublicStream', StreamWrapperInterface::NORMAL);
|
||||
|
||||
$fs = \Drupal::service('file_system');
|
||||
// The public file directory active during the test will serve as the
|
||||
// root of the fictional Drupal 7 site we're migrating.
|
||||
$fs->mkdir('public://sites/default/files', NULL, TRUE);
|
||||
file_put_contents('public://sites/default/files/cube.jpeg', str_repeat('*', 3620));
|
||||
|
||||
/** @var \Drupal\migrate\Plugin\Migration $migration */
|
||||
$migration = $this->getMigration('d7_file');
|
||||
// Set the destination plugin's source_base_path configuration value, which
|
||||
// would normally be set by the user running the migration.
|
||||
$migration->set('destination', [
|
||||
'plugin' => 'entity:file',
|
||||
// Note that source_base_path must include a trailing slash because it's
|
||||
// prepended directly to the value of the source path property.
|
||||
'source_base_path' => $fs->realpath('public://') . '/',
|
||||
// This is set in the migration's YAML file, but we need to repeat it
|
||||
// here because all the destination configuration must be set at once.
|
||||
'source_path_property' => 'filepath',
|
||||
]);
|
||||
$this->executeMigration($migration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests a single file entity.
|
||||
*
|
||||
* @param int $id
|
||||
* The file ID.
|
||||
* @param string $name
|
||||
* The expected file name.
|
||||
* @param string $uri
|
||||
* The expected URI.
|
||||
* @param string $mime
|
||||
* The expected MIME type.
|
||||
* @param int $size
|
||||
* The expected file size.
|
||||
* @param int $created
|
||||
* The expected creation time.
|
||||
* @param int $changed
|
||||
* The expected modification time.
|
||||
* @param int $uid
|
||||
* The expected owner ID.
|
||||
*/
|
||||
protected function assertEntity($id, $name, $uri, $mime, $size, $created, $changed, $uid) {
|
||||
/** @var \Drupal\file\FileInterface $file */
|
||||
$file = File::load($id);
|
||||
$this->assertTrue($file instanceof FileInterface);
|
||||
$this->assertIdentical($name, $file->getFilename());
|
||||
$this->assertIdentical($uri, $file->getFileUri());
|
||||
$this->assertTrue(file_exists($uri));
|
||||
$this->assertIdentical($mime, $file->getMimeType());
|
||||
$this->assertIdentical($size, $file->getSize());
|
||||
// isPermanent(), isTemporary(), etc. are determined by the status column.
|
||||
$this->assertTrue($file->isPermanent());
|
||||
$this->assertIdentical($created, $file->getCreatedTime());
|
||||
$this->assertIdentical($changed, $file->getChangedTime());
|
||||
$this->assertIdentical($uid, $file->getOwnerId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that all expected files are migrated.
|
||||
*/
|
||||
public function testFileMigration() {
|
||||
$this->assertEntity(1, 'cube.jpeg', 'public://cube.jpeg', 'image/jpeg', '3620', '1421727515', '1421727515', '1');
|
||||
}
|
||||
|
||||
}
|
159
core/modules/file/tests/src/Kernel/MoveTest.php
Normal file
159
core/modules/file/tests/src/Kernel/MoveTest.php
Normal file
|
@ -0,0 +1,159 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests the file move function.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class MoveTest extends FileManagedUnitTestBase {
|
||||
/**
|
||||
* Move a normal file.
|
||||
*/
|
||||
function testNormal() {
|
||||
$contents = $this->randomMachineName(10);
|
||||
$source = $this->createFile(NULL, $contents);
|
||||
$desired_filepath = 'public://' . $this->randomMachineName();
|
||||
|
||||
// Clone the object so we don't have to worry about the function changing
|
||||
// our reference copy.
|
||||
$result = file_move(clone $source, $desired_filepath, FILE_EXISTS_ERROR);
|
||||
|
||||
// Check the return status and that the contents changed.
|
||||
$this->assertTrue($result, 'File moved successfully.');
|
||||
$this->assertFalse(file_exists($source->getFileUri()));
|
||||
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of file correctly written.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('move', 'load', 'update'));
|
||||
|
||||
// Make sure we got the same file back.
|
||||
$this->assertEqual($source->id(), $result->id(), format_string("Source file id's' %fid is unchanged after move.", array('%fid' => $source->id())));
|
||||
|
||||
// Reload the file from the database and check that the changes were
|
||||
// actually saved.
|
||||
$loaded_file = File::load($result->id());
|
||||
$this->assertTrue($loaded_file, 'File can be loaded from the database.');
|
||||
$this->assertFileUnchanged($result, $loaded_file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test renaming when moving onto a file that already exists.
|
||||
*/
|
||||
function testExistingRename() {
|
||||
// Setup a file to overwrite.
|
||||
$contents = $this->randomMachineName(10);
|
||||
$source = $this->createFile(NULL, $contents);
|
||||
$target = $this->createFile();
|
||||
$this->assertDifferentFile($source, $target);
|
||||
|
||||
// Clone the object so we don't have to worry about the function changing
|
||||
// our reference copy.
|
||||
$result = file_move(clone $source, $target->getFileUri(), FILE_EXISTS_RENAME);
|
||||
|
||||
// Check the return status and that the contents changed.
|
||||
$this->assertTrue($result, 'File moved successfully.');
|
||||
$this->assertFalse(file_exists($source->getFileUri()));
|
||||
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of file correctly written.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('move', 'load', 'update'));
|
||||
|
||||
// Compare the returned value to what made it into the database.
|
||||
$this->assertFileUnchanged($result, File::load($result->id()));
|
||||
// The target file should not have been altered.
|
||||
$this->assertFileUnchanged($target, File::load($target->id()));
|
||||
// Make sure we end up with two distinct files afterwards.
|
||||
$this->assertDifferentFile($target, $result);
|
||||
|
||||
// Compare the source and results.
|
||||
$loaded_source = File::load($source->id());
|
||||
$this->assertEqual($loaded_source->id(), $result->id(), "Returned file's id matches the source.");
|
||||
$this->assertNotEqual($loaded_source->getFileUri(), $source->getFileUri(), 'Returned file path has changed from the original.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test replacement when moving onto a file that already exists.
|
||||
*/
|
||||
function testExistingReplace() {
|
||||
// Setup a file to overwrite.
|
||||
$contents = $this->randomMachineName(10);
|
||||
$source = $this->createFile(NULL, $contents);
|
||||
$target = $this->createFile();
|
||||
$this->assertDifferentFile($source, $target);
|
||||
|
||||
// Clone the object so we don't have to worry about the function changing
|
||||
// our reference copy.
|
||||
$result = file_move(clone $source, $target->getFileUri(), FILE_EXISTS_REPLACE);
|
||||
|
||||
// Look at the results.
|
||||
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of file were overwritten.');
|
||||
$this->assertFalse(file_exists($source->getFileUri()));
|
||||
$this->assertTrue($result, 'File moved successfully.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('move', 'update', 'delete', 'load'));
|
||||
|
||||
// Reload the file from the database and check that the changes were
|
||||
// actually saved.
|
||||
$loaded_result = File::load($result->id());
|
||||
$this->assertFileUnchanged($result, $loaded_result);
|
||||
// Check that target was re-used.
|
||||
$this->assertSameFile($target, $loaded_result);
|
||||
// Source and result should be totally different.
|
||||
$this->assertDifferentFile($source, $loaded_result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test replacement when moving onto itself.
|
||||
*/
|
||||
function testExistingReplaceSelf() {
|
||||
// Setup a file to overwrite.
|
||||
$contents = $this->randomMachineName(10);
|
||||
$source = $this->createFile(NULL, $contents);
|
||||
|
||||
// Copy the file over itself. Clone the object so we don't have to worry
|
||||
// about the function changing our reference copy.
|
||||
$result = file_move(clone $source, $source->getFileUri(), FILE_EXISTS_REPLACE);
|
||||
$this->assertFalse($result, 'File move failed.');
|
||||
$this->assertEqual($contents, file_get_contents($source->getFileUri()), 'Contents of file were not altered.');
|
||||
|
||||
// Check that no hooks were called while failing.
|
||||
$this->assertFileHooksCalled(array());
|
||||
|
||||
// Load the file from the database and make sure it is identical to what
|
||||
// was returned.
|
||||
$this->assertFileUnchanged($source, File::load($source->id()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that moving onto an existing file fails when FILE_EXISTS_ERROR is
|
||||
* specified.
|
||||
*/
|
||||
function testExistingError() {
|
||||
$contents = $this->randomMachineName(10);
|
||||
$source = $this->createFile();
|
||||
$target = $this->createFile(NULL, $contents);
|
||||
$this->assertDifferentFile($source, $target);
|
||||
|
||||
// Clone the object so we don't have to worry about the function changing
|
||||
// our reference copy.
|
||||
$result = file_move(clone $source, $target->getFileUri(), FILE_EXISTS_ERROR);
|
||||
|
||||
// Check the return status and that the contents did not change.
|
||||
$this->assertFalse($result, 'File move failed.');
|
||||
$this->assertTrue(file_exists($source->getFileUri()));
|
||||
$this->assertEqual($contents, file_get_contents($target->getFileUri()), 'Contents of file were not altered.');
|
||||
|
||||
// Check that no hooks were called while failing.
|
||||
$this->assertFileHooksCalled(array());
|
||||
|
||||
// Load the file from the database and make sure it is identical to what
|
||||
// was returned.
|
||||
$this->assertFileUnchanged($source, File::load($source->id()));
|
||||
$this->assertFileUnchanged($target, File::load($target->id()));
|
||||
}
|
||||
}
|
133
core/modules/file/tests/src/Kernel/SaveDataTest.php
Normal file
133
core/modules/file/tests/src/Kernel/SaveDataTest.php
Normal file
|
@ -0,0 +1,133 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests the file_save_data() function.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class SaveDataTest extends FileManagedUnitTestBase {
|
||||
/**
|
||||
* Test the file_save_data() function when no filename is provided.
|
||||
*/
|
||||
function testWithoutFilename() {
|
||||
$contents = $this->randomMachineName(8);
|
||||
|
||||
$result = file_save_data($contents);
|
||||
$this->assertTrue($result, 'Unnamed file saved correctly.');
|
||||
|
||||
$this->assertEqual(file_default_scheme(), file_uri_scheme($result->getFileUri()), "File was placed in Drupal's files directory.");
|
||||
$this->assertEqual($result->getFilename(), drupal_basename($result->getFileUri()), "Filename was set to the file's basename.");
|
||||
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of the file are correct.');
|
||||
$this->assertEqual($result->getMimeType(), 'application/octet-stream', 'A MIME type was set.');
|
||||
$this->assertTrue($result->isPermanent(), "The file's status was set to permanent.");
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('insert'));
|
||||
|
||||
// Verify that what was returned is what's in the database.
|
||||
$this->assertFileUnchanged($result, File::load($result->id()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the file_save_data() function when a filename is provided.
|
||||
*/
|
||||
function testWithFilename() {
|
||||
$contents = $this->randomMachineName(8);
|
||||
|
||||
// Using filename with non-latin characters.
|
||||
$filename = 'Текстовый файл.txt';
|
||||
|
||||
$result = file_save_data($contents, 'public://' . $filename);
|
||||
$this->assertTrue($result, 'Unnamed file saved correctly.');
|
||||
|
||||
$this->assertEqual('public', file_uri_scheme($result->getFileUri()), "File was placed in Drupal's files directory.");
|
||||
$this->assertEqual($filename, drupal_basename($result->getFileUri()), 'File was named correctly.');
|
||||
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of the file are correct.');
|
||||
$this->assertEqual($result->getMimeType(), 'text/plain', 'A MIME type was set.');
|
||||
$this->assertTrue($result->isPermanent(), "The file's status was set to permanent.");
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('insert'));
|
||||
|
||||
// Verify that what was returned is what's in the database.
|
||||
$this->assertFileUnchanged($result, File::load($result->id()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test file_save_data() when renaming around an existing file.
|
||||
*/
|
||||
function testExistingRename() {
|
||||
// Setup a file to overwrite.
|
||||
$existing = $this->createFile();
|
||||
$contents = $this->randomMachineName(8);
|
||||
|
||||
$result = file_save_data($contents, $existing->getFileUri(), FILE_EXISTS_RENAME);
|
||||
$this->assertTrue($result, 'File saved successfully.');
|
||||
|
||||
$this->assertEqual('public', file_uri_scheme($result->getFileUri()), "File was placed in Drupal's files directory.");
|
||||
$this->assertEqual($result->getFilename(), $existing->getFilename(), 'Filename was set to the basename of the source, rather than that of the renamed file.');
|
||||
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of the file are correct.');
|
||||
$this->assertEqual($result->getMimeType(), 'application/octet-stream', 'A MIME type was set.');
|
||||
$this->assertTrue($result->isPermanent(), "The file's status was set to permanent.");
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('insert'));
|
||||
|
||||
// Ensure that the existing file wasn't overwritten.
|
||||
$this->assertDifferentFile($existing, $result);
|
||||
$this->assertFileUnchanged($existing, File::load($existing->id()));
|
||||
|
||||
// Verify that was returned is what's in the database.
|
||||
$this->assertFileUnchanged($result, File::load($result->id()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test file_save_data() when replacing an existing file.
|
||||
*/
|
||||
function testExistingReplace() {
|
||||
// Setup a file to overwrite.
|
||||
$existing = $this->createFile();
|
||||
$contents = $this->randomMachineName(8);
|
||||
|
||||
$result = file_save_data($contents, $existing->getFileUri(), FILE_EXISTS_REPLACE);
|
||||
$this->assertTrue($result, 'File saved successfully.');
|
||||
|
||||
$this->assertEqual('public', file_uri_scheme($result->getFileUri()), "File was placed in Drupal's files directory.");
|
||||
$this->assertEqual($result->getFilename(), $existing->getFilename(), 'Filename was set to the basename of the existing file, rather than preserving the original name.');
|
||||
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of the file are correct.');
|
||||
$this->assertEqual($result->getMimeType(), 'application/octet-stream', 'A MIME type was set.');
|
||||
$this->assertTrue($result->isPermanent(), "The file's status was set to permanent.");
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('load', 'update'));
|
||||
|
||||
// Verify that the existing file was re-used.
|
||||
$this->assertSameFile($existing, $result);
|
||||
|
||||
// Verify that what was returned is what's in the database.
|
||||
$this->assertFileUnchanged($result, File::load($result->id()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that file_save_data() fails overwriting an existing file.
|
||||
*/
|
||||
function testExistingError() {
|
||||
$contents = $this->randomMachineName(8);
|
||||
$existing = $this->createFile(NULL, $contents);
|
||||
|
||||
// Check the overwrite error.
|
||||
$result = file_save_data('asdf', $existing->getFileUri(), FILE_EXISTS_ERROR);
|
||||
$this->assertFalse($result, 'Overwriting a file fails when FILE_EXISTS_ERROR is specified.');
|
||||
$this->assertEqual($contents, file_get_contents($existing->getFileUri()), 'Contents of existing file were unchanged.');
|
||||
|
||||
// Check that no hooks were called while failing.
|
||||
$this->assertFileHooksCalled(array());
|
||||
|
||||
// Ensure that the existing file wasn't overwritten.
|
||||
$this->assertFileUnchanged($existing, File::load($existing->id()));
|
||||
}
|
||||
}
|
85
core/modules/file/tests/src/Kernel/SaveTest.php
Normal file
85
core/modules/file/tests/src/Kernel/SaveTest.php
Normal file
|
@ -0,0 +1,85 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* File saving tests.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class SaveTest extends FileManagedUnitTestBase {
|
||||
function testFileSave() {
|
||||
// Create a new file entity.
|
||||
$file = File::create(array(
|
||||
'uid' => 1,
|
||||
'filename' => 'druplicon.txt',
|
||||
'uri' => 'public://druplicon.txt',
|
||||
'filemime' => 'text/plain',
|
||||
'status' => FILE_STATUS_PERMANENT,
|
||||
));
|
||||
file_put_contents($file->getFileUri(), 'hello world');
|
||||
|
||||
// Save it, inserting a new record.
|
||||
$file->save();
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('insert'));
|
||||
|
||||
$this->assertTrue($file->id() > 0, 'A new file ID is set when saving a new file to the database.', 'File');
|
||||
$loaded_file = File::load($file->id());
|
||||
$this->assertNotNull($loaded_file, 'Record exists in the database.');
|
||||
$this->assertEqual($loaded_file->isPermanent(), $file->isPermanent(), 'Status was saved correctly.');
|
||||
$this->assertEqual($file->getSize(), filesize($file->getFileUri()), 'File size was set correctly.', 'File');
|
||||
$this->assertTrue($file->getChangedTime() > 1, 'File size was set correctly.', 'File');
|
||||
$this->assertEqual($loaded_file->langcode->value, 'en', 'Langcode was defaulted correctly.');
|
||||
|
||||
// Resave the file, updating the existing record.
|
||||
file_test_reset();
|
||||
$file->status->value = 7;
|
||||
$file->save();
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('load', 'update'));
|
||||
|
||||
$this->assertEqual($file->id(), $file->id(), 'The file ID of an existing file is not changed when updating the database.', 'File');
|
||||
$this->assertTrue($file->getChangedTime() >= $file->getChangedTime(), "Timestamp didn't go backwards.", 'File');
|
||||
$loaded_file = File::load($file->id());
|
||||
$this->assertNotNull($loaded_file, 'Record still exists in the database.', 'File');
|
||||
$this->assertEqual($loaded_file->isPermanent(), $file->isPermanent(), 'Status was saved correctly.');
|
||||
$this->assertEqual($loaded_file->langcode->value, 'en', 'Langcode was saved correctly.');
|
||||
|
||||
// Try to insert a second file with the same name apart from case insensitivity
|
||||
// to ensure the 'uri' index allows for filenames with different cases.
|
||||
$uppercase_values = array(
|
||||
'uid' => 1,
|
||||
'filename' => 'DRUPLICON.txt',
|
||||
'uri' => 'public://DRUPLICON.txt',
|
||||
'filemime' => 'text/plain',
|
||||
'status' => FILE_STATUS_PERMANENT,
|
||||
);
|
||||
$uppercase_file = File::create($uppercase_values);
|
||||
file_put_contents($uppercase_file->getFileUri(), 'hello world');
|
||||
$violations = $uppercase_file->validate();
|
||||
$this->assertEqual(count($violations), 0, 'No violations when adding an URI with an existing filename in upper case.');
|
||||
$uppercase_file->save();
|
||||
|
||||
// Ensure the database URI uniqueness constraint is triggered.
|
||||
$uppercase_file_duplicate = File::create($uppercase_values);
|
||||
file_put_contents($uppercase_file_duplicate->getFileUri(), 'hello world');
|
||||
$violations = $uppercase_file_duplicate->validate();
|
||||
$this->assertEqual(count($violations), 1);
|
||||
$this->assertEqual($violations[0]->getMessage(), t('The file %value already exists. Enter a unique file URI.', [
|
||||
'%value' => $uppercase_file_duplicate->getFileUri(),
|
||||
]));
|
||||
// Ensure that file URI entity queries are case sensitive.
|
||||
$fids = \Drupal::entityQuery('file')
|
||||
->condition('uri', $uppercase_file->getFileUri())
|
||||
->execute();
|
||||
|
||||
$this->assertEqual(1, count($fids));
|
||||
$this->assertEqual(array($uppercase_file->id() => $uppercase_file->id()), $fids);
|
||||
|
||||
}
|
||||
}
|
74
core/modules/file/tests/src/Kernel/SpaceUsedTest.php
Normal file
74
core/modules/file/tests/src/Kernel/SpaceUsedTest.php
Normal file
|
@ -0,0 +1,74 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel;
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests the spaceUsed() function.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class SpaceUsedTest extends FileManagedUnitTestBase {
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// Create records for a couple of users with different sizes.
|
||||
$this->createFileWithSize('public://example1.txt', 50, 2);
|
||||
$this->createFileWithSize('public://example2.txt', 20, 2);
|
||||
$this->createFileWithSize('public://example3.txt', 100, 3);
|
||||
$this->createFileWithSize('public://example4.txt', 200, 3);
|
||||
|
||||
// Now create some non-permanent files.
|
||||
$this->createFileWithSize('public://example5.txt', 1, 2, 0);
|
||||
$this->createFileWithSize('public://example6.txt', 3, 3, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a file with a given size.
|
||||
*
|
||||
* @param string $uri
|
||||
* URI of the file to create.
|
||||
* @param int $size
|
||||
* Size of the file.
|
||||
* @param int $uid
|
||||
* File owner ID.
|
||||
* @param int $status
|
||||
* Whether the file should be permanent or temporary.
|
||||
*
|
||||
* @return \Drupal\Core\Entity\EntityInterface
|
||||
* The file entity.
|
||||
*/
|
||||
protected function createFileWithSize($uri, $size, $uid, $status = FILE_STATUS_PERMANENT) {
|
||||
file_put_contents($uri, $this->randomMachineName($size));
|
||||
$file = File::create([
|
||||
'uri' => $uri,
|
||||
'uid' => $uid,
|
||||
'status' => $status,
|
||||
]);
|
||||
$file->save();
|
||||
return $file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test different users with the default status.
|
||||
*/
|
||||
function testFileSpaceUsed() {
|
||||
$file = $this->container->get('entity.manager')->getStorage('file');
|
||||
// Test different users with default status.
|
||||
$this->assertEqual($file->spaceUsed(2), 70);
|
||||
$this->assertEqual($file->spaceUsed(3), 300);
|
||||
$this->assertEqual($file->spaceUsed(), 370);
|
||||
|
||||
// Test the status fields
|
||||
$this->assertEqual($file->spaceUsed(NULL, 0), 4);
|
||||
$this->assertEqual($file->spaceUsed(NULL, FILE_STATUS_PERMANENT), 370);
|
||||
|
||||
// Test both the user and status.
|
||||
$this->assertEqual($file->spaceUsed(1, 0), 0);
|
||||
$this->assertEqual($file->spaceUsed(1, FILE_STATUS_PERMANENT), 0);
|
||||
$this->assertEqual($file->spaceUsed(2, 0), 1);
|
||||
$this->assertEqual($file->spaceUsed(2, FILE_STATUS_PERMANENT), 70);
|
||||
$this->assertEqual($file->spaceUsed(3, 0), 3);
|
||||
$this->assertEqual($file->spaceUsed(3, FILE_STATUS_PERMANENT), 300);
|
||||
}
|
||||
}
|
205
core/modules/file/tests/src/Kernel/UsageTest.php
Normal file
205
core/modules/file/tests/src/Kernel/UsageTest.php
Normal file
|
@ -0,0 +1,205 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel;
|
||||
|
||||
/**
|
||||
* Tests file usage functions.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class UsageTest extends FileManagedUnitTestBase {
|
||||
/**
|
||||
* Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::listUsage().
|
||||
*/
|
||||
function testGetUsage() {
|
||||
$file = $this->createFile();
|
||||
db_insert('file_usage')
|
||||
->fields(array(
|
||||
'fid' => $file->id(),
|
||||
'module' => 'testing',
|
||||
'type' => 'foo',
|
||||
'id' => 1,
|
||||
'count' => 1
|
||||
))
|
||||
->execute();
|
||||
db_insert('file_usage')
|
||||
->fields(array(
|
||||
'fid' => $file->id(),
|
||||
'module' => 'testing',
|
||||
'type' => 'bar',
|
||||
'id' => 2,
|
||||
'count' => 2
|
||||
))
|
||||
->execute();
|
||||
|
||||
$usage = $this->container->get('file.usage')->listUsage($file);
|
||||
|
||||
$this->assertEqual(count($usage['testing']), 2, 'Returned the correct number of items.');
|
||||
$this->assertTrue(isset($usage['testing']['foo'][1]), 'Returned the correct id.');
|
||||
$this->assertTrue(isset($usage['testing']['bar'][2]), 'Returned the correct id.');
|
||||
$this->assertEqual($usage['testing']['foo'][1], 1, 'Returned the correct count.');
|
||||
$this->assertEqual($usage['testing']['bar'][2], 2, 'Returned the correct count.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::add().
|
||||
*/
|
||||
function testAddUsage() {
|
||||
$file = $this->createFile();
|
||||
$file_usage = $this->container->get('file.usage');
|
||||
$file_usage->add($file, 'testing', 'foo', 1);
|
||||
// Add the file twice to ensure that the count is incremented rather than
|
||||
// creating additional records.
|
||||
$file_usage->add($file, 'testing', 'bar', 2);
|
||||
$file_usage->add($file, 'testing', 'bar', 2);
|
||||
|
||||
$usage = db_select('file_usage', 'f')
|
||||
->fields('f')
|
||||
->condition('f.fid', $file->id())
|
||||
->execute()
|
||||
->fetchAllAssoc('id');
|
||||
$this->assertEqual(count($usage), 2, 'Created two records');
|
||||
$this->assertEqual($usage[1]->module, 'testing', 'Correct module');
|
||||
$this->assertEqual($usage[2]->module, 'testing', 'Correct module');
|
||||
$this->assertEqual($usage[1]->type, 'foo', 'Correct type');
|
||||
$this->assertEqual($usage[2]->type, 'bar', 'Correct type');
|
||||
$this->assertEqual($usage[1]->count, 1, 'Correct count');
|
||||
$this->assertEqual($usage[2]->count, 2, 'Correct count');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::delete().
|
||||
*/
|
||||
function testRemoveUsage() {
|
||||
$file = $this->createFile();
|
||||
$file_usage = $this->container->get('file.usage');
|
||||
db_insert('file_usage')
|
||||
->fields(array(
|
||||
'fid' => $file->id(),
|
||||
'module' => 'testing',
|
||||
'type' => 'bar',
|
||||
'id' => 2,
|
||||
'count' => 3,
|
||||
))
|
||||
->execute();
|
||||
|
||||
// Normal decrement.
|
||||
$file_usage->delete($file, 'testing', 'bar', 2);
|
||||
$count = db_select('file_usage', 'f')
|
||||
->fields('f', array('count'))
|
||||
->condition('f.fid', $file->id())
|
||||
->execute()
|
||||
->fetchField();
|
||||
$this->assertEqual(2, $count, 'The count was decremented correctly.');
|
||||
|
||||
// Multiple decrement and removal.
|
||||
$file_usage->delete($file, 'testing', 'bar', 2, 2);
|
||||
$count = db_select('file_usage', 'f')
|
||||
->fields('f', array('count'))
|
||||
->condition('f.fid', $file->id())
|
||||
->execute()
|
||||
->fetchField();
|
||||
$this->assertIdentical(FALSE, $count, 'The count was removed entirely when empty.');
|
||||
|
||||
// Non-existent decrement.
|
||||
$file_usage->delete($file, 'testing', 'bar', 2);
|
||||
$count = db_select('file_usage', 'f')
|
||||
->fields('f', array('count'))
|
||||
->condition('f.fid', $file->id())
|
||||
->execute()
|
||||
->fetchField();
|
||||
$this->assertIdentical(FALSE, $count, 'Decrementing non-exist record complete.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create files for all the possible combinations of age and status.
|
||||
*
|
||||
* We are using UPDATE statements because using the API would set the
|
||||
* timestamp.
|
||||
*/
|
||||
function createTempFiles() {
|
||||
// Temporary file that is old.
|
||||
$temp_old = file_save_data('');
|
||||
db_update('file_managed')
|
||||
->fields(array(
|
||||
'status' => 0,
|
||||
'changed' => REQUEST_TIME - $this->config('system.file')->get('temporary_maximum_age') - 1,
|
||||
))
|
||||
->condition('fid', $temp_old->id())
|
||||
->execute();
|
||||
$this->assertTrue(file_exists($temp_old->getFileUri()), 'Old temp file was created correctly.');
|
||||
|
||||
// Temporary file that is new.
|
||||
$temp_new = file_save_data('');
|
||||
db_update('file_managed')
|
||||
->fields(array('status' => 0))
|
||||
->condition('fid', $temp_new->id())
|
||||
->execute();
|
||||
$this->assertTrue(file_exists($temp_new->getFileUri()), 'New temp file was created correctly.');
|
||||
|
||||
// Permanent file that is old.
|
||||
$perm_old = file_save_data('');
|
||||
db_update('file_managed')
|
||||
->fields(array('changed' => REQUEST_TIME - $this->config('system.file')->get('temporary_maximum_age') - 1))
|
||||
->condition('fid', $temp_old->id())
|
||||
->execute();
|
||||
$this->assertTrue(file_exists($perm_old->getFileUri()), 'Old permanent file was created correctly.');
|
||||
|
||||
// Permanent file that is new.
|
||||
$perm_new = file_save_data('');
|
||||
$this->assertTrue(file_exists($perm_new->getFileUri()), 'New permanent file was created correctly.');
|
||||
return array($temp_old, $temp_new, $perm_old, $perm_new);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure that temporary files are removed by default.
|
||||
*/
|
||||
function testTempFileCleanupDefault() {
|
||||
list($temp_old, $temp_new, $perm_old, $perm_new) = $this->createTempFiles();
|
||||
|
||||
// Run cron and then ensure that only the old, temp file was deleted.
|
||||
$this->container->get('cron')->run();
|
||||
$this->assertFalse(file_exists($temp_old->getFileUri()), 'Old temp file was correctly removed.');
|
||||
$this->assertTrue(file_exists($temp_new->getFileUri()), 'New temp file was correctly ignored.');
|
||||
$this->assertTrue(file_exists($perm_old->getFileUri()), 'Old permanent file was correctly ignored.');
|
||||
$this->assertTrue(file_exists($perm_new->getFileUri()), 'New permanent file was correctly ignored.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure that temporary files are kept as configured.
|
||||
*/
|
||||
function testTempFileNoCleanup() {
|
||||
list($temp_old, $temp_new, $perm_old, $perm_new) = $this->createTempFiles();
|
||||
|
||||
// Set the max age to 0, meaning no temporary files will be deleted.
|
||||
$this->config('system.file')
|
||||
->set('temporary_maximum_age', 0)
|
||||
->save();
|
||||
|
||||
// Run cron and then ensure that no file was deleted.
|
||||
$this->container->get('cron')->run();
|
||||
$this->assertTrue(file_exists($temp_old->getFileUri()), 'Old temp file was correctly ignored.');
|
||||
$this->assertTrue(file_exists($temp_new->getFileUri()), 'New temp file was correctly ignored.');
|
||||
$this->assertTrue(file_exists($perm_old->getFileUri()), 'Old permanent file was correctly ignored.');
|
||||
$this->assertTrue(file_exists($perm_new->getFileUri()), 'New permanent file was correctly ignored.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure that temporary files are kept as configured.
|
||||
*/
|
||||
function testTempFileCustomCleanup() {
|
||||
list($temp_old, $temp_new, $perm_old, $perm_new) = $this->createTempFiles();
|
||||
|
||||
// Set the max age to older than default.
|
||||
$this->config('system.file')
|
||||
->set('temporary_maximum_age', 21600 + 2)
|
||||
->save();
|
||||
|
||||
// Run cron and then ensure that more files were deleted.
|
||||
$this->container->get('cron')->run();
|
||||
$this->assertTrue(file_exists($temp_old->getFileUri()), 'Old temp file was correctly ignored.');
|
||||
$this->assertTrue(file_exists($temp_new->getFileUri()), 'New temp file was correctly ignored.');
|
||||
$this->assertTrue(file_exists($perm_old->getFileUri()), 'Old permanent file was correctly ignored.');
|
||||
$this->assertTrue(file_exists($perm_new->getFileUri()), 'New permanent file was correctly ignored.');
|
||||
}
|
||||
}
|
37
core/modules/file/tests/src/Kernel/ValidateTest.php
Normal file
37
core/modules/file/tests/src/Kernel/ValidateTest.php
Normal file
|
@ -0,0 +1,37 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel;
|
||||
|
||||
|
||||
/**
|
||||
* Tests the file_validate() function.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class ValidateTest extends FileManagedUnitTestBase {
|
||||
/**
|
||||
* Test that the validators passed into are checked.
|
||||
*/
|
||||
function testCallerValidation() {
|
||||
$file = $this->createFile();
|
||||
|
||||
// Empty validators.
|
||||
$this->assertEqual(file_validate($file, array()), array(), 'Validating an empty array works successfully.');
|
||||
$this->assertFileHooksCalled(array('validate'));
|
||||
|
||||
// Use the file_test.module's test validator to ensure that passing tests
|
||||
// return correctly.
|
||||
file_test_reset();
|
||||
file_test_set_return('validate', array());
|
||||
$passing = array('file_test_validator' => array(array()));
|
||||
$this->assertEqual(file_validate($file, $passing), array(), 'Validating passes.');
|
||||
$this->assertFileHooksCalled(array('validate'));
|
||||
|
||||
// Now test for failures in validators passed in and by hook_validate.
|
||||
file_test_reset();
|
||||
file_test_set_return('validate', array('Epic fail'));
|
||||
$failing = array('file_test_validator' => array(array('Failed', 'Badly')));
|
||||
$this->assertEqual(file_validate($file, $failing), array('Failed', 'Badly', 'Epic fail'), 'Validating returns errors.');
|
||||
$this->assertFileHooksCalled(array('validate'));
|
||||
}
|
||||
}
|
155
core/modules/file/tests/src/Kernel/ValidatorTest.php
Normal file
155
core/modules/file/tests/src/Kernel/ValidatorTest.php
Normal file
|
@ -0,0 +1,155 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests the functions used to validate uploaded files.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class ValidatorTest extends FileManagedUnitTestBase {
|
||||
|
||||
/**
|
||||
* An image file.
|
||||
*
|
||||
* @var \Drupal\file\FileInterface
|
||||
*/
|
||||
protected $image;
|
||||
|
||||
/**
|
||||
* A file which is not an image.
|
||||
*
|
||||
* @var \Drupal\file\Entity\File
|
||||
*/
|
||||
protected $nonImage;
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->image = File::create();
|
||||
$this->image->setFileUri('core/misc/druplicon.png');
|
||||
$this->image->setFilename(drupal_basename($this->image->getFileUri()));
|
||||
|
||||
$this->nonImage = File::create();
|
||||
$this->nonImage->setFileUri('core/assets/vendor/jquery/jquery.min.js');
|
||||
$this->nonImage->setFilename(drupal_basename($this->nonImage->getFileUri()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the file_validate_extensions() function.
|
||||
*/
|
||||
function testFileValidateExtensions() {
|
||||
$file = File::create(['filename' => 'asdf.txt']);
|
||||
$errors = file_validate_extensions($file, 'asdf txt pork');
|
||||
$this->assertEqual(count($errors), 0, 'Valid extension accepted.', 'File');
|
||||
|
||||
$file->setFilename('asdf.txt');
|
||||
$errors = file_validate_extensions($file, 'exe png');
|
||||
$this->assertEqual(count($errors), 1, 'Invalid extension blocked.', 'File');
|
||||
}
|
||||
|
||||
/**
|
||||
* This ensures a specific file is actually an image.
|
||||
*/
|
||||
function testFileValidateIsImage() {
|
||||
$this->assertTrue(file_exists($this->image->getFileUri()), 'The image being tested exists.', 'File');
|
||||
$errors = file_validate_is_image($this->image);
|
||||
$this->assertEqual(count($errors), 0, 'No error reported for our image file.', 'File');
|
||||
|
||||
$this->assertTrue(file_exists($this->nonImage->getFileUri()), 'The non-image being tested exists.', 'File');
|
||||
$errors = file_validate_is_image($this->nonImage);
|
||||
$this->assertEqual(count($errors), 1, 'An error reported for our non-image file.', 'File');
|
||||
}
|
||||
|
||||
/**
|
||||
* This ensures the resolution of a specific file is within bounds.
|
||||
* The image will be resized if it's too large.
|
||||
*/
|
||||
function testFileValidateImageResolution() {
|
||||
// Non-images.
|
||||
$errors = file_validate_image_resolution($this->nonImage);
|
||||
$this->assertEqual(count($errors), 0, 'Should not get any errors for a non-image file.', 'File');
|
||||
$errors = file_validate_image_resolution($this->nonImage, '50x50', '100x100');
|
||||
$this->assertEqual(count($errors), 0, 'Do not check the resolution on non files.', 'File');
|
||||
|
||||
// Minimum size.
|
||||
$errors = file_validate_image_resolution($this->image);
|
||||
$this->assertEqual(count($errors), 0, 'No errors for an image when there is no minimum or maximum resolution.', 'File');
|
||||
$errors = file_validate_image_resolution($this->image, 0, '200x1');
|
||||
$this->assertEqual(count($errors), 1, 'Got an error for an image that was not wide enough.', 'File');
|
||||
$errors = file_validate_image_resolution($this->image, 0, '1x200');
|
||||
$this->assertEqual(count($errors), 1, 'Got an error for an image that was not tall enough.', 'File');
|
||||
$errors = file_validate_image_resolution($this->image, 0, '200x200');
|
||||
$this->assertEqual(count($errors), 1, 'Small images report an error.', 'File');
|
||||
|
||||
// Maximum size.
|
||||
if ($this->container->get('image.factory')->getToolkitId()) {
|
||||
// Copy the image so that the original doesn't get resized.
|
||||
copy('core/misc/druplicon.png', 'temporary://druplicon.png');
|
||||
$this->image->setFileUri('temporary://druplicon.png');
|
||||
|
||||
$errors = file_validate_image_resolution($this->image, '10x5');
|
||||
$this->assertEqual(count($errors), 0, 'No errors should be reported when an oversized image can be scaled down.', 'File');
|
||||
|
||||
$image = $this->container->get('image.factory')->get($this->image->getFileUri());
|
||||
$this->assertTrue($image->getWidth() <= 10, 'Image scaled to correct width.', 'File');
|
||||
$this->assertTrue($image->getHeight() <= 5, 'Image scaled to correct height.', 'File');
|
||||
|
||||
// Once again, now with negative width and height to force an error.
|
||||
copy('core/misc/druplicon.png', 'temporary://druplicon.png');
|
||||
$this->image->setFileUri('temporary://druplicon.png');
|
||||
$errors = file_validate_image_resolution($this->image, '-10x-5');
|
||||
$this->assertEqual(count($errors), 1, 'An error reported for an oversized image that can not be scaled down.', 'File');
|
||||
|
||||
drupal_unlink('temporary://druplicon.png');
|
||||
}
|
||||
else {
|
||||
// TODO: should check that the error is returned if no toolkit is available.
|
||||
$errors = file_validate_image_resolution($this->image, '5x10');
|
||||
$this->assertEqual(count($errors), 1, 'Oversize images that cannot be scaled get an error.', 'File');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This will ensure the filename length is valid.
|
||||
*/
|
||||
function testFileValidateNameLength() {
|
||||
// Create a new file entity.
|
||||
$file = File::create();
|
||||
|
||||
// Add a filename with an allowed length and test it.
|
||||
$file->setFilename(str_repeat('x', 240));
|
||||
$this->assertEqual(strlen($file->getFilename()), 240);
|
||||
$errors = file_validate_name_length($file);
|
||||
$this->assertEqual(count($errors), 0, 'No errors reported for 240 length filename.', 'File');
|
||||
|
||||
// Add a filename with a length too long and test it.
|
||||
$file->setFilename(str_repeat('x', 241));
|
||||
$errors = file_validate_name_length($file);
|
||||
$this->assertEqual(count($errors), 1, 'An error reported for 241 length filename.', 'File');
|
||||
|
||||
// Add a filename with an empty string and test it.
|
||||
$file->setFilename('');
|
||||
$errors = file_validate_name_length($file);
|
||||
$this->assertEqual(count($errors), 1, 'An error reported for 0 length filename.', 'File');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Test file_validate_size().
|
||||
*/
|
||||
function testFileValidateSize() {
|
||||
// Create a file with a size of 1000 bytes, and quotas of only 1 byte.
|
||||
$file = File::create(['filesize' => 1000]);
|
||||
$errors = file_validate_size($file, 0, 0);
|
||||
$this->assertEqual(count($errors), 0, 'No limits means no errors.', 'File');
|
||||
$errors = file_validate_size($file, 1, 0);
|
||||
$this->assertEqual(count($errors), 1, 'Error for the file being over the limit.', 'File');
|
||||
$errors = file_validate_size($file, 0, 1);
|
||||
$this->assertEqual(count($errors), 1, 'Error for the user being over their limit.', 'File');
|
||||
$errors = file_validate_size($file, 1, 1);
|
||||
$this->assertEqual(count($errors), 2, 'Errors for both the file and their limit.', 'File');
|
||||
}
|
||||
}
|
|
@ -0,0 +1,99 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Views;
|
||||
|
||||
use Drupal\Core\Render\RenderContext;
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\Tests\views\Kernel\ViewsKernelTestBase;
|
||||
use Drupal\views\Views;
|
||||
use Drupal\views\Tests\ViewTestData;
|
||||
|
||||
/**
|
||||
* Tests the core Drupal\file\Plugin\views\field\Extension handler.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class ExtensionViewsFieldTest extends ViewsKernelTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = array('file', 'file_test_views', 'user');
|
||||
|
||||
/**
|
||||
* Views used by this test.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $testViews = array('file_extension_view');
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp($import_test_views = TRUE) {
|
||||
parent::setUp();
|
||||
ViewTestData::createTestViews(get_class($this), array('file_test_views'));
|
||||
|
||||
$this->installEntitySchema('file');
|
||||
|
||||
file_put_contents('public://file.png', '');
|
||||
File::create([
|
||||
'uri' => 'public://file.png',
|
||||
'filename' => 'file.png',
|
||||
])->save();
|
||||
|
||||
file_put_contents('public://file.tar', '');
|
||||
File::create([
|
||||
'uri' => 'public://file.tar',
|
||||
'filename' => 'file.tar',
|
||||
])->save();
|
||||
|
||||
file_put_contents('public://file.tar.gz', '');
|
||||
File::create([
|
||||
'uri' => 'public://file.tar.gz',
|
||||
'filename' => 'file.tar.gz',
|
||||
])->save();
|
||||
|
||||
file_put_contents('public://file', '');
|
||||
File::create([
|
||||
'uri' => 'public://file',
|
||||
'filename' => 'file',
|
||||
])->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests file extension views field handler extension_detect_tar option.
|
||||
*/
|
||||
public function testFileExtensionTarOption() {
|
||||
/** @var \Drupal\Core\Render\RendererInterface $renderer */
|
||||
$renderer = \Drupal::service('renderer');
|
||||
|
||||
$view = Views::getView('file_extension_view');
|
||||
$view->setDisplay();
|
||||
$this->executeView($view);
|
||||
|
||||
// Test without the tar option.
|
||||
$renderer->executeInRenderContext(new RenderContext(), function () use ($view) {
|
||||
$this->assertEqual($view->field['extension']->advancedRender($view->result[0]), 'png');
|
||||
$this->assertEqual($view->field['extension']->advancedRender($view->result[1]), 'tar');
|
||||
$this->assertEqual($view->field['extension']->advancedRender($view->result[2]), 'gz');
|
||||
$this->assertEqual($view->field['extension']->advancedRender($view->result[3]), '');
|
||||
});
|
||||
|
||||
// Test with the tar option.
|
||||
$view = Views::getView('file_extension_view');
|
||||
$view->setDisplay();
|
||||
$view->initHandlers();
|
||||
|
||||
$view->field['extension']->options['settings']['extension_detect_tar'] = TRUE;
|
||||
$this->executeView($view);
|
||||
|
||||
$renderer->executeInRenderContext(new RenderContext(), function () use ($view) {
|
||||
$this->assertEqual($view->field['extension']->advancedRender($view->result[0]), 'png');
|
||||
$this->assertEqual($view->field['extension']->advancedRender($view->result[1]), 'tar');
|
||||
$this->assertEqual($view->field['extension']->advancedRender($view->result[2]), 'tar.gz');
|
||||
$this->assertEqual($view->field['extension']->advancedRender($view->result[3]), '');
|
||||
});
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\file\Kernel\Views;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\language\Entity\ConfigurableLanguage;
|
||||
use Drupal\user\Entity\User;
|
||||
use Drupal\Tests\views\Kernel\Handler\FieldFieldAccessTestBase;
|
||||
|
||||
/**
|
||||
* Tests base field access in Views for the file entity.
|
||||
*
|
||||
* @group File
|
||||
*/
|
||||
class FileViewsFieldAccessTest extends FieldFieldAccessTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = ['file', 'entity_test', 'language', 'user'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp($import_test_views = TRUE) {
|
||||
parent::setUp($import_test_views);
|
||||
|
||||
$this->installEntitySchema('file');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check access for file fields.
|
||||
*/
|
||||
public function testFileFields() {
|
||||
ConfigurableLanguage::create([
|
||||
'id' => 'fr',
|
||||
'name' => 'French',
|
||||
])->save();
|
||||
|
||||
$user = User::create([
|
||||
'name' => 'test user',
|
||||
]);
|
||||
$user->save();
|
||||
|
||||
file_put_contents('public://test.txt', 'test');
|
||||
$file = File::create([
|
||||
'filename' => 'test.txt',
|
||||
'uri' => 'public://test.txt',
|
||||
'status' => TRUE,
|
||||
'langcode' => 'fr',
|
||||
'uid' => $user->id()
|
||||
]);
|
||||
$file->save();
|
||||
|
||||
// @todo Expand the test coverage in https://www.drupal.org/node/2464635
|
||||
|
||||
$this->assertFieldAccess('file', 'fid', $file->id());
|
||||
$this->assertFieldAccess('file', 'uuid', $file->uuid());
|
||||
$this->assertFieldAccess('file', 'langcode', $file->language()->getName());
|
||||
$this->assertFieldAccess('file', 'uid', 'test user');
|
||||
$this->assertFieldAccess('file', 'filename', $file->getFilename());
|
||||
$this->assertFieldAccess('file', 'uri', $file->getFileUri());
|
||||
$this->assertFieldAccess('file', 'filemime', $file->filemime->value);
|
||||
$this->assertFieldAccess('file', 'filesize', '4 bytes');
|
||||
$this->assertFieldAccess('file', 'status', t('Permanent'));
|
||||
// $this->assertFieldAccess('file', 'created', \Drupal::service('date.formatter')->format(123456));
|
||||
// $this->assertFieldAccess('file', 'changed', \Drupal::service('date.formatter')->format(REQUEST_TIME));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,14 +1,9 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Tests\file\Unit\Plugin\migrate\process\d6\CckFileTest.
|
||||
*/
|
||||
|
||||
namespace Drupal\Tests\file\Unit\Plugin\migrate\process\d6;
|
||||
|
||||
use Drupal\file\Plugin\migrate\process\d6\CckFile;
|
||||
use Drupal\migrate\Entity\MigrationInterface;
|
||||
use Drupal\migrate\Plugin\MigrationInterface;
|
||||
use Drupal\migrate\MigrateExecutableInterface;
|
||||
use Drupal\migrate\Plugin\MigrateProcessInterface;
|
||||
use Drupal\migrate\Row;
|
||||
|
|
|
@ -1,10 +1,5 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Tests\file\Unit\Plugin\migrate\process\d6\FileUriTest.
|
||||
*/
|
||||
|
||||
namespace Drupal\Tests\file\Unit\Plugin\migrate\process\d6;
|
||||
|
||||
use Drupal\file\Plugin\migrate\process\d6\FileUri;
|
||||
|
|
|
@ -1,10 +1,5 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Tests\file\Unit\Plugin\migrate\source\d6\FileTest.
|
||||
*/
|
||||
|
||||
namespace Drupal\Tests\file\Unit\Plugin\migrate\source\d6;
|
||||
|
||||
use Drupal\Tests\migrate\Unit\MigrateSqlSourceTestCase;
|
||||
|
|
|
@ -1,10 +1,5 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Tests\file\Unit\Plugin\migrate\source\d6\UploadInstanceTest.
|
||||
*/
|
||||
|
||||
namespace Drupal\Tests\file\Unit\Plugin\migrate\source\d6;
|
||||
|
||||
use Drupal\file\Plugin\migrate\source\d6\UploadInstance;
|
||||
|
|
|
@ -1,10 +1,5 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Tests\file\Unit\Plugin\migrate\source\d6\UploadTest.
|
||||
*/
|
||||
|
||||
namespace Drupal\Tests\file\Unit\Plugin\migrate\source\d6;
|
||||
|
||||
use Drupal\file\Plugin\migrate\source\d6\Upload;
|
||||
|
|
Reference in a new issue