3 namespace Drupal\Tests\media\Kernel;
5 use Drupal\file\Entity\File;
6 use Drupal\KernelTests\KernelTestBase;
7 use Drupal\media\Entity\Media;
8 use Drupal\media\Entity\MediaType;
9 use Drupal\media\MediaTypeInterface;
10 use Drupal\user\Entity\User;
11 use org\bovigo\vfs\vfsStream;
14 * Base class for Media kernel tests.
16 abstract class MediaKernelTestBase extends KernelTestBase {
23 public static $modules = [
34 * The test media type.
36 * @var \Drupal\media\MediaTypeInterface
38 protected $testMediaType;
41 * The test media type with constraints.
43 * @var \Drupal\media\MediaTypeInterface
45 protected $testConstraintsMediaType;
50 * @var \Drupal\user\UserInterface
57 protected function setUp() {
60 $this->installEntitySchema('user');
61 $this->installEntitySchema('file');
62 $this->installSchema('file', 'file_usage');
63 $this->installSchema('system', 'sequences');
64 $this->installEntitySchema('media');
65 $this->installConfig(['field', 'system', 'image', 'file', 'media']);
67 // Create a test media type.
68 $this->testMediaType = $this->createMediaType('test');
69 // Create a test media type with constraints.
70 $this->testConstraintsMediaType = $this->createMediaType('test_constraints');
72 $this->user = User::create([
77 $this->container->get('current_user')->setAccount($this->user);
81 * Create a media type for a source plugin.
83 * @param string $media_source_name
84 * The name of the media source.
86 * @return \Drupal\media\MediaTypeInterface
89 protected function createMediaType($media_source_name) {
90 $id = strtolower($this->randomMachineName());
91 $media_type = MediaType::create([
94 'source' => $media_source_name,
95 'new_revision' => FALSE,
98 $source_field = $media_type->getSource()->createSourceField($media_type);
99 // The media type form creates a source field if it does not exist yet. The
100 // same must be done in a kernel test, since it does not use that form.
101 // @see \Drupal\media\MediaTypeForm::save()
102 $source_field->getFieldStorageDefinition()->save();
103 // The source field storage has been created, now the field can be saved.
104 $source_field->save();
105 $media_type->set('source_configuration', [
106 'source_field' => $source_field->getName(),
112 * Helper to generate media entity.
114 * @param string $filename
115 * String filename with extension.
116 * @param \Drupal\media\MediaTypeInterface $media_type
117 * The the media type.
119 * @return \Drupal\media\Entity\Media
122 protected function generateMedia($filename, MediaTypeInterface $media_type) {
123 vfsStream::setup('drupal_root');
128 $filename => str_repeat('a', 3000),
134 $file = File::create([
135 'uri' => 'vfs://drupal_root/sites/default/files/' . $filename,
136 'uid' => $this->user->id(),
138 $file->setPermanent();
141 return Media::create([
142 'bundle' => $media_type->id(),
143 'name' => 'Mr. Jones',
144 'field_media_file' => [
145 'target_id' => $file->id(),