Move into nested docroot

This commit is contained in:
Rob Davies 2017-02-13 15:31:17 +00:00
parent 83a0d3a149
commit c8b70abde9
13405 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,6 @@
name: 'File test'
type: module
description: 'Provides hooks for testing File module functionality.'
package: Testing
version: VERSION
core: 8.x

View file

@ -0,0 +1,10 @@
file_module_test.managed_test:
path: '/file/test/{tree}/{extended}/{multiple}/{default_fids}'
defaults:
_form: '\Drupal\file_module_test\Form\FileModuleTestForm'
tree: TRUE
extended: TRUE
multiple: FALSE
default_fids: NULL
requirements:
_access: 'TRUE'

View file

@ -0,0 +1,89 @@
<?php
namespace Drupal\file_module_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Form controller for file_module_test module.
*/
class FileModuleTestForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'file_module_test_form';
}
/**
* {@inheritdoc}
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param bool $tree
* (optional) If the form should use #tree. Defaults to TRUE.
* @param bool $extended
* (optional) If the form should use #extended. Defaults to TRUE.
* @param bool $multiple
* (optional) If the form should use #multiple. Defaults to FALSE.
* @param array $default_fids
* (optional) Any default file IDs to use.
*/
public function buildForm(array $form, FormStateInterface $form_state, $tree = TRUE, $extended = TRUE, $multiple = FALSE, $default_fids = NULL) {
$form['#tree'] = (bool) $tree;
$form['nested']['file'] = array(
'#type' => 'managed_file',
'#title' => $this->t('Managed <em>@type</em>', ['@type' => 'file & butter']),
'#upload_location' => 'public://test',
'#progress_message' => $this->t('Please wait...'),
'#extended' => (bool) $extended,
'#size' => 13,
'#multiple' => (bool) $multiple,
);
if ($default_fids) {
$default_fids = explode(',', $default_fids);
$form['nested']['file']['#default_value'] = $extended ? array('fids' => $default_fids) : $default_fids;
}
$form['textfield'] = array(
'#type' => 'textfield',
'#title' => $this->t('Type a value and ensure it stays'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Save'),
);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
if ($form['#tree']) {
$uploads = $form_state->getValue(array('nested', 'file'));
}
else {
$uploads = $form_state->getValue('file');
}
if ($form['nested']['file']['#extended']) {
$uploads = $uploads['fids'];
}
$fids = array();
foreach ($uploads as $fid) {
$fids[] = $fid;
}
drupal_set_message($this->t('The file ids are %fids.', array('%fids' => implode(',', $fids))));
}
}

View file

@ -0,0 +1,6 @@
name: 'File test'
type: module
description: 'Support module for file handling tests.'
package: Testing
version: VERSION
core: 8.x

View file

