Update core 8.3.0

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

View file

@ -36,7 +36,7 @@ class FileModuleTestForm extends FormBase {
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(
$form['nested']['file'] = [
'#type' => 'managed_file',
'#title' => $this->t('Managed <em>@type</em>', ['@type' => 'file & butter']),
'#upload_location' => 'public://test',
@ -44,21 +44,21 @@ class FileModuleTestForm extends FormBase {
'#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['nested']['file']['#default_value'] = $extended ? ['fids' => $default_fids] : $default_fids;
}
$form['textfield'] = array(
$form['textfield'] = [
'#type' => 'textfield',
'#title' => $this->t('Type a value and ensure it stays'),
);
];
$form['submit'] = array(
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save'),
);
];
return $form;
}
@ -68,7 +68,7 @@ class FileModuleTestForm extends FormBase {
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
if ($form['#tree']) {
$uploads = $form_state->getValue(array('nested', 'file'));
$uploads = $form_state->getValue(['nested', 'file']);
}
else {
$uploads = $form_state->getValue('file');
@ -78,12 +78,12 @@ class FileModuleTestForm extends FormBase {
$uploads = $uploads['fids'];
}
$fids = array();
$fids = [];
foreach ($uploads as $fid) {
$fids[] = $fid;
}
drupal_set_message($this->t('The file ids are %fids.', array('%fids' => implode(',', $fids))));
drupal_set_message($this->t('The file ids are %fids.', ['%fids' => implode(',', $fids)]));
}
}

View file

@ -21,23 +21,23 @@ const FILE_URL_TEST_CDN_2 = 'http://cdn2.example.com';
*/
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(),
);
$results = [
'load' => [],
'validate' => [],
'download' => [],
'insert' => [],
'update' => [],
'copy' => [],
'move' => [],
'delete' => [],
];
\Drupal::state()->set('file_test.results', $results);
// These hooks will return these values, see file_test_set_return().
$return = array(
'validate' => array(),
$return = [
'validate' => [],
'download' => NULL,
);
];
\Drupal::state()->set('file_test.return', $return);
}
@ -56,7 +56,7 @@ function file_test_reset() {
* @see file_test_reset()
*/
function file_test_get_calls($op) {
$results = \Drupal::state()->get('file_test.results') ?: array();
$results = \Drupal::state()->get('file_test.results') ?: [];
return $results[$op];
}
@ -69,7 +69,7 @@ function file_test_get_calls($op) {
* passed to each call.
*/
function file_test_get_all_calls() {
return \Drupal::state()->get('file_test.results') ?: array();
return \Drupal::state()->get('file_test.results') ?: [];
}
/**
@ -86,7 +86,7 @@ function file_test_get_all_calls() {
*/
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 = \Drupal::state()->get('file_test.results') ?: [];
$results[$op][] = $args;
\Drupal::state()->set('file_test.results', $results);
}
@ -105,7 +105,7 @@ function _file_test_log_call($op, $args) {
* @see file_test_reset()
*/
function _file_test_get_return($op) {
$return = \Drupal::state()->get('file_test.return') ?: array($op => NULL);
$return = \Drupal::state()->get('file_test.return') ?: [$op => NULL];
return $return[$op];
}
@ -121,7 +121,7 @@ function _file_test_get_return($op) {
* @see file_test_reset()
*/
function file_test_set_return($op, $value) {
$return = \Drupal::state()->get('file_test.return') ?: array();
$return = \Drupal::state()->get('file_test.return') ?: [];
$return[$op] = $value;
\Drupal::state()->set('file_test.return', $return);
}
@ -131,7 +131,7 @@ function file_test_set_return($op, $value) {
*/
function file_test_file_load($files) {
foreach ($files as $file) {
_file_test_log_call('load', array($file->id()));
_file_test_log_call('load', [$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;
@ -142,7 +142,7 @@ function file_test_file_load($files) {
* Implements hook_file_validate().
*/
function file_test_file_validate(File $file) {
_file_test_log_call('validate', array($file->id()));
_file_test_log_call('validate', [$file->id()]);
return _file_test_get_return('validate');
}
@ -151,11 +151,11 @@ function file_test_file_validate(File $file) {
*/
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));
$files = entity_load_multiple_by_properties('file', ['uri' => $uri]);
$file = reset($files);
return file_get_content_headers($file);
}
_file_test_log_call('download', array($uri));
_file_test_log_call('download', [$uri]);
return _file_test_get_return('download');
}
@ -163,35 +163,35 @@ function file_test_file_download($uri) {
* Implements hook_ENTITY_TYPE_insert() for file entities.
*/
function file_test_file_insert(File $file) {
_file_test_log_call('insert', array($file->id()));
_file_test_log_call('insert', [$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()));
_file_test_log_call('update', [$file->id()]);
}
/**
* Implements hook_file_copy().
*/
function file_test_file_copy(File $file, $source) {
_file_test_log_call('copy', array($file->id(), $source->id()));
_file_test_log_call('copy', [$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()));
_file_test_log_call('move', [$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()));
_file_test_log_call('delete', [$file->id()]);
}
/**
@ -206,11 +206,11 @@ function file_test_file_url_alter(&$uri) {
}
// Test alteration of file URLs to use a CDN.
elseif ($alter_mode == 'cdn') {
$cdn_extensions = array('css', 'js', 'gif', 'jpg', 'jpeg', 'png');
$cdn_extensions = ['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');
$schemes = ['public'];
$scheme = file_uri_scheme($uri);
@ -323,7 +323,7 @@ function file_test_validator(File $file, $errors) {
* If $filepath is NULL, an array of all previous $filepath parameters
*/
function file_test_file_scan_callback($filepath = NULL) {
$files = &drupal_static(__FUNCTION__, array());
$files = &drupal_static(__FUNCTION__, []);
if (isset($filepath)) {
$files[] = $filepath;
}

View file

@ -21,48 +21,48 @@ class FileTestForm implements FormInterface {
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['file_test_upload'] = array(
$form['file_test_upload'] = [
'#type' => 'file',
'#title' => t('Upload a file'),
);
$form['file_test_replace'] = array(
];
$form['file_test_replace'] = [
'#type' => 'select',
'#title' => t('Replace existing image'),
'#options' => array(
'#options' => [
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(
];
$form['file_subdir'] = [
'#type' => 'textfield',
'#title' => t('Subdirectory for test file'),
'#default_value' => '',
);
];
$form['extensions'] = array(
$form['extensions'] = [
'#type' => 'textfield',
'#title' => t('Allowed extensions.'),
'#default_value' => '',
);
];
$form['allow_all_extensions'] = array(
$form['allow_all_extensions'] = [
'#type' => 'checkbox',
'#title' => t('Allow all extensions?'),
'#default_value' => FALSE,
);
];
$form['is_image_file'] = array(
$form['is_image_file'] = [
'#type' => 'checkbox',
'#title' => t('Is this an image file?'),
'#default_value' => TRUE,
);
];
$form['submit'] = array(
$form['submit'] = [
'#type' => 'submit',
'#value' => t('Submit'),
);
];
return $form;
}
@ -86,16 +86,16 @@ class FileTestForm implements FormInterface {
}
// Setup validators.
$validators = array();
$validators = [];
if ($form_state->getValue('is_image_file')) {
$validators['file_validate_is_image'] = array();
$validators['file_validate_is_image'] = [];
}
if ($form_state->getValue('allow_all_extensions')) {
$validators['file_validate_extensions'] = array();
$validators['file_validate_extensions'] = [];
}
elseif (!$form_state->isValueEmpty('extensions')) {
$validators['file_validate_extensions'] = array($form_state->getValue('extensions'));
$validators['file_validate_extensions'] = [$form_state->getValue('extensions')];
}
// The test for drupal_move_uploaded_file() triggering a warning is
@ -108,9 +108,9 @@ class FileTestForm implements FormInterface {
$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('File @filepath was uploaded.', ['@filepath' => $file->getFileUri()]));
drupal_set_message(t('File name is @filename.', ['@filename' => $file->getFilename()]));
drupal_set_message(t('File MIME type is @mimetype.', ['@mimetype' => $file->getMimeType()]));
drupal_set_message(t('You WIN!'));
}
elseif ($file === FALSE) {

View file

@ -25,7 +25,7 @@ class DummyReadOnlyStreamWrapper extends LocalReadOnlyStream {
return t('Dummy wrapper for simpletest (readonly).');
}
function getDirectoryPath() {
public function getDirectoryPath() {
return \Drupal::service('site.path') . '/files';
}
@ -34,7 +34,7 @@ class DummyReadOnlyStreamWrapper extends LocalReadOnlyStream {
*
* Return a dummy path for testing.
*/
function getInternalUri() {
public function getInternalUri() {
return '/dummy/example.txt';
}
@ -43,7 +43,7 @@ class DummyReadOnlyStreamWrapper extends LocalReadOnlyStream {
*
* Return the HTML URI of a public file.
*/
function getExternalUrl() {
public function getExternalUrl() {
return '/dummy/example.txt';
}

View file

@ -27,7 +27,7 @@ class DummyRemoteStreamWrapper extends PublicStream {
return t('Dummy wrapper for simpletest (remote).');
}
function realpath() {
public function realpath() {
return FALSE;
}

View file

@ -25,7 +25,7 @@ class DummyStreamWrapper extends LocalStream {
return t('Dummy wrapper for simpletest.');
}
function getDirectoryPath() {
public function getDirectoryPath() {
return \Drupal::service('site.path') . '/files';
}
@ -34,7 +34,7 @@ class DummyStreamWrapper extends LocalStream {
*
* Return a dummy path for testing.
*/
function getInternalUri() {
public function getInternalUri() {
return '/dummy/example.txt';
}
@ -43,7 +43,7 @@ class DummyStreamWrapper extends LocalStream {
*
* Return the HTML URI of a public file.
*/
function getExternalUrl() {
public function getExternalUrl() {
return '/dummy/example.txt';
}

View file

@ -0,0 +1,320 @@
<?php
namespace Drupal\Tests\file\Functional;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\file\FileInterface;
use Drupal\Tests\BrowserTestBase;
use Drupal\file\Entity\File;
/**
* Provides methods specifically for testing File module's field handling.
*/
abstract class FileFieldTestBase extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['node', 'file', 'file_module_test', 'field_ui'];
/**
* An user with administration permissions.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
protected function setUp() {
parent::setUp();
$this->adminUser = $this->drupalCreateUser(['access content', 'access administration pages', 'administer site configuration', 'administer users', 'administer permissions', 'administer content types', 'administer node fields', 'administer node display', 'administer nodes', 'bypass node access']);
$this->drupalLogin($this->adminUser);
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
}
/**
* Retrieves a sample file of the specified type.
*
* @return \Drupal\file\FileInterface
*/
public function getTestFile($type_name, $size = NULL) {
// Get a file to upload.
$file = current($this->drupalGetTestFiles($type_name, $size));
// Add a filesize property to files as would be read by
// \Drupal\file\Entity\File::load().
$file->filesize = filesize($file->uri);
return File::create((array) $file);
}
/**
* Retrieves the fid of the last inserted file.
*/
public function getLastFileId() {
return (int) db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField();
}
/**
* Creates a new file field.
*
* @param string $name
* The name of the new field (all lowercase), exclude the "field_" prefix.
* @param string $entity_type
* The entity type.
* @param string $bundle
* The bundle that this field will be added to.
* @param array $storage_settings
* A list of field storage settings that will be added to the defaults.
* @param array $field_settings
* A list of instance settings that will be added to the instance defaults.
* @param array $widget_settings
* A list of widget settings that will be added to the widget defaults.
*/
public function createFileField($name, $entity_type, $bundle, $storage_settings = [], $field_settings = [], $widget_settings = []) {
$field_storage = FieldStorageConfig::create([
'entity_type' => $entity_type,
'field_name' => $name,
'type' => 'file',
'settings' => $storage_settings,
'cardinality' => !empty($storage_settings['cardinality']) ? $storage_settings['cardinality'] : 1,
]);
$field_storage->save();
$this->attachFileField($name, $entity_type, $bundle, $field_settings, $widget_settings);
return $field_storage;
}
/**
* Attaches a file field to an entity.
*
* @param string $name
* The name of the new field (all lowercase), exclude the "field_" prefix.
* @param string $entity_type
* The entity type this field will be added to.
* @param string $bundle
* The bundle this field will be added to.
* @param array $field_settings
* A list of field settings that will be added to the defaults.
* @param array $widget_settings
* A list of widget settings that will be added to the widget defaults.
*/
public function attachFileField($name, $entity_type, $bundle, $field_settings = [], $widget_settings = []) {
$field = [
'field_name' => $name,
'label' => $name,
'entity_type' => $entity_type,
'bundle' => $bundle,
'required' => !empty($field_settings['required']),
'settings' => $field_settings,
];
FieldConfig::create($field)->save();
entity_get_form_display($entity_type, $bundle, 'default')
->setComponent($name, [
'type' => 'file_generic',
'settings' => $widget_settings,
])
->save();
// Assign display settings.
entity_get_display($entity_type, $bundle, 'default')
->setComponent($name, [
'label' => 'hidden',
'type' => 'file_default',
])
->save();
}
/**
* Updates an existing file field with new settings.
*/
public function updateFileField($name, $type_name, $field_settings = [], $widget_settings = []) {
$field = FieldConfig::loadByName('node', $type_name, $name);
$field->setSettings(array_merge($field->getSettings(), $field_settings));
$field->save();
entity_get_form_display('node', $type_name, 'default')
->setComponent($name, [
'settings' => $widget_settings,
])
->save();
}
/**
* Uploads a file to a node.
*
* @param \Drupal\file\FileInterface $file
* The File to be uploaded.
* @param string $field_name
* The name of the field on which the files should be saved.
* @param $nid_or_type
* A numeric node id to upload files to an existing node, or a string
* indicating the desired bundle for a new node.
* @param bool $new_revision
* The revision number.
* @param array $extras
* Additional values when a new node is created.
*
* @return int
* The node id.
*/
public function uploadNodeFile(FileInterface $file, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = []) {
return $this->uploadNodeFiles([$file], $field_name, $nid_or_type, $new_revision, $extras);
}
/**
* Uploads multiple files to a node.
*
* @param \Drupal\file\FileInterface[] $files
* The files to be uploaded.
* @param string $field_name
* The name of the field on which the files should be saved.
* @param $nid_or_type
* A numeric node id to upload files to an existing node, or a string
* indicating the desired bundle for a new node.
* @param bool $new_revision
* The revision number.
* @param array $extras
* Additional values when a new node is created.
*
* @return int
* The node id.
*/
public function uploadNodeFiles(array $files, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = []) {
$edit = [
'title[0][value]' => $this->randomMachineName(),
'revision' => (string) (int) $new_revision,
];
$node_storage = $this->container->get('entity.manager')->getStorage('node');
if (is_numeric($nid_or_type)) {
$nid = $nid_or_type;
$node_storage->resetCache([$nid]);
$node = $node_storage->load($nid);
}
else {
// Add a new node.
$extras['type'] = $nid_or_type;
$node = $this->drupalCreateNode($extras);
$nid = $node->id();
// Save at least one revision to better simulate a real site.
$node->setNewRevision();
$node->save();
$node_storage->resetCache([$nid]);
$node = $node_storage->load($nid);
$this->assertNotEqual($nid, $node->getRevisionId(), 'Node revision exists.');
}
// Attach files to the node.
$field_storage = FieldStorageConfig::loadByName('node', $field_name);
// File input name depends on number of files already uploaded.
$field_num = count($node->{$field_name});
$name = 'files[' . $field_name . "_$field_num]";
if ($field_storage->getCardinality() != 1) {
$name .= '[]';
}
foreach ($files as $file) {
$file_path = $this->container->get('file_system')->realpath($file->getFileUri());
if (count($files) == 1) {
$edit[$name] = $file_path;
}
else {
$edit[$name][] = $file_path;
}
}
$this->drupalPostForm("node/$nid/edit", $edit, t('Save and keep published'));
return $nid;
}
/**
* Removes a file from a node.
*
* Note that if replacing a file, it must first be removed then added again.
*/
public function removeNodeFile($nid, $new_revision = TRUE) {
$edit = [
'revision' => (string) (int) $new_revision,
];
$this->drupalPostForm('node/' . $nid . '/edit', [], t('Remove'));
$this->drupalPostForm(NULL, $edit, t('Save and keep published'));
}
/**
* Replaces a file within a node.
*/
public function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
$edit = [
'files[' . $field_name . '_0]' => drupal_realpath($file->getFileUri()),
'revision' => (string) (int) $new_revision,
];
$this->drupalPostForm('node/' . $nid . '/edit', [], t('Remove'));
$this->drupalPostForm(NULL, $edit, t('Save and keep published'));
}
/**
* Asserts that a file exists physically on disk.
*
* Overrides PHPUnit_Framework_Assert::assertFileExists() to also work with
* file entities.
*
* @param \Drupal\File\FileInterface|string $file
* Either the file entity or the file URI.
* @param string $message
* (optional) A message to display with the assertion.
*/
public static function assertFileExists($file, $message = NULL) {
$message = isset($message) ? $message : format_string('File %file exists on the disk.', ['%file' => $file->getFileUri()]);
$filename = $file instanceof FileInterface ? $file->getFileUri() : $file;
parent::assertFileExists($filename, $message);
}
/**
* Asserts that a file exists in the database.
*/
public function assertFileEntryExists($file, $message = NULL) {
$this->container->get('entity.manager')->getStorage('file')->resetCache();
$db_file = File::load($file->id());
$message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', ['%file' => $file->getFileUri()]);
$this->assertEqual($db_file->getFileUri(), $file->getFileUri(), $message);
}
/**
* Asserts that a file does not exist on disk.
*
* Overrides PHPUnit_Framework_Assert::assertFileExists() to also work with
* file entities.
*
* @param \Drupal\File\FileInterface|string $file
* Either the file entity or the file URI.
* @param string $message
* (optional) A message to display with the assertion.
*/
public static function assertFileNotExists($file, $message = NULL) {
$message = isset($message) ? $message : format_string('File %file exists on the disk.', ['%file' => $file->getFileUri()]);
$filename = $file instanceof FileInterface ? $file->getFileUri() : $file;
parent::assertFileNotExists($filename, $message);
}
/**
* Asserts that a file does not exist in the database.
*/
public function assertFileEntryNotExists($file, $message) {
$this->container->get('entity.manager')->getStorage('file')->resetCache();
$message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', ['%file' => $file->getFileUri()]);
$this->assertFalse(File::load($file->id()), $message);
}
/**
* Asserts that a file's status is set to permanent in the database.
*/
public function assertFileIsPermanent(FileInterface $file, $message = NULL) {
$message = isset($message) ? $message : format_string('File %file is permanent.', ['%file' => $file->getFileUri()]);
$this->assertTrue($file->isPermanent(), $message);
}
}

View file

@ -0,0 +1,69 @@
<?php
namespace Drupal\Tests\file\Functional;
use Drupal\file\Entity\File;
/**
* Tests access to managed files.
*
* @group file
*/
class FileManagedAccessTest extends FileManagedTestBase {
/**
* Tests if public file is always accessible.
*/
public function testFileAccess() {
// Create a new file entity.
$file = File::create([
'uid' => 1,
'filename' => 'drupal.txt',
'uri' => 'public://drupal.txt',
'filemime' => 'text/plain',
'status' => FILE_STATUS_PERMANENT,
]);
file_put_contents($file->getFileUri(), 'hello world');
// Save it, inserting a new record.
$file->save();
// Create authenticated user to check file access.
$account = $this->createUser(['access site reports']);
$this->assertTrue($file->access('view', $account), 'Public file is viewable to authenticated user');
$this->assertTrue($file->access('download', $account), 'Public file is downloadable to authenticated user');
// Create anonymous user to check file access.
$account = $this->createUser()->getAnonymousUser();
$this->assertTrue($file->access('view', $account), 'Public file is viewable to anonymous user');
$this->assertTrue($file->access('download', $account), 'Public file is downloadable to anonymous user');
// Create a new file entity.
$file = File::create([
'uid' => 1,
'filename' => 'drupal.txt',
'uri' => 'private://drupal.txt',
'filemime' => 'text/plain',
'status' => FILE_STATUS_PERMANENT,
]);
file_put_contents($file->getFileUri(), 'hello world');
// Save it, inserting a new record.
$file->save();
// Create authenticated user to check file access.
$account = $this->createUser(['access site reports']);
$this->assertFalse($file->access('view', $account), 'Private file is not viewable to authenticated user');
$this->assertFalse($file->access('download', $account), 'Private file is not downloadable to authenticated user');
// Create anonymous user to check file access.
$account = $this->createUser()->getAnonymousUser();
$this->assertFalse($file->access('view', $account), 'Private file is not viewable to anonymous user');
$this->assertFalse($file->access('download', $account), 'Private file is not downloadable to anonymous user');
}
}

View file

@ -0,0 +1,200 @@
<?php
namespace Drupal\Tests\file\Functional;
use Drupal\file\Entity\File;
use Drupal\file\FileInterface;
use Drupal\Tests\BrowserTestBase;
/**
* Base class for file tests that use the file_test module to test uploads and
* hooks.
*/
abstract class FileManagedTestBase extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['file_test', 'file'];
protected function setUp() {
parent::setUp();
// Clear out any hook calls.
file_test_reset();
}
/**
* Assert that all of the specified hook_file_* hooks were called once, other
* values result in failure.
*
* @param string[] $expected
* An array of strings containing with the hook name; for example, 'load',
* 'save', 'insert', etc.
*/
public 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.', ['%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled)]));
}
else {
$this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', ['%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.', ['%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; for instance, 'load', 'save', 'insert', etc.
* @param int $expected_count
* Optional integer count.
* @param string|null $message
* Optional translated string message.
*/
public 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.', ['@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.', ['@name' => $hook, '@count' => $actual_count]);
}
else {
$message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', ['@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.
*/
public function assertFileUnchanged(FileInterface $before, FileInterface $after) {
$this->assertEqual($before->id(), $after->id(), t('File id is the same: %file1 == %file2.', ['%file1' => $before->id(), '%file2' => $after->id()]), 'File unchanged');
$this->assertEqual($before->getOwner()->id(), $after->getOwner()->id(), t('File owner is the same: %file1 == %file2.', ['%file1' => $before->getOwner()->id(), '%file2' => $after->getOwner()->id()]), 'File unchanged');
$this->assertEqual($before->getFilename(), $after->getFilename(), t('File name is the same: %file1 == %file2.', ['%file1' => $before->getFilename(), '%file2' => $after->getFilename()]), 'File unchanged');
$this->assertEqual($before->getFileUri(), $after->getFileUri(), t('File path is the same: %file1 == %file2.', ['%file1' => $before->getFileUri(), '%file2' => $after->getFileUri()]), 'File unchanged');
$this->assertEqual($before->getMimeType(), $after->getMimeType(), t('File MIME type is the same: %file1 == %file2.', ['%file1' => $before->getMimeType(), '%file2' => $after->getMimeType()]), 'File unchanged');
$this->assertEqual($before->getSize(), $after->getSize(), t('File size is the same: %file1 == %file2.', ['%file1' => $before->getSize(), '%file2' => $after->getSize()]), 'File unchanged');
$this->assertEqual($before->isPermanent(), $after->isPermanent(), t('File status is the same: %file1 == %file2.', ['%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.
*/
public function assertDifferentFile(FileInterface $file1, FileInterface $file2) {
$this->assertNotEqual($file1->id(), $file2->id(), t('Files have different ids: %file1 != %file2.', ['%file1' => $file1->id(), '%file2' => $file2->id()]), 'Different file');
$this->assertNotEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have different paths: %file1 != %file2.', ['%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.
*/
public function assertSameFile(FileInterface $file1, FileInterface $file2) {
$this->assertEqual($file1->id(), $file2->id(), t('Files have the same ids: %file1 == %file2.', ['%file1' => $file1->id(), '%file2-fid' => $file2->id()]), 'Same file');
$this->assertEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have the same path: %file1 == %file2.', ['%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.
*/
public 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.
*/
public 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

@ -49,7 +49,7 @@ class AccessTest extends KernelTestBase {
$this->installEntitySchema('file');
$this->installEntitySchema('user');
$this->installSchema('file', array('file_usage'));
$this->installSchema('file', ['file_usage']);
$this->installSchema('system', 'sequences');
$this->user1 = User::create([
@ -64,11 +64,11 @@ class AccessTest extends KernelTestBase {
]);
$this->user2->save();
$this->file = File::create(array(
$this->file = File::create([
'uid' => $this->user1->id(),
'filename' => 'druplicon.txt',
'filemime' => 'text/plain',
));
]);
}
/**

View file

@ -13,7 +13,7 @@ class CopyTest extends FileManagedUnitTestBase {
/**
* Test file copying in the normal, base case.
*/
function testNormal() {
public function testNormal() {
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
$desired_uri = 'public://' . $this->randomMachineName();
@ -27,7 +27,7 @@ class CopyTest extends FileManagedUnitTestBase {
$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->assertFileHooksCalled(['copy', 'insert']);
$this->assertDifferentFile($source, $result);
$this->assertEqual($result->getFileUri(), $desired_uri, 'The copied file entity has the desired filepath.');
@ -42,7 +42,7 @@ class CopyTest extends FileManagedUnitTestBase {
/**
* Test renaming when copying over a file that already exists.
*/
function testExistingRename() {
public function testExistingRename() {
// Setup a file to overwrite.
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
@ -59,7 +59,7 @@ class CopyTest extends FileManagedUnitTestBase {
$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'));
$this->assertFileHooksCalled(['copy', 'insert']);
// Load all the affected files to check the changes that actually made it
// to the database.
@ -82,7 +82,7 @@ class CopyTest extends FileManagedUnitTestBase {
/**
* Test replacement when copying over a file that already exists.
*/
function testExistingReplace() {
public function testExistingReplace() {
// Setup a file to overwrite.
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
@ -99,7 +99,7 @@ class CopyTest extends FileManagedUnitTestBase {
$this->assertDifferentFile($source, $result);
// Check that the correct hooks were called.
$this->assertFileHooksCalled(array('load', 'copy', 'update'));
$this->assertFileHooksCalled(['load', 'copy', 'update']);
// Load all the affected files to check the changes that actually made it
// to the database.
@ -121,7 +121,7 @@ class CopyTest extends FileManagedUnitTestBase {
* Test that copying over an existing file fails when FILE_EXISTS_ERROR is
* specified.
*/
function testExistingError() {
public function testExistingError() {
$contents = $this->randomMachineName(10);
$source = $this->createFile();
$target = $this->createFile(NULL, $contents);
@ -136,7 +136,7 @@ class CopyTest extends FileManagedUnitTestBase {
$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->assertFileHooksCalled([]);
$this->assertFileUnchanged($source, File::load($source->id()));
$this->assertFileUnchanged($target, File::load($target->id()));

View file

@ -13,13 +13,13 @@ class DeleteTest extends FileManagedUnitTestBase {
/**
* Tries deleting a normal file (as opposed to a directory, symlink, etc).
*/
function testUnused() {
public 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->assertFileHooksCalled(['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.');
}
@ -27,7 +27,7 @@ class DeleteTest extends FileManagedUnitTestBase {
/**
* Tries deleting a file that is in use.
*/
function testInUse() {
public function testInUse() {
$file = $this->createFile();
$file_usage = $this->container->get('file.usage');
$file_usage->add($file, 'testing', 'test', 1);
@ -35,7 +35,7 @@ class DeleteTest extends FileManagedUnitTestBase {
$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->assertEqual($usage['testing']['test'], [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.');
@ -44,7 +44,7 @@ class DeleteTest extends FileManagedUnitTestBase {
$file_usage->delete($file, 'testing', 'test', 1);
$usage = $file_usage->listUsage($file);
$this->assertFileHooksCalled(array('load', 'update'));
$this->assertFileHooksCalled(['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());
@ -56,15 +56,15 @@ class DeleteTest extends FileManagedUnitTestBase {
// of the file is older than the system.file.temporary_maximum_age
// configuration value.
db_update('file_managed')
->fields(array(
->fields([
'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->assertFileHooksCalled(['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

@ -23,7 +23,7 @@ class FileItemTest extends FieldKernelTestBase {
*
* @var array
*/
public static $modules = array('file');
public static $modules = ['file'];
/**
* Created file entity.
@ -43,20 +43,20 @@ class FileItemTest extends FieldKernelTestBase {
parent::setUp();
$this->installEntitySchema('file');
$this->installSchema('file', array('file_usage'));
$this->installSchema('file', ['file_usage']);
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => 'file_test',
'entity_type' => 'entity_test',
'type' => 'file',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
))->save();
])->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),
'settings' => ['file_directory' => $this->directory],
])->save();
file_put_contents('public://example.txt', $this->randomMachineName());
$this->file = File::create([
@ -131,7 +131,7 @@ class FileItemTest extends FieldKernelTestBase {
'weight' => 1,
])->save();
$entity = EntityTest::create();
$entity->file_test = array('entity' => $file3);
$entity->file_test = ['entity' => $file3];
$uri = $file3->getFileUri();
$output = entity_view($entity, 'default');
\Drupal::service('renderer')->renderRoot($output);

View file

@ -18,17 +18,17 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
*
* @var array
*/
public static $modules = array('file_test', 'file', 'system', 'field', 'user');
public static $modules = ['file_test', 'file', 'system', 'field', 'user'];
protected function setUp() {
parent::setUp();
// Clear out any hook calls.
file_test_reset();
$this->installConfig(array('system'));
$this->installConfig(['system']);
$this->installEntitySchema('file');
$this->installEntitySchema('user');
$this->installSchema('file', array('file_usage'));
$this->installSchema('file', ['file_usage']);
// Make sure that a user with uid 1 exists, self::createFile() relies on
// it.
@ -46,7 +46,7 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* Array with string containing with the hook name, e.g. 'load', 'save',
* 'insert', etc.
*/
function assertFileHooksCalled($expected) {
public function assertFileHooksCalled($expected) {
\Drupal::state()->resetCache();
// Determine which hooks were called.
@ -55,16 +55,16 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
// 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))));
$this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', ['%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))));
$this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', ['%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))));
$this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', ['%unexpected' => empty($unexpected) ? '(none)' : implode(', ', $unexpected)]));
}
else {
$this->assertTrue(TRUE, 'No unexpected hooks were called.');
@ -81,18 +81,18 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* @param string $message
* Optional translated string message.
*/
function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
public 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));
$message = format_string('hook_file_@name was called correctly.', ['@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));
$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.', ['@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));
$message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', ['@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count]);
}
}
$this->assertEqual($actual_count, $expected_count, $message);
@ -106,14 +106,14 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* @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');
public function assertFileUnchanged(FileInterface $before, FileInterface $after) {
$this->assertEqual($before->id(), $after->id(), t('File id is the same: %file1 == %file2.', ['%file1' => $before->id(), '%file2' => $after->id()]), 'File unchanged');
$this->assertEqual($before->getOwner()->id(), $after->getOwner()->id(), t('File owner is the same: %file1 == %file2.', ['%file1' => $before->getOwner()->id(), '%file2' => $after->getOwner()->id()]), 'File unchanged');
$this->assertEqual($before->getFilename(), $after->getFilename(), t('File name is the same: %file1 == %file2.', ['%file1' => $before->getFilename(), '%file2' => $after->getFilename()]), 'File unchanged');
$this->assertEqual($before->getFileUri(), $after->getFileUri(), t('File path is the same: %file1 == %file2.', ['%file1' => $before->getFileUri(), '%file2' => $after->getFileUri()]), 'File unchanged');
$this->assertEqual($before->getMimeType(), $after->getMimeType(), t('File MIME type is the same: %file1 == %file2.', ['%file1' => $before->getMimeType(), '%file2' => $after->getMimeType()]), 'File unchanged');
$this->assertEqual($before->getSize(), $after->getSize(), t('File size is the same: %file1 == %file2.', ['%file1' => $before->getSize(), '%file2' => $after->getSize()]), 'File unchanged');
$this->assertEqual($before->isPermanent(), $after->isPermanent(), t('File status is the same: %file1 == %file2.', ['%file1' => $before->isPermanent(), '%file2' => $after->isPermanent()]), 'File unchanged');
}
/**
@ -124,9 +124,9 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* @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');
public function assertDifferentFile(FileInterface $file1, FileInterface $file2) {
$this->assertNotEqual($file1->id(), $file2->id(), t('Files have different ids: %file1 != %file2.', ['%file1' => $file1->id(), '%file2' => $file2->id()]), 'Different file');
$this->assertNotEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have different paths: %file1 != %file2.', ['%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri()]), 'Different file');
}
/**
@ -137,9 +137,9 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* @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');
public function assertSameFile(FileInterface $file1, FileInterface $file2) {
$this->assertEqual($file1->id(), $file2->id(), t('Files have the same ids: %file1 == %file2.', ['%file1' => $file1->id(), '%file2-fid' => $file2->id()]), 'Same file');
$this->assertEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have the same path: %file1 == %file2.', ['%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri()]), 'Same file');
}
/**
@ -158,7 +158,7 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* @return \Drupal\file\FileInterface
* File entity.
*/
function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
public 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([
@ -190,7 +190,7 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* @return string
* File URI.
*/
function createUri($filepath = NULL, $contents = NULL, $scheme = NULL) {
public 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.

View file

@ -13,33 +13,33 @@ class LoadTest extends FileManagedUnitTestBase {
/**
* Try to load a non-existent file by fid.
*/
function testLoadMissingFid() {
public function testLoadMissingFid() {
$this->assertFalse(File::load(-1), 'Try to load an invalid fid fails.');
$this->assertFileHooksCalled(array());
$this->assertFileHooksCalled([]);
}
/**
* Try to load a non-existent file by URI.
*/
function testLoadMissingFilepath() {
$files = entity_load_multiple_by_properties('file', array('uri' => 'foobar://misc/druplicon.png'));
public function testLoadMissingFilepath() {
$files = entity_load_multiple_by_properties('file', ['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());
$this->assertFileHooksCalled([]);
}
/**
* Try to load a non-existent file by status.
*/
function testLoadInvalidStatus() {
$files = entity_load_multiple_by_properties('file', array('status' => -99));
public function testLoadInvalidStatus() {
$files = entity_load_multiple_by_properties('file', ['status' => -99]);
$this->assertFalse(reset($files), 'Trying to load a file with an invalid status fails.');
$this->assertFileHooksCalled(array());
$this->assertFileHooksCalled([]);
}
/**
* Load a single file and ensure that the correct values are returned.
*/
function testSingleValues() {
public 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());
@ -56,13 +56,13 @@ class LoadTest extends FileManagedUnitTestBase {
/**
* This will test loading file data from the database.
*/
function testMultiple() {
public 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()));
$by_path_files = entity_load_multiple_by_properties('file', ['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);
@ -71,8 +71,8 @@ class LoadTest extends FileManagedUnitTestBase {
// Load by fid.
file_test_reset();
$by_fid_files = File::loadMultiple(array($file->id()));
$this->assertFileHooksCalled(array());
$by_fid_files = File::loadMultiple([$file->id()]);
$this->assertFileHooksCalled([]);
$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.');

View file

@ -2,7 +2,7 @@
namespace Drupal\Tests\file\Kernel\Migrate\d6;
use Drupal\config\Tests\SchemaCheckTestTrait;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**

View file

@ -69,33 +69,77 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
$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');
$this->assertEntity(4, 'html-1.txt', '24', 'public://html-1.txt', 'text/plain', '1');
$map_table = $this->getMigration('d6_file')->getIdMap()->mapTableName();
$map = \Drupal::database()
->select($map_table, 'm')
->fields('m', ['sourceid1', 'destid1'])
->execute()
->fetchAllKeyed();
$map_expected = [
// The 4 files from the fixture.
1 => '1',
2 => '2',
3 => '3',
5 => '4',
// The file updated in migrateDumpAlter().
6 => NULL,
// The file created in migrateDumpAlter().
7 => '4',
];
$this->assertEquals($map_expected, $map);
// Test that we can re-import and also test with file_directory_path set.
\Drupal::database()
->truncate($this->getMigration('d6_file')->getIdMap()->mapTableName())
->truncate($map_table)
->execute();
// Update the file_directory_path.
Database::getConnection('default', 'migrate')
->update('variable')
->fields(array('value' => serialize('files/test')))
->fields(['value' => serialize('files/test')])
->condition('name', 'file_directory_path')
->execute();
Database::getConnection('default', 'migrate')
->update('variable')
->fields(array('value' => serialize(file_directory_temp())))
->fields(['value' => serialize(file_directory_temp())])
->condition('name', 'file_directory_temp')
->execute();
$this->executeMigration('d6_file');
$file = File::load(2);
// File 2, when migrated for the second time, is treated as a different file
// (due to having a different uri this time) and is given fid 6.
$file = File::load(6);
$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));
$map_table = $this->getMigration('d6_file')->getIdMap()->mapTableName();
$map = \Drupal::database()
->select($map_table, 'm')
->fields('m', ['sourceid1', 'destid1'])
->execute()
->fetchAllKeyed();
$map_expected = [
// The 4 files from the fixture.
1 => '5',
2 => '6',
3 => '7',
5 => '8',
// The file updated in migrateDumpAlter().
6 => NULL,
// The files created in migrateDumpAlter().
7 => '8',
8 => '8',
];
$this->assertEquals($map_expected, $map);
// File 6, created in static::migrateDumpAlter(), shares a path with
// file 4, which means it should be skipped entirely. If it was migrated
// then it would have an fid of 9.
$this->assertNull(File::load(9));
$this->assertEquals(8, count(File::loadMultiple()));
}
/**
@ -122,10 +166,10 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
$db->update('files')
->condition('fid', 6)
->fields(array(
->fields([
'filename' => static::$tempFilename,
'filepath' => $file_path,
))
])
->execute();
$file = (array) $db->select('files')

View file

@ -38,7 +38,7 @@ class MigrateUploadEntityDisplayTest extends MigrateDrupal6TestBase {
$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')));
$this->assertIdentical(['node', 'page', 'default', 'upload'], $this->getMigration('d6_upload_entity_display')->getIdMap()->lookupDestinationID(['page']));
}
}

View file

@ -38,7 +38,7 @@ class MigrateUploadEntityFormDisplayTest extends MigrateDrupal6TestBase {
$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')));
$this->assertIdentical(['node', 'page', 'default', 'upload'], $this->getMigration('d6_upload_entity_form_display')->getIdMap()->lookupDestinationID(['page']));
}
}

View file

@ -26,7 +26,7 @@ class MigrateUploadFieldTest extends MigrateDrupal6TestBase {
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('')));
$this->assertIdentical(['node', 'upload'], $this->getMigration('d6_upload_field')->getIdMap()->lookupDestinationID(['']));
}
}

View file

@ -38,7 +38,7 @@ class MigrateUploadInstanceTest extends MigrateDrupal6TestBase {
$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')));
$this->assertIdentical(['node', 'page', 'upload'], $this->getMigration('d6_upload_field_instance')->getIdMap()->lookupDestinationID(['page']));
}
}

View file

@ -24,10 +24,10 @@ class MigrateUploadTest extends MigrateDrupal6TestBase {
$this->installSchema('file', ['file_usage']);
$this->installSchema('node', ['node_access']);
$id_mappings = array('d6_file' => array());
$id_mappings = ['d6_file' => []];
// Create new file entities.
for ($i = 1; $i <= 3; $i++) {
$file = File::create(array(
$file = File::create([
'fid' => $i,
'uid' => 1,
'filename' => 'druplicon.txt',
@ -36,13 +36,13 @@ class MigrateUploadTest extends MigrateDrupal6TestBase {
'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));
$id_mappings['d6_file'][] = [[$i], [$i]];
}
$this->prepareMigrations($id_mappings);
@ -57,7 +57,7 @@ class MigrateUploadTest extends MigrateDrupal6TestBase {
/**
* Test upload migration from Drupal 6 to Drupal 8.
*/
function testUpload() {
public function testUpload() {
$this->container->get('entity.manager')
->getStorage('node')
->resetCache([1, 2]);

View file

@ -2,7 +2,7 @@
namespace Drupal\Tests\file\Kernel\Migrate\d7;
use Drupal\config\Tests\SchemaCheckTestTrait;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**

View file

@ -13,7 +13,7 @@ class MoveTest extends FileManagedUnitTestBase {
/**
* Move a normal file.
*/
function testNormal() {
public function testNormal() {
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
$desired_filepath = 'public://' . $this->randomMachineName();
@ -28,10 +28,10 @@ class MoveTest extends FileManagedUnitTestBase {
$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'));
$this->assertFileHooksCalled(['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())));
$this->assertEqual($source->id(), $result->id(), format_string("Source file id's' %fid is unchanged after move.", ['%fid' => $source->id()]));
// Reload the file from the database and check that the changes were
// actually saved.
@ -43,7 +43,7 @@ class MoveTest extends FileManagedUnitTestBase {
/**
* Test renaming when moving onto a file that already exists.
*/
function testExistingRename() {
public function testExistingRename() {
// Setup a file to overwrite.
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
@ -60,7 +60,7 @@ class MoveTest extends FileManagedUnitTestBase {
$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'));
$this->assertFileHooksCalled(['move', 'load', 'update']);
// Compare the returned value to what made it into the database.
$this->assertFileUnchanged($result, File::load($result->id()));
@ -78,7 +78,7 @@ class MoveTest extends FileManagedUnitTestBase {
/**
* Test replacement when moving onto a file that already exists.
*/
function testExistingReplace() {
public function testExistingReplace() {
// Setup a file to overwrite.
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
@ -95,7 +95,7 @@ class MoveTest extends FileManagedUnitTestBase {
$this->assertTrue($result, 'File moved successfully.');
// Check that the correct hooks were called.
$this->assertFileHooksCalled(array('move', 'update', 'delete', 'load'));
$this->assertFileHooksCalled(['move', 'update', 'delete', 'load']);
// Reload the file from the database and check that the changes were
// actually saved.
@ -110,7 +110,7 @@ class MoveTest extends FileManagedUnitTestBase {
/**
* Test replacement when moving onto itself.
*/
function testExistingReplaceSelf() {
public function testExistingReplaceSelf() {
// Setup a file to overwrite.
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
@ -122,7 +122,7 @@ class MoveTest extends FileManagedUnitTestBase {
$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());
$this->assertFileHooksCalled([]);
// Load the file from the database and make sure it is identical to what
// was returned.
@ -133,7 +133,7 @@ class MoveTest extends FileManagedUnitTestBase {
* Test that moving onto an existing file fails when FILE_EXISTS_ERROR is
* specified.
*/
function testExistingError() {
public function testExistingError() {
$contents = $this->randomMachineName(10);
$source = $this->createFile();
$target = $this->createFile(NULL, $contents);
@ -149,7 +149,7 @@ class MoveTest extends FileManagedUnitTestBase {
$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());
$this->assertFileHooksCalled([]);
// Load the file from the database and make sure it is identical to what
// was returned.

View file

@ -13,7 +13,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
/**
* Test the file_save_data() function when no filename is provided.
*/
function testWithoutFilename() {
public function testWithoutFilename() {
$contents = $this->randomMachineName(8);
$result = file_save_data($contents);
@ -26,7 +26,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
$this->assertTrue($result->isPermanent(), "The file's status was set to permanent.");
// Check that the correct hooks were called.
$this->assertFileHooksCalled(array('insert'));
$this->assertFileHooksCalled(['insert']);
// Verify that what was returned is what's in the database.
$this->assertFileUnchanged($result, File::load($result->id()));
@ -35,7 +35,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
/**
* Test the file_save_data() function when a filename is provided.
*/
function testWithFilename() {
public function testWithFilename() {
$contents = $this->randomMachineName(8);
// Using filename with non-latin characters.
@ -51,7 +51,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
$this->assertTrue($result->isPermanent(), "The file's status was set to permanent.");
// Check that the correct hooks were called.
$this->assertFileHooksCalled(array('insert'));
$this->assertFileHooksCalled(['insert']);
// Verify that what was returned is what's in the database.
$this->assertFileUnchanged($result, File::load($result->id()));
@ -60,7 +60,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
/**
* Test file_save_data() when renaming around an existing file.
*/
function testExistingRename() {
public function testExistingRename() {
// Setup a file to overwrite.
$existing = $this->createFile();
$contents = $this->randomMachineName(8);
@ -75,7 +75,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
$this->assertTrue($result->isPermanent(), "The file's status was set to permanent.");
// Check that the correct hooks were called.
$this->assertFileHooksCalled(array('insert'));
$this->assertFileHooksCalled(['insert']);
// Ensure that the existing file wasn't overwritten.
$this->assertDifferentFile($existing, $result);
@ -88,7 +88,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
/**
* Test file_save_data() when replacing an existing file.
*/
function testExistingReplace() {
public function testExistingReplace() {
// Setup a file to overwrite.
$existing = $this->createFile();
$contents = $this->randomMachineName(8);
@ -103,7 +103,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
$this->assertTrue($result->isPermanent(), "The file's status was set to permanent.");
// Check that the correct hooks were called.
$this->assertFileHooksCalled(array('load', 'update'));
$this->assertFileHooksCalled(['load', 'update']);
// Verify that the existing file was re-used.
$this->assertSameFile($existing, $result);
@ -115,7 +115,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
/**
* Test that file_save_data() fails overwriting an existing file.
*/
function testExistingError() {
public function testExistingError() {
$contents = $this->randomMachineName(8);
$existing = $this->createFile(NULL, $contents);
@ -125,7 +125,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
$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());
$this->assertFileHooksCalled([]);
// Ensure that the existing file wasn't overwritten.
$this->assertFileUnchanged($existing, File::load($existing->id()));

View file

@ -10,22 +10,22 @@ use Drupal\file\Entity\File;
* @group file
*/
class SaveTest extends FileManagedUnitTestBase {
function testFileSave() {
public function testFileSave() {
// Create a new file entity.
$file = File::create(array(
$file = File::create([
'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->assertFileHooksCalled(['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());
@ -41,7 +41,7 @@ class SaveTest extends FileManagedUnitTestBase {
$file->save();
// Check that the correct hooks were called.
$this->assertFileHooksCalled(array('load', 'update'));
$this->assertFileHooksCalled(['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');
@ -52,13 +52,13 @@ class SaveTest extends FileManagedUnitTestBase {
// 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(
$uppercase_values = [
'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();
@ -79,7 +79,7 @@ class SaveTest extends FileManagedUnitTestBase {
->execute();
$this->assertEqual(1, count($fids));
$this->assertEqual(array($uppercase_file->id() => $uppercase_file->id()), $fids);
$this->assertEqual([$uppercase_file->id() => $uppercase_file->id()], $fids);
}

View file

@ -52,7 +52,7 @@ class SpaceUsedTest extends FileManagedUnitTestBase {
/**
* Test different users with the default status.
*/
function testFileSpaceUsed() {
public function testFileSpaceUsed() {
$file = $this->container->get('entity.manager')->getStorage('file');
// Test different users with default status.
$this->assertEqual($file->spaceUsed(2), 70);

View file

@ -18,25 +18,25 @@ class UsageTest extends FileManagedUnitTestBase {
/**
* Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::listUsage().
*/
function testGetUsage() {
public function testGetUsage() {
$file = $this->createFile();
db_insert('file_usage')
->fields(array(
->fields([
'fid' => $file->id(),
'module' => 'testing',
'type' => 'foo',
'id' => 1,
'count' => 1
))
])
->execute();
db_insert('file_usage')
->fields(array(
->fields([
'fid' => $file->id(),
'module' => 'testing',
'type' => 'bar',
'id' => 2,
'count' => 2
))
])
->execute();
$usage = $this->container->get('file.usage')->listUsage($file);
@ -51,7 +51,7 @@ class UsageTest extends FileManagedUnitTestBase {
/**
* Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::add().
*/
function testAddUsage() {
public function testAddUsage() {
$file = $this->createFile();
$file_usage = $this->container->get('file.usage');
$file_usage->add($file, 'testing', 'foo', 1);
@ -77,23 +77,23 @@ class UsageTest extends FileManagedUnitTestBase {
/**
* Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::delete().
*/
function testRemoveUsage() {
public function testRemoveUsage() {
$file = $this->createFile();
$file_usage = $this->container->get('file.usage');
db_insert('file_usage')
->fields(array(
->fields([
'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'))
->fields('f', ['count'])
->condition('f.fid', $file->id())
->execute()
->fetchField();
@ -102,7 +102,7 @@ class UsageTest extends FileManagedUnitTestBase {
// Multiple decrement and removal.
$file_usage->delete($file, 'testing', 'bar', 2, 2);
$count = db_select('file_usage', 'f')
->fields('f', array('count'))
->fields('f', ['count'])
->condition('f.fid', $file->id())
->execute()
->fetchField();
@ -111,7 +111,7 @@ class UsageTest extends FileManagedUnitTestBase {
// Non-existent decrement.
$file_usage->delete($file, 'testing', 'bar', 2);
$count = db_select('file_usage', 'f')
->fields('f', array('count'))
->fields('f', ['count'])
->condition('f.fid', $file->id())
->execute()
->fetchField();
@ -124,14 +124,14 @@ class UsageTest extends FileManagedUnitTestBase {
* We are using UPDATE statements because using the API would set the
* timestamp.
*/
function createTempFiles() {
public function createTempFiles() {
// Temporary file that is old.
$temp_old = file_save_data('');
db_update('file_managed')
->fields(array(
->fields([
'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.');
@ -139,7 +139,7 @@ class UsageTest extends FileManagedUnitTestBase {
// Temporary file that is new.
$temp_new = file_save_data('');
db_update('file_managed')
->fields(array('status' => 0))
->fields(['status' => 0])
->condition('fid', $temp_new->id())
->execute();
$this->assertTrue(file_exists($temp_new->getFileUri()), 'New temp file was created correctly.');
@ -147,7 +147,7 @@ class UsageTest extends FileManagedUnitTestBase {
// 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))
->fields(['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.');
@ -155,13 +155,13 @@ class UsageTest extends FileManagedUnitTestBase {
// 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);
return [$temp_old, $temp_new, $perm_old, $perm_new];
}
/**
* Ensure that temporary files are removed by default.
*/
function testTempFileCleanupDefault() {
public 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.
@ -175,7 +175,7 @@ class UsageTest extends FileManagedUnitTestBase {
/**
* Ensure that temporary files are kept as configured.
*/
function testTempFileNoCleanup() {
public 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.
@ -194,7 +194,7 @@ class UsageTest extends FileManagedUnitTestBase {
/**
* Ensure that temporary files are kept as configured.
*/
function testTempFileCustomCleanup() {
public function testTempFileCustomCleanup() {
list($temp_old, $temp_new, $perm_old, $perm_new) = $this->createTempFiles();
// Set the max age to older than default.

View file

@ -12,27 +12,27 @@ class ValidateTest extends FileManagedUnitTestBase {
/**
* Test that the validators passed into are checked.
*/
function testCallerValidation() {
public function testCallerValidation() {
$file = $this->createFile();
// Empty validators.
$this->assertEqual(file_validate($file, array()), array(), 'Validating an empty array works successfully.');
$this->assertFileHooksCalled(array('validate'));
$this->assertEqual(file_validate($file, []), [], 'Validating an empty array works successfully.');
$this->assertFileHooksCalled(['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'));
file_test_set_return('validate', []);
$passing = ['file_test_validator' => [[]]];
$this->assertEqual(file_validate($file, $passing), [], 'Validating passes.');
$this->assertFileHooksCalled(['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'));
file_test_set_return('validate', ['Epic fail']);
$failing = ['file_test_validator' => [['Failed', 'Badly']]];
$this->assertEqual(file_validate($file, $failing), ['Failed', 'Badly', 'Epic fail'], 'Validating returns errors.');
$this->assertFileHooksCalled(['validate']);
}
}

View file

@ -40,7 +40,7 @@ class ValidatorTest extends FileManagedUnitTestBase {
/**
* Test the file_validate_extensions() function.
*/
function testFileValidateExtensions() {
public 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');
@ -53,7 +53,7 @@ class ValidatorTest extends FileManagedUnitTestBase {
/**
* This ensures a specific file is actually an image.
*/
function testFileValidateIsImage() {
public 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');
@ -68,7 +68,7 @@ class ValidatorTest extends FileManagedUnitTestBase {
*
* The image will be resized if it's too large.
*/
function testFileValidateImageResolution() {
public 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');
@ -116,7 +116,7 @@ class ValidatorTest extends FileManagedUnitTestBase {
/**
* This will ensure the filename length is valid.
*/
function testFileValidateNameLength() {
public function testFileValidateNameLength() {
// Create a new file entity.
$file = File::create();
@ -141,7 +141,7 @@ class ValidatorTest extends FileManagedUnitTestBase {
/**
* Test file_validate_size().
*/
function testFileValidateSize() {
public 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);

View file

@ -18,21 +18,21 @@ class ExtensionViewsFieldTest extends ViewsKernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = array('file', 'file_test_views', 'user');
public static $modules = ['file', 'file_test_views', 'user'];
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = array('file_extension_view');
public static $testViews = ['file_extension_view'];
/**
* {@inheritdoc}
*/
protected function setUp($import_test_views = TRUE) {
parent::setUp();
ViewTestData::createTestViews(get_class($this), array('file_test_views'));
ViewTestData::createTestViews(get_class($this), ['file_test_views']);
$this->installEntitySchema('file');

View file

@ -25,26 +25,26 @@ class CckFileTest extends UnitTestCase {
$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());
$plugin = new CckFile([], 'd6_cck_file', [], $migration, $migration_plugin->reveal());
$options = array(
$options = [
'alt' => 'Foobaz',
'title' => 'Wambooli',
);
$value = array(
];
$value = [
'fid' => 1,
'list' => TRUE,
'data' => serialize($options),
);
];
$transformed = $plugin->transform($value, $executable, $row, 'foo');
$expected = array(
$expected = [
'target_id' => 1,
'display' => TRUE,
'description' => '',
'alt' => 'Foobaz',
'title' => 'Wambooli',
);
];
$this->assertSame($expected, $transformed);
}