function RetrieveFileTest::testFileRetrieving
Same name in other branches
- 8.9.x core/modules/system/tests/src/Functional/System/RetrieveFileTest.php \Drupal\Tests\system\Functional\System\RetrieveFileTest::testFileRetrieving()
- 10 core/modules/system/tests/src/Functional/System/RetrieveFileTest.php \Drupal\Tests\system\Functional\System\RetrieveFileTest::testFileRetrieving()
Invokes system_retrieve_file() in several scenarios.
File
-
core/
modules/ system/ tests/ src/ Functional/ System/ RetrieveFileTest.php, line 22
Class
- RetrieveFileTest
- Tests HTTP file fetching and error handling.
Namespace
Drupal\Tests\system\Functional\SystemCode
public function testFileRetrieving() {
// Test 404 handling by trying to fetch a randomly named file.
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$file_system->mkdir($sourcedir = 'public://' . $this->randomMachineName());
// cSpell:disable-next-line
$filename = 'Файл для тестирования ' . $this->randomMachineName();
$url = \Drupal::service('file_url_generator')->generateAbsoluteString($sourcedir . '/' . $filename);
$retrieved_file = system_retrieve_file($url);
$this->assertFalse($retrieved_file, 'Non-existent file not fetched.');
// Actually create that file, download it via HTTP and test the returned path.
file_put_contents($sourcedir . '/' . $filename, 'testing');
$retrieved_file = system_retrieve_file($url);
// URLs could not contains characters outside the ASCII set so $filename
// has to be encoded.
$encoded_filename = rawurlencode($filename);
$this->assertEquals('public://' . $encoded_filename, $retrieved_file, 'Sane path for downloaded file returned (public:// scheme).');
$this->assertFileExists($retrieved_file);
$this->assertEquals(7, filesize($retrieved_file), 'File size of downloaded file is correct (public:// scheme).');
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$file_system->delete($retrieved_file);
// Test downloading file to a different location.
$file_system->mkdir($targetdir = 'temporary://' . $this->randomMachineName());
$retrieved_file = system_retrieve_file($url, $targetdir);
$this->assertEquals("{$targetdir}/{$encoded_filename}", $retrieved_file, 'Sane path for downloaded file returned (temporary:// scheme).');
$this->assertFileExists($retrieved_file);
$this->assertEquals(7, filesize($retrieved_file), 'File size of downloaded file is correct (temporary:// scheme).');
$file_system->delete($retrieved_file);
$file_system->deleteRecursive($sourcedir);
$file_system->deleteRecursive($targetdir);
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.