@ -0,0 +1,351 @@
<?php
/**
* @file
* Helper module for the file tests.
*
* The caller is must call file_test_reset() to initializing this module before
* calling file_test_get_calls() or file_test_set_return().
*/
use Drupal\file\Entity\File;
const FILE_URL_TEST_CDN_1 = 'http://cdn1.example.com';
const FILE_URL_TEST_CDN_2 = 'http://cdn2.example.com';
/**
* Reset/initialize the history of calls to the file_* hooks.
*
* @see file_test_get_calls()
* @see file_test_reset()
*/
function file_test_reset() {
// Keep track of calls to these hooks
$results = array(
'load' => array(),
'validate' => array(),
'download' => array(),
'insert' => array(),
'update' => array(),
'copy' => array(),
'move' => array(),
'delete' => array(),
);
\Drupal::state()->set('file_test.results', $results);
// These hooks will return these values, see file_test_set_return().
$return = array(
'validate' => array(),
'download' => NULL,
);
\Drupal::state()->set('file_test.return', $return);
}
/**
* Get the arguments passed to invocation of a given hook since
* file_test_reset() was last called.
*
* @param string $op
* One of the hook_file_* operations: 'load', 'validate', 'download',
* 'insert', 'update', 'copy', 'move', 'delete'.
*
* @return array
* Array of the parameters passed to each call.
*
* @see _file_test_log_call()
* @see file_test_reset()
*/
function file_test_get_calls($op) {
$results = \Drupal::state()->get('file_test.results') ?: array();
return $results[$op];
}
/**
* Get an array with the calls for all hooks.
*
* @return
* An array keyed by hook name ('load', 'validate', 'download', 'insert',
* 'update', 'copy', 'move', 'delete') with values being arrays of parameters
* passed to each call.
*/
function file_test_get_all_calls() {
return \Drupal::state()->get('file_test.results') ?: array();
}
/**
* Store the values passed to a hook invocation.
*
* @param string $op
* One of the hook_file_* operations: 'load', 'validate', 'download',
* 'insert', 'update', 'copy', 'move', 'delete'.
* @param array $args
* Values passed to hook.
*
* @see file_test_get_calls()
* @see file_test_reset()
*/
function _file_test_log_call($op, $args) {
if (\Drupal::state()->get('file_test.count_hook_invocations', TRUE)) {
$results = \Drupal::state()->get('file_test.results') ?: array();
$results[$op][] = $args;
\Drupal::state()->set('file_test.results', $results);
}
}
/**
* Load the appropriate return value.
*
* @param string $op
* One of the hook_file_[validate,download] operations.
*
* @return mixed
* Value set by file_test_set_return().
*
* @see file_test_set_return()
* @see file_test_reset()
*/
function _file_test_get_return($op) {
$return = \Drupal::state()->get('file_test.return') ?: array($op => NULL);
return $return[$op];
}
/**
* Assign a return value for a given operation.
*
* @param string $op
* One of the hook_file_[validate,download] operations.
* @param mixed $value
* Value for the hook to return.
*
* @see _file_test_get_return()
* @see file_test_reset()
*/
function file_test_set_return($op, $value) {
$return = \Drupal::state()->get('file_test.return') ?: array();
$return[$op] = $value;
\Drupal::state()->set('file_test.return', $return);
}
/**
* Implements hook_ENTITY_TYPE_load() for file entities.
*/
function file_test_file_load($files) {
foreach ($files as $file) {
_file_test_log_call('load', array($file->id()));
// Assign a value on the object so that we can test that the $file is passed
// by reference.
$file->file_test['loaded'] = TRUE;
}
}
/**
* Implements hook_file_validate().
*/
function file_test_file_validate(File $file) {
_file_test_log_call('validate', array($file->id()));
return _file_test_get_return('validate');
}
/**
* Implements hook_file_download().
*/
function file_test_file_download($uri) {
if (\Drupal::state()->get('file_test.allow_all', FALSE)) {
$files = entity_load_multiple_by_properties('file', array('uri' => $uri));
$file = reset($files);
return file_get_content_headers($file);
}
_file_test_log_call('download', array($uri));
return _file_test_get_return('download');
}
/**
* Implements hook_ENTITY_TYPE_insert() for file entities.
*/
function file_test_file_insert(File $file) {
_file_test_log_call('insert', array($file->id()));
}
/**
* Implements hook_ENTITY_TYPE_update() for file entities.
*/
function file_test_file_update(File $file) {
_file_test_log_call('update', array($file->id()));
}
/**
* Implements hook_file_copy().
*/
function file_test_file_copy(File $file, $source) {
_file_test_log_call('copy', array($file->id(), $source->id()));
}
/**
* Implements hook_file_move().
*/
function file_test_file_move(File $file, File $source) {
_file_test_log_call('move', array($file->id(), $source->id()));
}
/**
* Implements hook_ENTITY_TYPE_predelete() for file entities.
*/
function file_test_file_predelete(File $file) {
_file_test_log_call('delete', array($file->id()));
}
/**
* Implements hook_file_url_alter().
*/
function file_test_file_url_alter(&$uri) {
// Only run this hook when this variable is set. Otherwise, we'd have to add
// another hidden test module just for this hook.
$alter_mode = \Drupal::state()->get('file_test.hook_file_url_alter');
if (!$alter_mode) {
return;
}
// Test alteration of file URLs to use a CDN.
elseif ($alter_mode == 'cdn') {
$cdn_extensions = array('css', 'js', 'gif', 'jpg', 'jpeg', 'png');
// Most CDNs don't support private file transfers without a lot of hassle,
// so don't support this in the common case.
$schemes = array('public');
$scheme = file_uri_scheme($uri);
// Only serve shipped files and public created files from the CDN.
if (!$scheme || in_array($scheme, $schemes)) {
// Shipped files.
if (!$scheme) {
$path = $uri;
}
// Public created files.
else {
$wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
$path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
}
// Clean up Windows paths.
$path = str_replace('\\', '/', $path);
// Serve files with one of the CDN extensions from CDN 1, all others from
// CDN 2.
$pathinfo = pathinfo($path);
if (array_key_exists('extension', $pathinfo) && in_array($pathinfo['extension'], $cdn_extensions)) {
$uri = FILE_URL_TEST_CDN_1 . '/' . $path;
}
else {
$uri = FILE_URL_TEST_CDN_2 . '/' . $path;
}
}
}
// Test alteration of file URLs to use root-relative URLs.
elseif ($alter_mode == 'root-relative') {
// Only serve shipped files and public created files with root-relative
// URLs.
$scheme = file_uri_scheme($uri);
if (!$scheme || $scheme == 'public') {
// Shipped files.
if (!$scheme) {
$path = $uri;
}
// Public created files.
else {
$wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
$path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
}
// Clean up Windows paths.
$path = str_replace('\\', '/', $path);
// Generate a root-relative URL.
$uri = base_path() . '/' . $path;
}
}
// Test alteration of file URLs to use protocol-relative URLs.
elseif ($alter_mode == 'protocol-relative') {
// Only serve shipped files and public created files with protocol-relative
// URLs.
$scheme = file_uri_scheme($uri);
if (!$scheme || $scheme == 'public') {
// Shipped files.
if (!$scheme) {
$path = $uri;
}
// Public created files.
else {
$wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
$path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
}
// Clean up Windows paths.
$path = str_replace('\\', '/', $path);
// Generate a protocol-relative URL.
$uri = '/' . base_path() . '/' . $path;
}
}
}
/**
* Implements hook_file_mimetype_mapping_alter().
*/
function file_test_file_mimetype_mapping_alter(&$mapping) {
// Add new mappings.
$mapping['mimetypes']['file_test_mimetype_1'] = 'madeup/file_test_1';
$mapping['mimetypes']['file_test_mimetype_2'] = 'madeup/file_test_2';
$mapping['mimetypes']['file_test_mimetype_3'] = 'madeup/doc';
$mapping['extensions']['file_test_1'] = 'file_test_mimetype_1';
$mapping['extensions']['file_test_2'] = 'file_test_mimetype_2';
$mapping['extensions']['file_test_3'] = 'file_test_mimetype_2';
// Override existing mapping.
$mapping['extensions']['doc'] = 'file_test_mimetype_3';
}
/**
* Helper validator that returns the $errors parameter.
*/
function file_test_validator(File $file, $errors) {
return $errors;
}
/**
* Helper function for testing file_scan_directory().
*
* Each time the function is called the file is stored in a static variable.
* When the function is called with no $filepath parameter, the results are
* returned.
*
* @param string|null $filepath
* File path
* @return array
* If $filepath is NULL, an array of all previous $filepath parameters
*/
function file_test_file_scan_callback($filepath = NULL) {
$files = &drupal_static(__FUNCTION__, array());
if (isset($filepath)) {
$files[] = $filepath;
}
else {
return $files;
}
}
/**
* Reset static variables used by file_test_file_scan_callback().
*/
function file_test_file_scan_callback_reset() {
drupal_static_reset('file_test_file_scan_callback');
}
/**
* Implements hook_entity_info_alter().
*/
function file_test_entity_type_alter(&$entity_types) {
if (\Drupal::state()->get('file_test_alternate_access_handler', FALSE)) {
/** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
$entity_types['file']
->setAccessClass('Drupal\file_test\FileTestAccessControlHandler');
}
}

View file

@ -0,0 +1,6 @@
file.test:
path: '/file-test/upload'
defaults:
_form: 'Drupal\file_test\Form\FileTestForm'
requirements:
_access: 'TRUE'

View file

@ -0,0 +1,13 @@
services:
stream_wrapper.dummy_readonly:
class: Drupal\file_test\StreamWrapper\DummyReadOnlyStreamWrapper
tags:
- { name: stream_wrapper, scheme: dummy-readonly }
stream_wrapper.dummy_remote:
class: Drupal\file_test\StreamWrapper\DummyRemoteStreamWrapper
tags:
- { name: stream_wrapper, scheme: dummy-remote }
stream_wrapper.dummy:
class: Drupal\file_test\StreamWrapper\DummyStreamWrapper
tags:
- { name: stream_wrapper, scheme: dummy }

View file

@ -0,0 +1,23 @@
<?php
namespace Drupal\file_test;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\file\FileAccessFormatterControlHandlerInterface;
use Drupal\file\FileAccessControlHandler;
/**
* Defines a class for an alternate file access control handler.
*/
class FileTestAccessControlHandler extends FileAccessControlHandler implements FileAccessFormatterControlHandlerInterface {
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
\Drupal::state()->set('file_access_formatter_check', TRUE);
return parent::checkAccess($entity, $operation, $account);
}
}

View file

@ -0,0 +1,121 @@
<?php
namespace Drupal\file_test\Form;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* File test form class.
*/
class FileTestForm implements FormInterface {
/**
* {@inheritdoc}
*/
public function getFormId() {
return '_file_test_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['file_test_upload'] = array(
'#type' => 'file',
'#title' => t('Upload a file'),
);
$form['file_test_replace'] = array(
'#type' => 'select',
'#title' => t('Replace existing image'),
'#options' => array(
FILE_EXISTS_RENAME => t('Appends number until name is unique'),
FILE_EXISTS_REPLACE => t('Replace the existing file'),
FILE_EXISTS_ERROR => t('Fail with an error'),
),
'#default_value' => FILE_EXISTS_RENAME,
);
$form['file_subdir'] = array(
'#type' => 'textfield',
'#title' => t('Subdirectory for test file'),
'#default_value' => '',
);
$form['extensions'] = array(
'#type' => 'textfield',
'#title' => t('Allowed extensions.'),
'#default_value' => '',
);
$form['allow_all_extensions'] = array(
'#type' => 'checkbox',
'#title' => t('Allow all extensions?'),
'#default_value' => FALSE,
);
$form['is_image_file'] = array(
'#type' => 'checkbox',
'#title' => t('Is this an image file?'),
'#default_value' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Process the upload and perform validation. Note: we're using the
// form value for the $replace parameter.
if (!$form_state->isValueEmpty('file_subdir')) {
$destination = 'temporary://' . $form_state->getValue('file_subdir');
file_prepare_directory($destination, FILE_CREATE_DIRECTORY);
}
else {
$destination = FALSE;
}
// Setup validators.
$validators = array();
if ($form_state->getValue('is_image_file')) {
$validators['file_validate_is_image'] = array();
}
if ($form_state->getValue('allow_all_extensions')) {
$validators['file_validate_extensions'] = array();
}
elseif (!$form_state->isValueEmpty('extensions')) {
$validators['file_validate_extensions'] = array($form_state->getValue('extensions'));
}
// The test for drupal_move_uploaded_file() triggering a warning is
// unavoidable. We're interested in what happens afterwards in
// file_save_upload().
if (\Drupal::state()->get('file_test.disable_error_collection')) {
define('SIMPLETEST_COLLECT_ERRORS', FALSE);
}
$file = file_save_upload('file_test_upload', $validators, $destination, 0, $form_state->getValue('file_test_replace'));
if ($file) {
$form_state->setValue('file_test_upload', $file);
drupal_set_message(t('File @filepath was uploaded.', array('@filepath' => $file->getFileUri())));
drupal_set_message(t('File name is @filename.', array('@filename' => $file->getFilename())));
drupal_set_message(t('File MIME type is @mimetype.', array('@mimetype' => $file->getMimeType())));
drupal_set_message(t('You WIN!'));
}
elseif ($file === FALSE) {
drupal_set_message(t('Epic upload FAIL!'), 'error');
}
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Drupal\file_test\StreamWrapper;
use Drupal\Core\StreamWrapper\LocalReadOnlyStream;
/**
* Helper class for testing the stream wrapper registry.
*
* Dummy stream wrapper implementation (dummy-readonly://).
*/
class DummyReadOnlyStreamWrapper extends LocalReadOnlyStream {
/**
* {@inheritdoc}
*/
public function getName() {
return t('Dummy files (readonly)');
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return t('Dummy wrapper for simpletest (readonly).');
}
function getDirectoryPath() {
return \Drupal::service('site.path') . '/files';
}
/**
* Override getInternalUri().
*
* Return a dummy path for testing.
*/
function getInternalUri() {
return '/dummy/example.txt';
}
/**
* Override getExternalUrl().
*
* Return the HTML URI of a public file.
*/
function getExternalUrl() {
return '/dummy/example.txt';
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace Drupal\file_test\StreamWrapper;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
/**
* Dummy read-only remote stream wrapper (dummy-remote-readonly://).
*/
class DummyRemoteReadOnlyStreamWrapper extends DummyRemoteStreamWrapper {
/**
* {@inheritdoc}
*/
public static function getType() {
return StreamWrapperInterface::READ_VISIBLE;
}
/**
* {@inheritdoc}
*/
public function getName() {
return t('Dummy remote read-only files');
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return t('Dummy remote read-only stream wrapper for testing.');
}
}

View file

@ -0,0 +1,34 @@
<?php
namespace Drupal\file_test\StreamWrapper;
use Drupal\Core\StreamWrapper\PublicStream;
/**
* Helper class for testing the stream wrapper registry.
*
* Dummy remote stream wrapper implementation (dummy-remote://).
*
* Basically just the public scheme but not returning a local file for realpath.
*/
class DummyRemoteStreamWrapper extends PublicStream {
/**
* {@inheritdoc}
*/
public function getName() {
return t('Dummy files (remote)');
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return t('Dummy wrapper for simpletest (remote).');
}
function realpath() {
return FALSE;
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Drupal\file_test\StreamWrapper;
use Drupal\Core\StreamWrapper\LocalStream;
/**
* Helper class for testing the stream wrapper registry.
*
* Dummy stream wrapper implementation (dummy://).
*/
class DummyStreamWrapper extends LocalStream {
/**
* {@inheritdoc}
*/
public function getName() {
return t('Dummy files');
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return t('Dummy wrapper for simpletest.');
}
function getDirectoryPath() {
return \Drupal::service('site.path') . '/files';
}
/**
* Override getInternalUri().
*
* Return a dummy path for testing.
*/
function getInternalUri() {
return '/dummy/example.txt';
}
/**
* Override getExternalUrl().
*
* Return the HTML URI of a public file.
*/
function getExternalUrl() {
return '/dummy/example.txt';
}
}

View file

@ -0,0 +1,9 @@
name: 'File test views'
type: module
description: 'Provides default views for views file tests.'
package: Testing
version: VERSION
core: 8.x
dependencies:
- file
- views

View file

@ -0,0 +1,48 @@
langcode: en
status: true
dependencies: { }
id: file_extension_view
label: 'Test view for file extension views field handler'
module: views
description: ''
tag: ''
base_table: file_managed
base_field: fid
core: '8'
display:
default:
display_options:
defaults:
fields: false
pager: false
sorts: false
fields:
fid:
field: fid
id: fid
relationship: none
table: file_managed
plugin_id: field
extension:
field: extension
id: extension
relationship: none
table: file_managed
plugin_id: field
type: file_extension
pager:
options:
offset: 0
type: none
sorts:
fid:
field: fid
id: fid
order: ASC
relationship: none
table: file_managed
plugin_id: standard
display_plugin: default
display_title: Master
id: default
position: 0

View file

@ -0,0 +1,77 @@
langcode: en
status: true
dependencies:
module:
- file
- user
id: test_file_user_file_data
label: test_file_user_file_data
module: views
description: ''
tag: ''
base_table: users_field_data
base_field: uid
core: 8.x
display:
default:
display_plugin: default
id: default
display_title: Master
position: 0
display_options:
access:
type: perm
options:
perm: 'access user profiles'
cache:
type: tag
style:
type: table
options:
grouping: { }
row_class: ''
default_row_class: true
override: true
sticky: false
caption: ''
summary: ''
description: ''
columns:
name: name
fid: fid
info:
name:
sortable: false
default_sort_order: asc
align: ''
separator: ''
empty_column: false
responsive: ''
fid:
sortable: false
default_sort_order: asc
align: ''
separator: ''
empty_column: false
responsive: ''
default: '-1'
empty_table: false
row:
type: fields
options:
inline: { }
separator: ''
hide_empty: false
default_field_elements: true
relationships:
user_file_target_id:
id: user_file_target_id
table: user__user_file
field: user_file_target_id
relationship: none
group_type: group
admin_label: 'file from user_file'
required: true
plugin_id: standard
arguments: { }
display_extenders: { }

View file

@ -0,0 +1,107 @@
<?php
namespace Drupal\Tests\file\Kernel;
use Drupal\file\Entity\File;
use Drupal\KernelTests\KernelTestBase;
use Drupal\user\Entity\User;
/**
* Tests for the File access control.
*
* @group file
*/
class AccessTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['file', 'system', 'user'];
/**
* An authenticated user.
*
* @var \Drupal\user\UserInterface
*/
protected $user1;
/**
* An authenticated user.
*
* @var \Drupal\user\UserInterface
*/
protected $user2;
/**
* The file object used in the test.
*
* @var \Drupal\file\FileInterface
*/
protected $file;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installEntitySchema('file');
$this->installEntitySchema('user');
$this->installSchema('file', array('file_usage'));
$this->installSchema('system', 'sequences');
$this->user1 = User::create([
'name' => 'user1',
'status' => 1,
]);
$this->user1->save();
$this->user2 = User::create([
'name' => 'user2',
'status' => 1,
]);
$this->user2->save();
$this->file = File::create(array(
'uid' => $this->user1->id(),
'filename' => 'druplicon.txt',
'filemime' => 'text/plain',
));
}
/**
* Tests that only the file owner can delete or update a file.
*/
public function testOnlyOwnerCanDeleteUpdateFile() {
\Drupal::currentUser()->setAccount($this->user2);
$this->assertFalse($this->file->access('delete'));
$this->assertFalse($this->file->access('update'));
\Drupal::currentUser()->setAccount($this->user1);
$this->assertTrue($this->file->access('delete'));
$this->assertTrue($this->file->access('update'));
}
/**
* Tests that the status field is not editable.
*/
public function testStatusFieldIsNotEditable() {
\Drupal::currentUser()->setAccount($this->user1);
$this->assertFalse($this->file->get('status')->access('edit'));
}
/**
* Tests create access checks.
*/
public function testCreateAccess() {
// Anonymous users can create a file by default.
$this->assertFalse($this->file->access('create'));
// Authenticated users can create a file by default.
\Drupal::currentUser()->setAccount($this->user1);
$this->assertFalse($this->file->access('create'));
}
}

View file

@ -0,0 +1,145 @@
<?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()));
}
}

View file

@ -0,0 +1,72 @@
<?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.');
}
}

