Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / modules / file / tests / src / Kernel / FileManagedUnitTestBase.php
1 <?php
2
3 namespace Drupal\Tests\file\Kernel;
4
5 use Drupal\file\Entity\File;
6 use Drupal\file\FileInterface;
7 use Drupal\KernelTests\KernelTestBase;
8 use Drupal\user\Entity\User;
9
10 /**
11  * Base class for file unit tests that use the file_test module to test uploads and
12  * hooks.
13  */
14 abstract class FileManagedUnitTestBase extends KernelTestBase {
15
16   /**
17    * Modules to enable.
18    *
19    * @var array
20    */
21   public static $modules = ['file_test', 'file', 'system', 'field', 'user'];
22
23   protected function setUp() {
24     parent::setUp();
25     // Clear out any hook calls.
26     file_test_reset();
27
28     $this->installConfig(['system']);
29     $this->installEntitySchema('file');
30     $this->installEntitySchema('user');
31     $this->installSchema('file', ['file_usage']);
32
33     // Make sure that a user with uid 1 exists, self::createFile() relies on
34     // it.
35     $user = User::create(['uid' => 1, 'name' => $this->randomMachineName()]);
36     $user->enforceIsNew();
37     $user->save();
38     \Drupal::currentUser()->setAccount($user);
39   }
40
41   /**
42    * Assert that all of the specified hook_file_* hooks were called once, other
43    * values result in failure.
44    *
45    * @param array $expected
46    *   Array with string containing with the hook name, e.g. 'load', 'save',
47    *   'insert', etc.
48    */
49   public function assertFileHooksCalled($expected) {
50     \Drupal::state()->resetCache();
51
52     // Determine which hooks were called.
53     $actual = array_keys(array_filter(file_test_get_all_calls()));
54
55     // Determine if there were any expected that were not called.
56     $uncalled = array_diff($expected, $actual);
57     if (count($uncalled)) {
58       $this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', ['%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled)]));
59     }
60     else {
61       $this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', ['%expected' => empty($expected) ? '(none)' : implode(', ', $expected)]));
62     }
63
64     // Determine if there were any unexpected calls.
65     $unexpected = array_diff($actual, $expected);
66     if (count($unexpected)) {
67       $this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', ['%unexpected' => empty($unexpected) ? '(none)' : implode(', ', $unexpected)]));
68     }
69     else {
70       $this->assertTrue(TRUE, 'No unexpected hooks were called.');
71     }
72   }
73
74   /**
75    * Assert that a hook_file_* hook was called a certain number of times.
76    *
77    * @param string $hook
78    *   String with the hook name, e.g. 'load', 'save', 'insert', etc.
79    * @param int $expected_count
80    *   Optional integer count.
81    * @param string $message
82    *   Optional translated string message.
83    */
84   public function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
85     $actual_count = count(file_test_get_calls($hook));
86
87     if (!isset($message)) {
88       if ($actual_count == $expected_count) {
89         $message = format_string('hook_file_@name was called correctly.', ['@name' => $hook]);
90       }
91       elseif ($expected_count == 0) {
92         $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]);
93       }
94       else {
95         $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]);
96       }
97     }
98     $this->assertEqual($actual_count, $expected_count, $message);
99   }
100
101   /**
102    * Asserts that two files have the same values (except timestamp).
103    *
104    * @param \Drupal\file\FileInterface $before
105    *   File object to compare.
106    * @param \Drupal\file\FileInterface $after
107    *   File object to compare.
108    */
109   public function assertFileUnchanged(FileInterface $before, FileInterface $after) {
110     $this->assertEqual($before->id(), $after->id(), t('File id is the same: %file1 == %file2.', ['%file1' => $before->id(), '%file2' => $after->id()]), 'File unchanged');
111     $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');
112     $this->assertEqual($before->getFilename(), $after->getFilename(), t('File name is the same: %file1 == %file2.', ['%file1' => $before->getFilename(), '%file2' => $after->getFilename()]), 'File unchanged');
113     $this->assertEqual($before->getFileUri(), $after->getFileUri(), t('File path is the same: %file1 == %file2.', ['%file1' => $before->getFileUri(), '%file2' => $after->getFileUri()]), 'File unchanged');
114     $this->assertEqual($before->getMimeType(), $after->getMimeType(), t('File MIME type is the same: %file1 == %file2.', ['%file1' => $before->getMimeType(), '%file2' => $after->getMimeType()]), 'File unchanged');
115     $this->assertEqual($before->getSize(), $after->getSize(), t('File size is the same: %file1 == %file2.', ['%file1' => $before->getSize(), '%file2' => $after->getSize()]), 'File unchanged');
116     $this->assertEqual($before->isPermanent(), $after->isPermanent(), t('File status is the same: %file1 == %file2.', ['%file1' => $before->isPermanent(), '%file2' => $after->isPermanent()]), 'File unchanged');
117   }
118
119   /**
120    * Asserts that two files are not the same by comparing the fid and filepath.
121    *
122    * @param \Drupal\file\FileInterface $file1
123    *   File object to compare.
124    * @param \Drupal\file\FileInterface $file2
125    *   File object to compare.
126    */
127   public function assertDifferentFile(FileInterface $file1, FileInterface $file2) {
128     $this->assertNotEqual($file1->id(), $file2->id(), t('Files have different ids: %file1 != %file2.', ['%file1' => $file1->id(), '%file2' => $file2->id()]), 'Different file');
129     $this->assertNotEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have different paths: %file1 != %file2.', ['%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri()]), 'Different file');
130   }
131
132   /**
133    * Asserts that two files are the same by comparing the fid and filepath.
134    *
135    * @param \Drupal\file\FileInterface $file1
136    *   File object to compare.
137    * @param \Drupal\file\FileInterface $file2
138    *   File object to compare.
139    */
140   public function assertSameFile(FileInterface $file1, FileInterface $file2) {
141     $this->assertEqual($file1->id(), $file2->id(), t('Files have the same ids: %file1 == %file2.', ['%file1' => $file1->id(), '%file2-fid' => $file2->id()]), 'Same file');
142     $this->assertEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have the same path: %file1 == %file2.', ['%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri()]), 'Same file');
143   }
144
145   /**
146    * Create a file and save it to the files table and assert that it occurs
147    * correctly.
148    *
149    * @param string $filepath
150    *   Optional string specifying the file path. If none is provided then a
151    *   randomly named file will be created in the site's files directory.
152    * @param string $contents
153    *   Optional contents to save into the file. If a NULL value is provided an
154    *   arbitrary string will be used.
155    * @param string $scheme
156    *   Optional string indicating the stream scheme to use. Drupal core includes
157    *   public, private, and temporary. The public wrapper is the default.
158    * @return \Drupal\file\FileInterface
159    *   File entity.
160    */
161   public function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
162     // Don't count hook invocations caused by creating the file.
163     \Drupal::state()->set('file_test.count_hook_invocations', FALSE);
164     $file = File::create([
165       'uri' => $this->createUri($filepath, $contents, $scheme),
166       'uid' => 1,
167     ]);
168     $file->save();
169     // Write the record directly rather than using the API so we don't invoke
170     // the hooks.
171     $this->assertTrue($file->id() > 0, 'The file was added to the database.', 'Create test file');
172
173     \Drupal::state()->set('file_test.count_hook_invocations', TRUE);
174     return $file;
175   }
176
177   /**
178    * Creates a file and returns its URI.
179    *
180    * @param string $filepath
181    *   Optional string specifying the file path. If none is provided then a
182    *   randomly named file will be created in the site's files directory.
183    * @param string $contents
184    *   Optional contents to save into the file. If a NULL value is provided an
185    *   arbitrary string will be used.
186    * @param string $scheme
187    *   Optional string indicating the stream scheme to use. Drupal core includes
188    *   public, private, and temporary. The public wrapper is the default.
189    *
190    * @return string
191    *   File URI.
192    */
193   public function createUri($filepath = NULL, $contents = NULL, $scheme = NULL) {
194     if (!isset($filepath)) {
195       // Prefix with non-latin characters to ensure that all file-related
196       // tests work with international filenames.
197       $filepath = 'Файл для тестирования ' . $this->randomMachineName();
198     }
199     if (!isset($scheme)) {
200       $scheme = file_default_scheme();
201     }
202     $filepath = $scheme . '://' . $filepath;
203
204     if (!isset($contents)) {
205       $contents = "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.";
206     }
207
208     file_put_contents($filepath, $contents);
209     $this->assertTrue(is_file($filepath), t('The test file exists on the disk.'), 'Create test file');
210     return $filepath;
211   }
212
213 }