View 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 = EntityTest::load($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);
}
}

View file

@ -0,0 +1,114 @@
<?php
namespace Drupal\Tests\file\Kernel;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\file\Entity\File;
use Drupal\KernelTests\KernelTestBase;
use Drupal\user\Entity\User;
use org\bovigo\vfs\vfsStream;
/**
* Tests that files referenced in file and image fields are always validated.
*
* @group file
*/
class FileItemValidationTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['file', 'image', 'entity_test', 'field', 'user', 'system'];
/**
* A user.
*
* @var \Drupal\user\UserInterface
*/
protected $user;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installEntitySchema('user');
$this->installEntitySchema('file');
$this->installSchema('file', 'file_usage');
$this->installSchema('system', 'sequences');
$this->user = User::create([
'name' => 'username',
'status' => 1,
]);
$this->user->save();
}
/**
* @covers \Drupal\file\Plugin\Validation\Constraint\FileValidationConstraint
* @covers \Drupal\file\Plugin\Validation\Constraint\FileValidationConstraintValidator
* @dataProvider getFileTypes
*/
public function testFileValidationConstraint($file_type) {
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_test_file',
'entity_type' => 'entity_test',
'type' => $file_type,
]);
$field_storage->save();
$field = FieldConfig::create([
'field_name' => 'field_test_file',
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
'settings' => [
'max_filesize' => '2k',
'file_extensions' => 'jpg|png',
],
]);
$field->save();
vfsStream::setup('drupal_root');
vfsStream::create([
'sites' => [
'default' => [
'files' => [
'test.txt' => str_repeat('a', 3000),
]
]
]
]);
// Test for max filesize.
$file = File::create([
'uri' => 'vfs://drupal_root/sites/default/files/test.txt',
]);
$file->setPermanent();
$file->save();
$entity_test = EntityTest::create([
'uid' => $this->user->id(),
'field_test_file' => [
'target_id' => $file->id(),
]
]);
$result = $entity_test->validate();
$this->assertCount(2, $result);
$this->assertEquals('field_test_file.0', $result->get(0)->getPropertyPath());
$this->assertEquals('The file is <em class="placeholder">2.93 KB</em> exceeding the maximum file size of <em class="placeholder">2 KB</em>.', (string) $result->get(0)->getMessage());
$this->assertEquals('field_test_file.0', $result->get(1)->getPropertyPath());
$this->assertEquals('Only files with the following extensions are allowed: <em class="placeholder">jpg|png</em>.', (string) $result->get(1)->getMessage());
}
/**
* Provides a list of file types to test.
*/
public function getFileTypes() {
return [['file'], ['image']];
}
}

View 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;
}
}

View file

@ -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']);
}
}
}

View 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.');
}
}
}

View file

@ -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');
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace Drupal\Tests\file\Kernel\Migrate\d6;
use Drupal\migrate\Plugin\MigrationInterface;
/**
* 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']);
$this->executeMigration('d6_file');
}
/**
* {@inheritdoc}
*/
protected function prepareMigration(MigrationInterface $migration) {
// File migrations need a source_base_path.
// @see MigrateUpgradeRunBatch::run
$destination = $migration->getDestinationConfiguration();
if ($destination['plugin'] === 'entity:file') {
// Make sure we have a single trailing slash.
$source = $migration->getSourceConfiguration();
$source['site_path'] = 'core/modules/simpletest';
$source['constants']['source_base_path'] = \Drupal::root() . '/';
$migration->set('source', $source);
}
}
}

View file

@ -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('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());
}
}

View file

@ -0,0 +1,142 @@
<?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.
\Drupal::database()
->truncate($this->getMigration('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();
$this->executeMigration('d6_file');
$file = File::load(2);
$this->assertIdentical('public://core/modules/simpletest/files/image-2.jpg', $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;
}
}

View file

@ -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')));
}
}

View file

@ -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')));
}
}

View file

@ -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('')));
}
}

View file

@ -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')));
}
}

View file

@ -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);
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Drupal\Tests\file\Kernel\Migrate\d7;
use Drupal\config\Tests\SchemaCheckTestTrait;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Upgrade variables to file.settings.yml.
*
* @group migrate_drupal_7
*/
class MigrateFileConfigsTest extends MigrateDrupal7TestBase {
use SchemaCheckTestTrait;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->executeMigration('file_settings');
}
/**
* Tests migration of file variables to file.settings.yml.
*/
public function testFileSettings() {
$config = $this->config('file.settings');
$this->assertSame('textfield', $config->get('description.type'));
$this->assertSame(256, $config->get('description.length'));
$this->assertSame('sites/default/files/icons', $config->get('icon.directory'));
$this->assertConfigSchema(\Drupal::service('config.typed'), 'file.settings', $config->get());
}
}

View file

@ -0,0 +1,87 @@
<?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 {
public 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 source plugin's source_base_path configuration value, which
// would normally be set by the user running the migration.
$source = $migration->getSourceConfiguration();
$source['constants']['source_base_path'] = $fs->realpath('public://');
$migration->set('source', $source);
$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');
}
}

View file

@ -0,0 +1,32 @@
<?php
namespace Drupal\Tests\file\Kernel\Migrate\process\d6;
use Drupal\file\Plugin\migrate\process\d6\CckFile;
use Drupal\migrate\Plugin\Migration;
use Drupal\Tests\migrate_drupal\Kernel\MigrateDrupalTestBase;
/**
* Cck file field migration.
*
* @coversDefaultClass \Drupal\file\Plugin\migrate\process\d6\CckFile
*
* @group file
*/
class CckFileTest extends MigrateDrupalTestBase {
/**
* Tests configurability of file migration name.
*
* @covers ::__construct
*/
public function testConfigurableFileMigration() {
$migration = Migration::create($this->container, [], 'custom_migration', []);
$cck_file_migration = CckFile::create($this->container, ['migration' => 'custom_file'], 'custom_file', [], $migration);
$migration_plugin = $this->readAttribute($cck_file_migration, 'migrationPlugin');
$config = $this->readAttribute($migration_plugin, 'configuration');
$this->assertEquals($config['migration'], 'custom_file');
}
}

View file

@ -0,0 +1,160 @@
<?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()));
}
}

View file

@ -0,0 +1,57 @@
<?php
namespace Drupal\Tests\file\Kernel\Plugin\migrate\source\d6;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests D6 file source plugin.
*
* @covers \Drupal\file\Plugin\migrate\source\d6\File
*
* @group file
*/
class FileTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['file', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['files'] = [
[
'fid' => 1,
'uid' => 1,
'filename' => 'migrate-test-file-1.pdf',
'filepath' => 'sites/default/files/migrate-test-file-1.pdf',
'filemime' => 'application/pdf',
'filesize' => 890404,
'status' => 1,
'timestamp' => 1382255613,
],
[
'fid' => 2,
'uid' => 1,
'filename' => 'migrate-test-file-2.pdf',
'filepath' => 'sites/default/files/migrate-test-file-2.pdf',
'filemime' => 'application/pdf',
'filesize' => 204124,
'status' => 1,
'timestamp' => 1382255662,
],
];
// The expected results are identical to the source data.
$tests[0]['expected_data'] = $tests[0]['source_data']['files'];
return $tests;
}
}

View file

@ -0,0 +1,68 @@
<?php
namespace Drupal\Tests\file\Kernel\Plugin\migrate\source\d6;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests D6 d6_upload_instance source plugin.
*
* @covers \Drupal\file\Plugin\migrate\source\d6\UploadInstance
*
* @group file
*/
class UploadInstanceTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['file', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['node_type'] = [
[
'type' => 'article',
],
[
'type' => 'company',
],
];
$tests[0]['source_data']['variable'] = [
[
'name' => 'upload_article',
'value' => serialize(TRUE),
],
[
'name' => 'upload_company',
'value' => serialize(FALSE),
],
[
'name' => 'upload_uploadsize_default',
'value' => serialize(16),
],
[
'name' => 'upload_extensions_default',
'value' => serialize('txt pdf'),
],
];
// The expected results.
$tests[0]['expected_data'] = [
[
'node_type' => 'article',
'max_filesize' => '16MB',
'file_extensions' => 'txt pdf',
],
];
return $tests;
}
}

View file

@ -0,0 +1,78 @@
<?php
namespace Drupal\Tests\file\Kernel\Plugin\migrate\source\d6;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests D6 d6_upload source plugin.
*
* @covers \Drupal\file\Plugin\migrate\source\d6\Upload
*
* @group file
*/
class UploadTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['file', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['upload'] = [
[
'fid' => '1',
'nid' => '1',
'vid' => '1',
'description' => 'file 1-1-1',
'list' => '0',
'weight' => '-1',
],
];
$tests[0]['source_data']['node'] = [
[
'nid' => '1',
'vid' => '1',
'type' => 'story',
'language' => '',
'title' => 'Test title',
'uid' => '1',
'status' => '1',
'created' => '1388271197',
'changed' => '1420861423',
'comment' => '0',
'promote' => '0',
'moderate' => '0',
'sticky' => '0',
'tnid' => '0',
'translate' => '0',
],
];
// The expected results.
$tests[0]['expected_data'] = [
[
'upload' => [
[
'fid' => '1',
'description' => 'file 1-1-1',
'list' => '0',
],
],
'nid' => '1',
'vid' => '1',
'type' => 'story',
],
];
return $tests;
}
}

View file

@ -0,0 +1,112 @@
<?php
namespace Drupal\Tests\file\Kernel\Plugin\migrate\source\d7;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests D7 file source plugin.
*
* @covers \Drupal\file\Plugin\migrate\source\d7\File
* @group file
*/
class FileTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['file', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [];
$tests[0]['source_data']['file_managed'] = [
// A public file.
[
'fid' => '1',
'uid' => '1',
'filename' => 'cube.jpeg',
'uri' => 'public://cube.jpeg',
'filemime' => 'image/jpeg',
'filesize' => '3620',
'status' => '1',
'timestamp' => '1421727515',
],
// A private file.
[
'fid' => '1',
'uid' => '1',
'filename' => 'cube.jpeg',
'uri' => 'private://cube.jpeg',
'filemime' => 'image/jpeg',
'filesize' => '3620',
'status' => '1',
'timestamp' => '1421727515',
],
// A temporary file.
[
'fid' => '1',
'uid' => '1',
'filename' => 'cube.jpeg',
'uri' => 'temporary://cube.jpeg',
'filemime' => 'image/jpeg',
'filesize' => '3620',
'status' => '1',
'timestamp' => '1421727515',
],
// A file with a URI scheme that will be filtered out.
[
'fid' => '1',
'uid' => '1',
'filename' => 'cube.jpeg',
'uri' => 'null://cube.jpeg',
'filemime' => 'image/jpeg',
'filesize' => '3620',
'status' => '1',
'timestamp' => '1421727515',
],
];
$tests[0]['source_data']['variable'] = [
[
'name' => 'file_public_path',
'value' => serialize('sites/default/files'),
],
[
'name' => 'file_private_path',
'value' => serialize('/path/to/private/files'),
],
[
'name' => 'file_temporary_path',
'value' => serialize('/tmp'),
],
];
// The expected results will include only the first three files, since we
// are configuring the plugin to filter out the file with the null URI
// scheme.
$tests[0]['expected_data'] = array_slice($tests[0]['source_data']['file_managed'], 0, 3);
// The filepath property will vary by URI scheme.
$tests[0]['expected_data'][0]['filepath'] = 'sites/default/files/cube.jpeg';
$tests[0]['expected_data'][1]['filepath'] = '/path/to/private/files/cube.jpeg';
$tests[0]['expected_data'][2]['filepath'] = '/tmp/cube.jpeg';
// Do an automatic count.
$tests[0]['expected_count'] = NULL;
// Set up plugin configuration.
$tests[0]['configuration'] = [
'constants' => [
'source_base_path' => '/path/to/files',
],
// Only return files which use one of these URI schemes.
'scheme' => ['public', 'private', 'temporary'],
];
return $tests;
}
}

View file

@ -0,0 +1,134 @@
<?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()));
}
}

View file

@ -0,0 +1,86 @@
<?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);
}
}

View file

@ -0,0 +1,75 @@
<?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);
}
}

View file

@ -0,0 +1,266 @@
<?php
namespace Drupal\Tests\file\Kernel;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\language\Entity\ContentLanguageSettings;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
/**
* 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.');
}
/**
* Tests file usage with translated entities.
*/
public function testFileUsageWithEntityTranslation() {
/** @var \Drupal\file\FileUsage\FileUsageInterface $file_usage */
$file_usage = $this->container->get('file.usage');
$this->enableModules(['node', 'language']);
$this->installEntitySchema('node');
$this->installSchema('node', ['node_access']);
// Activate English and Romanian languages.
ConfigurableLanguage::create(['id' => 'en'])->save();
ConfigurableLanguage::create(['id' => 'ro'])->save();
NodeType::create(['type' => 'page'])->save();
ContentLanguageSettings::loadByEntityTypeBundle('node', 'page')
->setLanguageAlterable(FALSE)
->setDefaultLangcode('en')
->save();
// Create a file field attached to 'page' node-type.
FieldStorageConfig::create([
'type' => 'file',
'entity_type' => 'node',
'field_name' => 'file',
])->save();
FieldConfig::create([
'entity_type' => 'node',
'bundle' => 'page',
'field_name' => 'file',
'label' => 'File',
])->save();
// Create a node, attach a file and add a Romanian translation.
$node = Node::create(['type' => 'page', 'title' => 'Page']);
$node
->set('file', $file = $this->createFile())
->addTranslation('ro', $node->getTranslation('en')->toArray())
->save();
// Check that the file is used twice.
$usage = $file_usage->listUsage($file);
$this->assertEquals(2, $usage['file']['node'][$node->id()]);
// Remove the Romanian translation.
$node->removeTranslation('ro');
$node->save();
// Check that one usage has been removed and is used only once now.
$usage = $file_usage->listUsage($file);
$this->assertEquals(1, $usage['file']['node'][$node->id()]);
}
}

View file

@ -0,0 +1,38 @@
<?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'));
}
}

View file

@ -0,0 +1,157 @@
<?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');
}
}

View 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]), '');
});
}
}

View file

@ -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));
}
}

View file

@ -0,0 +1,51 @@
<?php
namespace Drupal\Tests\file\Unit\Plugin\migrate\process\d6;
use Drupal\file\Plugin\migrate\process\d6\CckFile;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Plugin\MigrateProcessInterface;
use Drupal\migrate\Row;
use Drupal\Tests\UnitTestCase;
/**
* @group file
*/
class CckFileTest extends UnitTestCase {
/**
* Tests that alt and title attributes are included in transformed values.
*/
public function testTransformAltTitle() {
$executable = $this->prophesize(MigrateExecutableInterface::class)->reveal();
$row = $this->prophesize(Row::class)->reveal();
$migration = $this->prophesize(MigrationInterface::class)->reveal();
$migration_plugin = $this->prophesize(MigrateProcessInterface::class);
$migration_plugin->transform(1, $executable, $row, 'foo')->willReturn(1);
$plugin = new CckFile(array(), 'd6_cck_file', array(), $migration, $migration_plugin->reveal());
$options = array(
'alt' => 'Foobaz',
'title' => 'Wambooli',
);
$value = array(
'fid' => 1,
'list' => TRUE,
'data' => serialize($options),
);
$transformed = $plugin->transform($value, $executable, $row, 'foo');
$expected = array(
'target_id' => 1,
'display' => TRUE,
'description' => '',
'alt' => 'Foobaz',
'title' => 'Wambooli',
);
$this->assertSame($expected, $transformed);
}
}

View file

@ -0,0 +1,79 @@
<?php
namespace Drupal\Tests\file\Unit\Plugin\migrate\process\d6;
use Drupal\file\Plugin\migrate\process\d6\FileUri;
use Drupal\migrate\MigrateExecutable;
use Drupal\migrate\MigrateMessage;
use Drupal\migrate\Row;
use Drupal\Tests\migrate\Unit\MigrateTestCase;
/**
* @coversDefaultClass \Drupal\file\Plugin\migrate\process\d6\FileUri
* @group file
*/
class FileUriTest extends MigrateTestCase {
protected $migrationConfiguration = [
'id' => 'test',
];
public function testPublic() {
$value = [
'sites/default/files/foo.jpg',
'sites/default/files',
'/tmp',
TRUE,
];
$this->assertEquals('public://foo.jpg', $this->doTransform($value));
}
public function testPublicUnknownBasePath() {
$value = [
'/path/to/public/files/foo.jpg',
'sites/default/files',
'/tmp',
TRUE,
];
$this->assertEquals('public://path/to/public/files/foo.jpg', $this->doTransform($value));
}
public function testPrivate() {
$value = [
'sites/default/files/baz.gif',
'sites/default/files',
'/tmp',
FALSE,
];
$this->assertEquals('private://baz.gif', $this->doTransform($value));
}
public function testPrivateUnknownBasePath() {
$value = [
'/path/to/private/files/baz.gif',
'sites/default/files',
'/tmp',
FALSE,
];
$this->assertEquals('private://path/to/private/files/baz.gif', $this->doTransform($value));
}
public function testTemporary() {
$value = [
'/tmp/bar.png',
'sites/default/files',
'/tmp',
TRUE,
];
$this->assertEquals('temporary://bar.png', $this->doTransform($value));
}
protected function doTransform(array $value) {
$executable = new MigrateExecutable($this->getMigration(), new MigrateMessage());
$row = new Row();
return (new FileUri([], 'file_uri', []))
->transform($value, $executable, $row, 'foobaz');
}
}