updated core to 8.6.1 via composer

This commit is contained in:
2018-09-12 13:58:26 +02:00
parent a9a219f2ed
commit ea56b9fba3
4443 changed files with 112098 additions and 40708 deletions
@@ -0,0 +1,8 @@
<!DOCTYPE html>
<html lang="de">
<head>
<link rel="alternate" href="photo_flickr.json"
type="application/json+oembed" title="Druplicon FTW!">
</head>
<body></body>
</html>
@@ -0,0 +1,12 @@
{
"type": "photo",
"title": "Druplicon FTW!",
"width": "88",
"height": "100",
"url": "internal:\/core\/misc\/druplicon.png",
"thumbnail_url": "internal:\/core\/misc\/druplicon.png",
"thumbnail_width": 88,
"thumbnail_height": 100,
"provider_name": "Flickr",
"version": "1.0"
}
+61
View File
@@ -0,0 +1,61 @@
[
{
"provider_name": "Vimeo",
"provider_url": "https:\/\/vimeo.com\/",
"endpoints": [
{
"schemes": [
"https:\/\/vimeo.com\/*",
"https:\/\/vimeo.com\/album\/*\/video\/*",
"https:\/\/vimeo.com\/channels\/*\/*",
"https:\/\/vimeo.com\/groups\/*\/videos\/*",
"https:\/\/vimeo.com\/ondemand\/*\/*",
"https:\/\/player.vimeo.com\/video\/*"
],
"url": "https:\/\/vimeo.com\/api\/oembed.{format}",
"discovery": true
}
]
},
{
"provider_name": "Twitter",
"provider_url": "http:\/\/www.twitter.com\/",
"endpoints": [
{
"schemes": [
"https:\/\/twitter.com\/*\/status\/*",
"https:\/\/*.twitter.com\/*\/status\/*"
],
"url": "https:\/\/publish.twitter.com\/oembed"
}
]
},
{
"provider_name": "CollegeHumor",
"provider_url": "http:\/\/www.collegehumor.com\/",
"endpoints": [
{
"schemes": [
"http:\/\/www.collegehumor.com\/video\/*"
],
"url": "http:\/\/www.collegehumor.com\/oembed.{format}",
"discovery": true
}
]
},
{
"provider_name": "Flickr",
"provider_url": "http:\/\/www.flickr.com\/",
"endpoints": [
{
"schemes": [
"http:\/\/*.flickr.com\/photos\/*",
"http:\/\/flic.kr\/p\/*"
],
"url": "http:\/\/www.flickr.com\/services\/oembed\/",
"discovery": true
}
]
}
]
@@ -0,0 +1,13 @@
{
"url": "https:\/\/twitter.com\/drupaldevdays\/status\/935643039741202432",
"author_name": "Drupal Dev Days",
"author_url": "https:\/\/twitter.com\/drupaldevdays",
"html": "<h1>By the power of Greyskull, Twitter works!</h1>",
"width": 550,
"height": 360,
"type": "rich",
"cache_age": "3153600000",
"provider_name": "Twitter",
"provider_url": "https:\/\/twitter.com",
"version": "1.0"
}
@@ -0,0 +1,8 @@
<!DOCTYPE html>
<html lang="de">
<head>
<link rel="alternate" href="video_collegehumor.xml"
type="application/xml+oembed" title="Let&#039;s Not Get a Drink Sometime">
</head>
<body></body>
</html>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<oembed>
<type>video</type>
<version>1.0</version>
<title>Let's Not Get a Drink Sometime</title>
<https/>
<author_name>CollegeHumor</author_name>
<author_url>http://www.collegehumor.com</author_url>
<provider_name>CollegeHumor</provider_name>
<provider_url>http://www.collegehumor.com</provider_url>
<width>610</width>
<height>343</height>
<html><h1>By the power of Greyskull, CollegeHumor works!</h1>
</html>
<thumbnail_url>internal:/core/misc/druplicon.png</thumbnail_url>
<thumbnail_width>88</thumbnail_width>
<thumbnail_height>100</thumbnail_height>
</oembed>
@@ -0,0 +1,8 @@
<!DOCTYPE html>
<html lang="de">
<head>
<link rel="alternate" href="video_vimeo.json"
type="application/json+oembed" title="Drupal Rap Video - Schipulcon09">
</head>
<body></body>
</html>
@@ -0,0 +1,16 @@
{
"type": "video",
"version": "1.0",
"provider_name": "Vimeo",
"provider_url": "https:\/\/vimeo.com\/",
"title": "Drupal Rap Video - Schipulcon09",
"author_name": "Tendenci - The Open Source AMS",
"author_url": "https:\/\/vimeo.com\/schipul",
"html": "<h1>By the power of Greyskull, Vimeo works!</h1>",
"width": 480,
"height": 360,
"description": "Special thanks to Tendenci, formerly Schipul for sponsoring this video with training, equipment and time. The open source way. All creative however was self directed by the individuals - A. Hughes (www.schipul.com\/ahughes) featuring QCait (www.schipul.com\/qcait) - Hands On Drupal\n\nDrupal is a free software package that allows an individual or a community of users to easily publish, manage and organize a wide variety of content on a website.\n\nNeed a little Drupal help or just want to geek out with us? Visit our www.schipul.com\/drupal for more info - we'd love to connect!\n\nGo here for Drupal Common Terms and Suggested Modules : http:\/\/schipul.com\/en\/helpfiles\/v\/229",
"thumbnail_url": "internal:\/core\/misc\/druplicon.png",
"thumbnail_width": 295,
"thumbnail_height": 221
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,36 @@
<?php
// @codingStandardsIgnoreFile
/**
* @file
* Contains database additions to drupal-8.4.0.bare.standard.php.gz for testing
* the upgrade path of https://www.drupal.org/node/2862422.
*/
use Drupal\Core\Database\Database;
$connection = Database::getConnection();
$role = $connection->select('config')
->fields('config', ['data'])
->condition('collection', '')
->condition('name', 'user.role.authenticated')
->execute()
->fetchField();
$role = unserialize($role);
$role['permissions'][] = 'update media';
$role['permissions'][] = 'update any media';
$role['permissions'][] = 'delete media';
$role['permissions'][] = 'delete any media';
$role['permissions'][] = 'create media';
$connection->update('config')
->fields([
'data' => serialize($role),
'collection' => '',
'name' => 'user.role.authenticated',
])
->condition('collection', '')
->condition('name', 'user.role.authenticated')
->execute();
File diff suppressed because one or more lines are too long
@@ -0,0 +1,8 @@
name: Media oEmbed test
description: 'Provides functionality to mimic an oEmbed provider.'
type: module
package: Testing
version: VERSION
core: 8.x
dependencies:
- drupal:media
@@ -0,0 +1,17 @@
<?php
/**
* @file
* Helper module for the Media oEmbed tests.
*/
use Drupal\media\OEmbed\Provider;
/**
* Implements hook_oembed_resource_url_alter().
*/
function media_test_oembed_oembed_resource_url_alter(array &$parsed_url, Provider $provider) {
if ($provider->getName() === 'Vimeo') {
$parsed_url['query']['altered'] = 1;
}
}
@@ -0,0 +1,6 @@
media_test_oembed.resource.get:
path: '/media_test_oembed/resource'
defaults:
_controller: '\Drupal\media_test_oembed\Controller\ResourceController::get'
requirements:
_access: 'TRUE'
@@ -0,0 +1,48 @@
<?php
namespace Drupal\media_test_oembed\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Test controller returning oEmbed resources from Media's test fixtures.
*/
class ResourceController {
/**
* Returns the contents of an oEmbed resource fixture.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request.
*
* @return \Symfony\Component\HttpFoundation\Response
* The JSON response.
*/
public function get(Request $request) {
$asset_url = $request->query->get('url');
$resources = \Drupal::state()->get(static::class, []);
$content = file_get_contents($resources[$asset_url]);
$response = new Response($content);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* Maps an asset URL to a local fixture representing its oEmbed resource.
*
* @param string $asset_url
* The asset URL.
* @param string $resource_path
* The path of the oEmbed resource representing the asset.
*/
public static function setResourceUrl($asset_url, $resource_path) {
$resources = \Drupal::state()->get(static::class, []);
$resources[$asset_url] = $resource_path;
\Drupal::state()->set(static::class, $resources);
}
}
@@ -0,0 +1,26 @@
<?php
namespace Drupal\media_test_oembed;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
/**
* Replaces oEmbed-related media services with testing versions.
*/
class MediaTestOembedServiceProvider extends ServiceProviderBase {
/**
* {@inheritdoc}
*/
public function alter(ContainerBuilder $container) {
parent::alter($container);
$container->getDefinition('media.oembed.provider_repository')
->setClass(ProviderRepository::class);
$container->getDefinition('media.oembed.url_resolver')
->setClass(UrlResolver::class);
}
}
@@ -0,0 +1,55 @@
<?php
namespace Drupal\media_test_oembed;
use Drupal\media\OEmbed\Provider;
use Drupal\media\OEmbed\ProviderRepository as BaseProviderRepository;
/**
* Overrides the oEmbed provider repository service for testing purposes.
*
* This service does not use caching at all, and will always try to retrieve
* provider data from state before calling the parent methods.
*/
class ProviderRepository extends BaseProviderRepository {
/**
* {@inheritdoc}
*/
protected function cacheGet($cid) {
return FALSE;
}
/**
* {@inheritdoc}
*/
public function getAll() {
return \Drupal::state()->get(static::class) ?: parent::getAll();
}
/**
* {@inheritdoc}
*/
public function get($provider_name) {
$providers = \Drupal::state()->get(static::class, []);
if (isset($providers[$provider_name])) {
return $providers[$provider_name];
}
return parent::get($provider_name);
}
/**
* Stores an oEmbed provider value object in state.
*
* @param \Drupal\media\OEmbed\Provider $provider
* The provider to store.
*/
public function setProvider(Provider $provider) {
$providers = \Drupal::state()->get(static::class, []);
$name = $provider->getName();
$providers[$name] = $provider;
\Drupal::state()->set(static::class, $providers);
}
}
@@ -0,0 +1,38 @@
<?php
namespace Drupal\media_test_oembed;
use Drupal\media\OEmbed\UrlResolver as BaseUrlResolver;
/**
* Overrides the oEmbed URL resolver service for testing purposes.
*/
class UrlResolver extends BaseUrlResolver {
/**
* Sets the endpoint URL for an oEmbed resource URL.
*
* @param string $url
* The resource URL.
* @param string $endpoint_url
* The endpoint URL.
*/
public static function setEndpointUrl($url, $endpoint_url) {
$urls = \Drupal::state()->get(static::class, []);
$urls[$url] = $endpoint_url;
\Drupal::state()->set(static::class, $urls);
}
/**
* {@inheritdoc}
*/
public function getResourceUrl($url, $max_width = NULL, $max_height = NULL) {
$urls = \Drupal::state()->get(static::class, []);
if (isset($urls[$url])) {
return $urls[$url];
}
return parent::getResourceUrl($url, $max_width, $max_height);
}
}
@@ -5,5 +5,5 @@ core: 8.x
package: Testing
version: VERSION
dependencies:
- media
- media_test_source
- drupal:media
- drupal:media_test_source
@@ -0,0 +1,154 @@
langcode: en
status: true
dependencies:
module:
- media
- user
id: test_media_bulk_form
label: ''
module: views
description: ''
tag: ''
base_table: media_field_data
base_field: mid
core: 8.x
display:
default:
display_plugin: default
id: default
display_title: Master
position: 0
display_options:
style:
type: table
row:
type: fields
fields:
media_bulk_form:
id: media_bulk_form
table: media
field: media_bulk_form
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: false
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
action_title: 'With selection'
include_exclude: exclude
selected_actions: { }
entity_type: media
plugin_id: bulk_form
name:
id: name
table: media_field_data
field: name
entity_type: media
entity_field: media
hide_empty: false
empty_zero: false
settings:
link_to_entity: false
plugin_id: field
relationship: none
group_type: group
admin_label: ''
label: 'Media name'
exclude: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_alter_empty: true
click_sort_column: value
type: string
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
status:
id: status
table: media_field_data
field: status
relationship: none
group_type: group
admin_label: ''
label: Status
exclude: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: boolean
settings:
format: custom
format_custom_true: Published
format_custom_false: Unpublished
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
entity_type: media
entity_field: status
plugin_id: field
sorts:
mid:
id: mid
table: media_field_data
field: mid
relationship: none
group_type: group
admin_label: ''
order: ASC
exposed: false
expose:
label: ''
entity_type: media
entity_field: mid
plugin_id: standard
title: 'Entity bulk form test view'
header: { }
footer: { }
empty: { }
relationships: { }
arguments: { }
display_extenders: { }
page_1:
display_plugin: page
id: page_1
display_title: Page
position: 1
display_options:
path: test-media-bulk-form
@@ -5,5 +5,5 @@ package: Testing
version: VERSION
core: 8.x
dependencies:
- media
- views
- drupal:media
- drupal:views
@@ -0,0 +1,173 @@
<?php
namespace Drupal\Tests\media\Functional\FieldFormatter;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\media\Entity\Media;
use Drupal\media_test_oembed\Controller\ResourceController;
use Drupal\media_test_oembed\UrlResolver;
use Drupal\Tests\media\Functional\MediaFunctionalTestBase;
use Drupal\Tests\media\Traits\OEmbedTestTrait;
/**
* @covers \Drupal\media\Plugin\Field\FieldFormatter\OEmbedFormatter
*
* @group media
*/
class OEmbedFormatterTest extends MediaFunctionalTestBase {
use OEmbedTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = [
'field_ui',
'link',
'media_test_oembed',
];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->lockHttpClientToFixtures();
}
/**
* Data provider for testRender().
*
* @see ::testRender()
*
* @return array
*/
public function providerRender() {
return [
'Vimeo video' => [
'https://vimeo.com/7073899',
'video_vimeo.json',
[],
[
'iframe' => [
'src' => '/media/oembed?url=https%3A//vimeo.com/7073899',
'width' => 480,
'height' => 360,
],
],
],
'Vimeo video, resized' => [
'https://vimeo.com/7073899',
'video_vimeo.json?maxwidth=100&maxheight=100',
['max_width' => 100, 'max_height' => 100],
[
'iframe' => [
'src' => '/media/oembed?url=https%3A//vimeo.com/7073899',
'width' => 100,
'height' => 100,
],
],
],
'tweet' => [
'https://twitter.com/drupaldevdays/status/935643039741202432',
'rich_twitter.json',
[],
[
'iframe' => [
'src' => '/media/oembed?url=https%3A//twitter.com/drupaldevdays/status/935643039741202432',
'width' => 550,
'height' => 360,
],
],
],
'Flickr photo' => [
'https://www.flickr.com/photos/amazeelabs/26497866357',
'photo_flickr.json',
[],
[
'img' => [
'src' => '/core/misc/druplicon.png',
'width' => 88,
'height' => 100,
],
],
],
];
}
/**
* Tests that oEmbed media types' display can be configured correctly.
*/
public function testDisplayConfiguration() {
$account = $this->drupalCreateUser(['administer media display']);
$this->drupalLogin($account);
$media_type = $this->createMediaType('oembed:video');
$this->drupalGet('/admin/structure/media/manage/' . $media_type->id() . '/display');
$assert = $this->assertSession();
$assert->statusCodeEquals(200);
// Test that the formatter doesn't try to check applicability for fields
// which do not have a specific target bundle.
// @see https://www.drupal.org/project/drupal/issues/2976795.
$assert->pageTextNotContains('Can only flip STRING and INTEGER values!');
}
/**
* Tests the oEmbed field formatter.
*
* @param string $url
* The canonical URL of the media asset to test.
* @param string $resource_url
* The oEmebd resource URL of the media asset to test.
* @param mixed $formatter_settings
* Settings for the oEmbed field formatter.
* @param array $selectors
* An array of arrays. Each key is a CSS selector targeting an element in
* the rendered output, and each value is an array of attributes, keyed by
* name, that the element is expected to have.
*
* @dataProvider providerRender
*/
public function testRender($url, $resource_url, array $formatter_settings, array $selectors) {
$account = $this->drupalCreateUser(['view media']);
$this->drupalLogin($account);
$media_type = $this->createMediaType('oembed:video');
$source = $media_type->getSource();
$source_field = $source->getSourceFieldDefinition($media_type);
EntityViewDisplay::create([
'targetEntityType' => 'media',
'bundle' => $media_type->id(),
'mode' => 'full',
'status' => TRUE,
])->removeComponent('thumbnail')
->setComponent($source_field->getName(), [
'type' => 'oembed',
'settings' => $formatter_settings,
])
->save();
$this->hijackProviderEndpoints();
ResourceController::setResourceUrl($url, $this->getFixturesDirectory() . '/' . $resource_url);
UrlResolver::setEndpointUrl($url, $resource_url);
$entity = Media::create([
'bundle' => $media_type->id(),
$source_field->getName() => $url,
]);
$entity->save();
$this->drupalGet($entity->toUrl());
$assert = $this->assertSession();
$assert->statusCodeEquals(200);
foreach ($selectors as $selector => $attributes) {
foreach ($attributes as $attribute => $value) {
$assert->elementAttributeContains('css', $selector, $attribute, $value);
}
}
}
}
@@ -0,0 +1,228 @@
<?php
namespace Drupal\Tests\media\Functional\Hal;
use Drupal\Core\Cache\Cache;
use Drupal\file\Entity\File;
use Drupal\Tests\hal\Functional\EntityResource\HalEntityNormalizationTrait;
use Drupal\Tests\media\Functional\Rest\MediaResourceTestBase;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\user\Entity\User;
/**
* @group hal
*/
class MediaHalJsonAnonTest extends MediaResourceTestBase {
use HalEntityNormalizationTrait;
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedEntity() {
$default_normalization = parent::getExpectedNormalizedEntity();
$normalization = $this->applyHalFieldNormalization($default_normalization);
$file = File::load(1);
$thumbnail = File::load(2);
$author = User::load($this->entity->getOwnerId());
return $normalization + [
'_links' => [
'self' => [
'href' => $this->baseUrl . '/media/1?_format=hal_json',
],
'type' => [
'href' => $this->baseUrl . '/rest/type/media/camelids',
],
$this->baseUrl . '/rest/relation/media/camelids/field_media_file' => [
[
'href' => $file->url(),
'lang' => 'en',
],
],
$this->baseUrl . '/rest/relation/media/camelids/revision_user' => [
[
'href' => $this->baseUrl . '/user/' . $author->id() . '?_format=hal_json',
],
],
$this->baseUrl . '/rest/relation/media/camelids/thumbnail' => [
[
'href' => $thumbnail->url(),
'lang' => 'en',
],
],
$this->baseUrl . '/rest/relation/media/camelids/uid' => [
[
'href' => $this->baseUrl . '/user/' . $author->id() . '?_format=hal_json',
'lang' => 'en',
],
],
],
'_embedded' => [
$this->baseUrl . '/rest/relation/media/camelids/field_media_file' => [
[
'_links' => [
'self' => [
'href' => $file->url(),
],
'type' => [
'href' => $this->baseUrl . '/rest/type/file/file',
],
],
'lang' => 'en',
'uuid' => [
[
'value' => $file->uuid(),
],
],
],
],
$this->baseUrl . '/rest/relation/media/camelids/revision_user' => [
[
'_links' => [
'self' => [
'href' => $this->baseUrl . '/user/' . $author->id() . '?_format=hal_json',
],
'type' => [
'href' => $this->baseUrl . '/rest/type/user/user',
],
],
'uuid' => [
[
'value' => $author->uuid(),
],
],
],
],
$this->baseUrl . '/rest/relation/media/camelids/thumbnail' => [
[
'_links' => [
'self' => [
'href' => $thumbnail->url(),
],
'type' => [
'href' => $this->baseUrl . '/rest/type/file/file',
],
],
'lang' => 'en',
'uuid' => [
[
'value' => $thumbnail->uuid(),
],
],
],
],
$this->baseUrl . '/rest/relation/media/camelids/uid' => [
[
'_links' => [
'self' => [
'href' => $this->baseUrl . '/user/' . $author->id() . '?_format=hal_json',
],
'type' => [
'href' => $this->baseUrl . '/rest/type/user/user',
],
],
'uuid' => [
[
'value' => $author->uuid(),
],
],
'lang' => 'en',
],
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedFileEntity() {
$normalization = parent::getExpectedNormalizedFileEntity();
$owner = static::$auth ? $this->account : User::load(0);
// Cannot use applyHalFieldNormalization() as it uses the $entity property
// from the test class, which in the case of file upload tests, is the
// parent entity test entity for the file that's created.
// The HAL normalization adds entity reference fields to '_links' and
// '_embedded'.
unset($normalization['uid']);
return $normalization + [
'_links' => [
'self' => [
// @todo This can use a proper link once
// https://www.drupal.org/project/drupal/issues/2907402 is complete.
// This link matches what is generated from from File::url(), a
// resource URL is currently not available.
'href' => file_create_url($normalization['uri'][0]['value']),
],
'type' => [
'href' => $this->baseUrl . '/rest/type/file/file',
],
$this->baseUrl . '/rest/relation/file/file/uid' => [
['href' => $this->baseUrl . '/user/' . $owner->id() . '?_format=hal_json'],
],
],
'_embedded' => [
$this->baseUrl . '/rest/relation/file/file/uid' => [
[
'_links' => [
'self' => [
'href' => $this->baseUrl . '/user/' . $owner->id() . '?_format=hal_json',
],
'type' => [
'href' => $this->baseUrl . '/rest/type/user/user',
],
],
'uuid' => [
[
'value' => $owner->uuid(),
],
],
],
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPostEntity() {
return parent::getNormalizedPostEntity() + [
'_links' => [
'type' => [
'href' => $this->baseUrl . '/rest/type/media/camelids',
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheTags() {
return Cache::mergeTags(parent::getExpectedCacheTags(), ['config:hal.settings']);
}
}
@@ -0,0 +1,24 @@
<?php
namespace Drupal\Tests\media\Functional\Hal;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group hal
*/
class MediaHalJsonBasicAuthTest extends MediaHalJsonAnonTest {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}
@@ -0,0 +1,19 @@
<?php
namespace Drupal\Tests\media\Functional\Hal;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group hal
*/
class MediaHalJsonCookieTest extends MediaHalJsonAnonTest {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}
@@ -0,0 +1,30 @@
<?php
namespace Drupal\Tests\media\Functional\Hal;
use Drupal\Tests\media\Functional\Rest\MediaTypeResourceTestBase;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
/**
* @group hal
*/
class MediaTypeHalJsonAnonTest extends MediaTypeResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
}
@@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\media\Functional\Hal;
use Drupal\Tests\media\Functional\Rest\MediaTypeResourceTestBase;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group hal
*/
class MediaTypeHalJsonBasicAuthTest extends MediaTypeResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal', 'basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}
@@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\media\Functional\Hal;
use Drupal\Tests\media\Functional\Rest\MediaTypeResourceTestBase;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group hal
*/
class MediaTypeHalJsonCookieTest extends MediaTypeResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}
@@ -39,7 +39,7 @@ class MediaAccessTest extends MediaFunctionalTestBase {
public function testMediaAccess() {
$assert_session = $this->assertSession();
$media_type = $this->createMediaType();
$media_type = $this->createMediaType('test');
// Create media.
$media = Media::create([
@@ -0,0 +1,113 @@
<?php
namespace Drupal\Tests\media\Functional;
use Drupal\media\Entity\Media;
use Drupal\views\Views;
/**
* Tests a media bulk form.
*
* @group media
*/
class MediaBulkFormTest extends MediaFunctionalTestBase {
/**
* Modules to be enabled.
*
* @var array
*/
public static $modules = ['media_test_views'];
/**
* The test media type.
*
* @var \Drupal\media\MediaTypeInterface
*/
protected $testMediaType;
/**
* The test media items.
*
* @var \Drupal\media\MediaInterface[]
*/
protected $mediaItems;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->testMediaType = $this->createMediaType('test');
// Create some test media items.
$this->mediaItems = [];
for ($i = 1; $i <= 5; $i++) {
$media = Media::create([
'bundle' => $this->testMediaType->id(),
]);
$media->save();
$this->mediaItems[] = $media;
}
}
/**
* Tests the media bulk form.
*/
public function testBulkForm() {
$session = $this->getSession();
$page = $session->getPage();
$assert_session = $this->assertSession();
// Check that all created items are present in the test view.
$view = Views::getView('test_media_bulk_form');
$view->execute();
$this->assertSame($view->total_rows, 5);
// Check the operations are accessible to the logged in user.
$this->drupalGet('test-media-bulk-form');
// Current available actions: Delete, Save, Publish, Unpublish.
$available_actions = [
'media_delete_action',
'media_publish_action',
'media_save_action',
'media_unpublish_action',
];
foreach ($available_actions as $action_name) {
$assert_session->optionExists('action', $action_name);
}
// Test unpublishing in bulk.
$page->checkField('media_bulk_form[0]');
$page->checkField('media_bulk_form[1]');
$page->checkField('media_bulk_form[2]');
$page->selectFieldOption('action', 'media_unpublish_action');
$page->pressButton('Apply to selected items');
$assert_session->pageTextContains('Unpublish media was applied to 3 items');
$this->assertFalse($this->storage->loadUnchanged(1)->isPublished(), 'The unpublish action failed in some of the media items.');
$this->assertFalse($this->storage->loadUnchanged(2)->isPublished(), 'The unpublish action failed in some of the media items.');
$this->assertFalse($this->storage->loadUnchanged(3)->isPublished(), 'The unpublish action failed in some of the media items.');
// Test publishing in bulk.
$page->checkField('media_bulk_form[0]');
$page->checkField('media_bulk_form[1]');
$page->selectFieldOption('action', 'media_publish_action');
$page->pressButton('Apply to selected items');
$assert_session->pageTextContains('Publish media was applied to 2 items');
$this->assertTrue($this->storage->loadUnchanged(1)->isPublished(), 'The publish action failed in some of the media items.');
$this->assertTrue($this->storage->loadUnchanged(2)->isPublished(), 'The publish action failed in some of the media items.');
// Test deletion in bulk.
$page->checkField('media_bulk_form[0]');
$page->checkField('media_bulk_form[1]');
$page->selectFieldOption('action', 'media_delete_action');
$page->pressButton('Apply to selected items');
$assert_session->pageTextContains('Are you sure you want to delete these media items?');
$page->pressButton('Delete');
$assert_session->pageTextContains('Deleted 2 items.');
$this->assertNull($this->storage->loadUnchanged(1), 'Could not delete some of the media items.');
$this->assertNull($this->storage->loadUnchanged(2), 'Could not delete some of the media items.');
}
}
@@ -4,7 +4,8 @@ namespace Drupal\Tests\media\Functional;
use Drupal\Core\Entity\EntityInterface;
use Drupal\media\Entity\Media;
use Drupal\system\Tests\Entity\EntityWithUriCacheTagsTestBase;
use Drupal\Tests\media\Traits\MediaTypeCreationTrait;
use Drupal\Tests\system\Functional\Entity\EntityWithUriCacheTagsTestBase;
/**
* Tests the media items cache tags.
@@ -13,7 +14,7 @@ use Drupal\system\Tests\Entity\EntityWithUriCacheTagsTestBase;
*/
class MediaCacheTagsTest extends EntityWithUriCacheTagsTestBase {
use MediaFunctionalTestCreateMediaTypeTrait;
use MediaTypeCreationTrait;
/**
* {@inheritdoc}
@@ -28,7 +29,7 @@ class MediaCacheTagsTest extends EntityWithUriCacheTagsTestBase {
*/
protected function createEntity() {
// Create a media type.
$mediaType = $this->createMediaType();
$mediaType = $this->createMediaType('test');
// Create a media item.
$media = Media::create([
@@ -23,7 +23,7 @@ class MediaContextualLinksTest extends MediaFunctionalTestBase {
*/
public function testMediaContextualLinks() {
// Create a media type.
$mediaType = $this->createMediaType();
$mediaType = $this->createMediaType('test');
// Create a media item.
$media = Media::create([
@@ -3,6 +3,7 @@
namespace Drupal\Tests\media\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\media\Traits\MediaTypeCreationTrait;
/**
* Base class for Media functional tests.
@@ -10,7 +11,7 @@ use Drupal\Tests\BrowserTestBase;
abstract class MediaFunctionalTestBase extends BrowserTestBase {
use MediaFunctionalTestTrait;
use MediaFunctionalTestCreateMediaTypeTrait;
use MediaTypeCreationTrait;
/**
* Modules to enable.
@@ -2,13 +2,24 @@
namespace Drupal\Tests\media\Functional;
use Drupal\media\Entity\MediaType;
@trigger_error(__NAMESPACE__ . '\MediaFunctionalTestCreateMediaTypeTrait is deprecated in Drupal 8.6.0 and will be removed before Drupal 9.0.0. Use \Drupal\Tests\media\Traits\MediaTypeCreationTrait instead. See https://www.drupal.org/node/2981614.', E_USER_DEPRECATED);
use Drupal\Tests\media\Traits\MediaTypeCreationTrait;
/**
* Trait with helpers for Media functional tests.
*
* @deprecated in Drupal 8.6.0 and will be removed before Drupal 9.0.0. Use
* \Drupal\Tests\media\Traits\MediaTypeCreationTrait instead.
*
* @see https://www.drupal.org/node/2981614
*/
trait MediaFunctionalTestCreateMediaTypeTrait {
use MediaTypeCreationTrait {
createMediaType as traitCreateMediaType;
}
/**
* Creates a media type.
*
@@ -22,52 +33,7 @@ trait MediaFunctionalTestCreateMediaTypeTrait {
* A newly created media type.
*/
protected function createMediaType(array $values = [], $source = 'test') {
if (empty($values['bundle'])) {
$id = strtolower($this->randomMachineName());
}
else {
$id = $values['bundle'];
}
$values += [
'id' => $id,
'label' => $id,
'source' => $source,
'source_configuration' => [],
'field_map' => [],
'new_revision' => FALSE,
];
$media_type = MediaType::create($values);
$status = $media_type->save();
// @todo Rename to assertSame() when #1945040 is done.
// @see https://www.drupal.org/node/1945040
$this->assertIdentical(SAVED_NEW, $status, 'Media type was created successfully.');
// Ensure that the source field exists.
/** @var \Drupal\media\MediaSourceInterface $source */
$source = $media_type->getSource();
$source_field = $source->getSourceFieldDefinition($media_type);
if (!$source_field) {
$source_field = $source->createSourceField($media_type);
/** @var \Drupal\field\FieldStorageConfigInterface $storage */
$storage = $source_field->getFieldStorageDefinition();
$storage->save();
$source_field->save();
$media_type
->set('source_configuration', [
'source_field' => $source_field->getName(),
])
->save();
}
// Move source field in form display.
entity_get_form_display('media', $id, 'default')
->setComponent($source_field->getName())
->save();
return $media_type;
return $this->traitCreateMediaType($source, $values);
}
}
@@ -34,16 +34,11 @@ class MediaInstallTest extends BrowserTestBase {
// Uninstall the media module.
$this->container->get('module_installer')->uninstall(['media'], FALSE);
// Install the media module again, through a test module that depends on it.
// Note: We use a test module because in 8.4 the media module is hidden.
// @todo Simplify this in https://www.drupal.org/node/2897028 once it's
// shown again.
$this->drupalGet('/admin/modules');
$page->checkField('modules[media_test_views][enable]');
$page->checkField('modules[media][enable]');
$page->pressButton('Install');
$assert_session->pageTextContains('Some required modules must be enabled');
$page->pressButton('Continue');
$this->assertSession()->pageTextNotContains('could not be moved/copied because a file by that name already exists in the destination directory');
$assert_session->pageTextNotContains('could not be moved/copied because a file by that name already exists in the destination directory');
$assert_session->pageTextContains('Module Media has been enabled');
}
}
@@ -41,24 +41,24 @@ class MediaOverviewPageTest extends MediaFunctionalTestBase {
$assert_session->selectExists('langcode');
$assert_session->buttonExists('Filter');
$header = $assert_session->elementExists('css', 'th#view-thumbnail-target-id-table-column');
$this->assertEquals('Thumbnail', $header->getText());
$this->assertSame('Thumbnail', $header->getText());
$header = $assert_session->elementExists('css', 'th#view-name-table-column');
$this->assertEquals('Media name', $header->getText());
$this->assertSame('Media name', $header->getText());
$header = $assert_session->elementExists('css', 'th#view-bundle-table-column');
$this->assertEquals('Type', $header->getText());
$this->assertSame('Type', $header->getText());
$header = $assert_session->elementExists('css', 'th#view-uid-table-column');
$this->assertEquals('Author', $header->getText());
$this->assertSame('Author', $header->getText());
$header = $assert_session->elementExists('css', 'th#view-status-table-column');
$this->assertEquals('Status', $header->getText());
$this->assertSame('Status', $header->getText());
$header = $assert_session->elementExists('css', 'th#view-changed-table-column');
$this->assertEquals('Updated Sort ascending', $header->getText());
$this->assertSame('Updated Sort ascending', $header->getText());
$header = $assert_session->elementExists('css', 'th#view-operations-table-column');
$this->assertEquals('Operations', $header->getText());
$assert_session->pageTextContains('No content available.');
$this->assertSame('Operations', $header->getText());
$assert_session->pageTextContains('No media available.');
// Create some content for the view.
$media_type1 = $this->createMediaType();
$media_type2 = $this->createMediaType();
$media_type1 = $this->createMediaType('test');
$media_type2 = $this->createMediaType('test');
$media1 = Media::create([
'bundle' => $media_type1->id(),
'name' => 'Media 1',
@@ -97,50 +97,50 @@ class MediaOverviewPageTest extends MediaFunctionalTestBase {
// Media names.
$name1 = $assert_session->elementExists('css', 'td.views-field-name a', $row1);
$this->assertEquals($media1->label(), $name1->getText());
$this->assertSame($media1->label(), $name1->getText());
$name2 = $assert_session->elementExists('css', 'td.views-field-name a', $row2);
$this->assertEquals($media2->label(), $name2->getText());
$this->assertSame($media2->label(), $name2->getText());
$name3 = $assert_session->elementExists('css', 'td.views-field-name a', $row3);
$this->assertEquals($media3->label(), $name3->getText());
$this->assertSame($media3->label(), $name3->getText());
$assert_session->linkByHrefExists('/media/' . $media1->id());
$assert_session->linkByHrefExists('/media/' . $media2->id());
$assert_session->linkByHrefExists('/media/' . $media3->id());
// Media types.
$type_element1 = $assert_session->elementExists('css', 'td.views-field-bundle', $row1);
$this->assertEquals($media_type1->label(), $type_element1->getText());
$this->assertSame($media_type1->label(), $type_element1->getText());
$type_element2 = $assert_session->elementExists('css', 'td.views-field-bundle', $row2);
$this->assertEquals($media_type2->label(), $type_element2->getText());
$this->assertSame($media_type2->label(), $type_element2->getText());
$type_element3 = $assert_session->elementExists('css', 'td.views-field-bundle', $row3);
$this->assertEquals($media_type1->label(), $type_element3->getText());
$this->assertSame($media_type1->label(), $type_element3->getText());
// Media authors.
$author_element1 = $assert_session->elementExists('css', 'td.views-field-uid', $row1);
$this->assertEquals($this->adminUser->getDisplayName(), $author_element1->getText());
$this->assertSame($this->adminUser->getDisplayName(), $author_element1->getText());
$author_element2 = $assert_session->elementExists('css', 'td.views-field-uid', $row2);
$this->assertEquals($this->adminUser->getDisplayName(), $author_element2->getText());
$this->assertSame($this->adminUser->getDisplayName(), $author_element2->getText());
$author_element3 = $assert_session->elementExists('css', 'td.views-field-uid', $row3);
$this->assertEquals($this->nonAdminUser->getDisplayName(), $author_element3->getText());
$this->assertSame($this->nonAdminUser->getDisplayName(), $author_element3->getText());
// Media publishing status.
$status_element1 = $assert_session->elementExists('css', 'td.views-field-status', $row1);
$this->assertEquals('Published', $status_element1->getText());
$this->assertSame('Published', $status_element1->getText());
$status_element2 = $assert_session->elementExists('css', 'td.views-field-status', $row2);
$this->assertEquals('Unpublished', $status_element2->getText());
$this->assertSame('Unpublished', $status_element2->getText());
$status_element3 = $assert_session->elementExists('css', 'td.views-field-status', $row3);
$this->assertEquals('Published', $status_element3->getText());
$this->assertSame('Published', $status_element3->getText());
// Timestamp.
$expected = \Drupal::service('date.formatter')->format($media1->getChangedTime(), 'short');
$changed_element1 = $assert_session->elementExists('css', 'td.views-field-changed', $row1);
$this->assertEquals($expected, $changed_element1->getText());
$this->assertSame($expected, $changed_element1->getText());
// Operations.
$edit_link1 = $assert_session->elementExists('css', 'td.views-field-operations li.edit a', $row1);
$this->assertEquals('Edit', $edit_link1->getText());
$this->assertSame('Edit', $edit_link1->getText());
$assert_session->linkByHrefExists('/media/' . $media1->id() . '/edit');
$delete_link1 = $assert_session->elementExists('css', 'td.views-field-operations li.delete a', $row1);
$this->assertEquals('Delete', $delete_link1->getText());
$this->assertSame('Delete', $delete_link1->getText());
$assert_session->linkByHrefExists('/media/' . $media1->id() . '/delete');
}
@@ -25,7 +25,7 @@ class MediaRevisionTest extends MediaFunctionalTestBase {
$media_storage = $this->container->get('entity.manager')->getStorage('media');
// Create a media type and media item.
$media_type = $this->createMediaType();
$media_type = $this->createMediaType('test');
$media = $media_storage->create([
'bundle' => $media_type->id(),
'name' => 'Unnamed',
@@ -80,7 +80,7 @@ class MediaRevisionTest extends MediaFunctionalTestBase {
$uri = 'temporary://foo.txt';
file_put_contents($uri, $this->randomString(128));
$this->createMediaType(['bundle' => 'file', 'new_revision' => TRUE], 'file');
$this->createMediaType('file', ['id' => 'file', 'new_revision' => TRUE]);
// Create a media item.
$this->drupalGet('/media/add/file');
@@ -88,7 +88,7 @@ class MediaRevisionTest extends MediaFunctionalTestBase {
$page->fillField('Name', 'Foobar');
$page->attachFileToField('File', $this->container->get('file_system')->realpath($uri));
$page->pressButton('Save');
$assert->addressMatches('/^\/media\/[0-9]+$/');
$assert->addressEquals('admin/content/media');
// The media item was just created, so it should only have one revision.
$media = $this->container
@@ -119,7 +119,7 @@ class MediaRevisionTest extends MediaFunctionalTestBase {
public function testImageMediaRevision() {
$assert = $this->assertSession();
$this->createMediaType(['bundle' => 'image', 'new_revision' => TRUE], 'image');
$this->createMediaType('image', ['id' => 'image', 'new_revision' => TRUE]);
/** @var \Drupal\field\FieldConfigInterface $field */
// Disable the alt text field, because this is not a JavaScript test and
@@ -135,9 +135,9 @@ class MediaRevisionTest extends MediaFunctionalTestBase {
$this->drupalGet('/media/add/image');
$page = $this->getSession()->getPage();
$page->fillField('Name', 'Foobar');
$page->attachFileToField('Image', \Drupal::root() . '/core/modules/media/tests/fixtures/example_1.jpeg');
$page->attachFileToField('Image', $this->root . '/core/modules/media/tests/fixtures/example_1.jpeg');
$page->pressButton('Save');
$assert->addressMatches('/^\/media\/[0-9]+$/');
$assert->addressEquals('admin/content/media');
// The media item was just created, so it should only have one revision.
$media = $this->container
@@ -190,8 +190,9 @@ class MediaRevisionTest extends MediaFunctionalTestBase {
$entity_type = $entity->getEntityType();
$count = $this->container
->get('entity.query')
->get($entity_type->id())
->get('entity_type.manager')
->getStorage($entity_type->id())
->getQuery()
->count()
->allRevisions()
->condition($entity_type->getKey('id'), $entity->id())
@@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\media\Functional;
/**
* Testing the media settings.
*
* @group media
*/
class MediaSettingsTest extends MediaFunctionalTestBase {
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->drupalLogin($this->createUser(['administer site configuration']));
}
/**
* Test that media warning appears if oEmbed media types exists.
*/
public function testStatusPage() {
$assert_session = $this->assertSession();
$this->drupalGet('admin/reports/status');
$assert_session->pageTextNotContains('It is potentially insecure to display oEmbed content in a frame');
$this->createMediaType('oembed:video');
$this->drupalGet('admin/reports/status');
$assert_session->pageTextContains('It is potentially insecure to display oEmbed content in a frame');
}
}
@@ -19,7 +19,7 @@ class MediaSourceFileTest extends MediaFunctionalTestBase {
$page = $session->getPage();
$assert_session = $this->assertSession();
$media_type = $this->createMediaType([], 'file');
$media_type = $this->createMediaType('file');
$media_type_id = $media_type->id();
$this->assertSame('txt doc docx pdf', FieldConfig::load("media.$media_type_id.field_media_file")->get('settings')['file_extensions']);
@@ -43,7 +43,7 @@ class MediaSourceFileTest extends MediaFunctionalTestBase {
* Ensure source field deletion is not possible.
*/
public function testPreventSourceFieldDeletion() {
$media_type = $this->createMediaType([], 'file');
$media_type = $this->createMediaType('file');
$media_type_id = $media_type->id();
$this->drupalGet("admin/structure/media/manage/$media_type_id/fields/media.$media_type_id.field_media_file/delete");
@@ -22,8 +22,7 @@ class MediaTemplateSuggestionsTest extends MediaFunctionalTestBase {
* Tests template suggestions from media_theme_suggestions_media().
*/
public function testMediaThemeHookSuggestions() {
$media_type = $this->createMediaType([
'new_revision' => FALSE,
$media_type = $this->createMediaType('test', [
'queue_thumbnail_downloads' => FALSE,
]);
@@ -40,7 +39,7 @@ class MediaTemplateSuggestionsTest extends MediaFunctionalTestBase {
$variables['elements'] = $build;
$suggestions = \Drupal::moduleHandler()->invokeAll('theme_suggestions_media', [$variables]);
$this->assertEquals($suggestions, ['media__full', 'media__' . $media_type->id(), 'media__' . $media_type->id() . '__full'], 'Found expected media suggestions.');
$this->assertSame($suggestions, ['media__full', 'media__' . $media_type->id(), 'media__' . $media_type->id() . '__full', 'media__source_' . $media_type->getSource()->getPluginId()], 'Found expected media suggestions.');
}
}
@@ -43,8 +43,7 @@ class MediaUiFunctionalTest extends MediaFunctionalTestBase {
$page = $session->getPage();
$assert_session = $this->assertSession();
$media_type = $this->createMediaType([
'new_revision' => FALSE,
$media_type = $this->createMediaType('test', [
'queue_thumbnail_downloads' => FALSE,
]);
@@ -61,14 +60,18 @@ class MediaUiFunctionalTest extends MediaFunctionalTestBase {
$source_field = $this->randomString();
$page->fillField('field_media_test[0][value]', $source_field);
$page->pressButton('Save');
$media_id = $this->container->get('entity.query')->get('media')->execute();
$media_id = $this->container->get('entity_type.manager')
->getStorage('media')
->getQuery()
->execute();
$media_id = reset($media_id);
/** @var \Drupal\media\MediaInterface $media */
$media = $this->container->get('entity_type.manager')
->getStorage('media')
->loadUnchanged($media_id);
$this->assertEquals($media->getRevisionLogMessage(), $revision_log_message);
$this->assertEquals($media->getName(), $media_name);
$this->assertSame($media->getRevisionLogMessage(), $revision_log_message);
$this->assertSame($media->getName(), $media_name);
$this->drupalGet('media/' . $media_id);
$assert_session->titleEquals($media_name . ' | Drupal');
// Tests media edit form.
@@ -84,7 +87,8 @@ class MediaUiFunctionalTest extends MediaFunctionalTestBase {
$media = $this->container->get('entity_type.manager')
->getStorage('media')
->loadUnchanged($media_id);
$this->assertEquals($media->getName(), $media_name2);
$this->assertSame($media->getName(), $media_name2);
$this->drupalGet('media/' . $media_id);
$assert_session->titleEquals($media_name2 . ' | Drupal');
// Test that there is no empty vertical tabs element, if the container is
@@ -111,12 +115,13 @@ class MediaUiFunctionalTest extends MediaFunctionalTestBase {
$page->fillField('name[0][value]', $media_name);
$page->fillField('revision_log_message[0][value]', $revision_log_message);
$page->pressButton('Save');
$this->drupalGet('media/' . $media_id);
$assert_session->titleEquals($media_name . ' | Drupal');
/** @var \Drupal\media\MediaInterface $media */
$media = $this->container->get('entity_type.manager')
->getStorage('media')
->loadUnchanged($media_id);
$this->assertEquals($media->getRevisionLogMessage(), $revision_log_message);
$this->assertSame($media->getRevisionLogMessage(), $revision_log_message);
$this->assertNotEquals($previous_revision_id, $media->getRevisionId());
// Test the status checkbox.
@@ -148,10 +153,10 @@ class MediaUiFunctionalTest extends MediaFunctionalTestBase {
$assert_session = $this->assertSession();
// Tests and creates the first media type.
$first_media_type = $this->createMediaType(['description' => $this->randomMachineName(32)]);
$first_media_type = $this->createMediaType('test', ['description' => $this->randomMachineName()]);
// Test and create a second media type.
$second_media_type = $this->createMediaType(['description' => $this->randomMachineName(32)]);
$second_media_type = $this->createMediaType('test', ['description' => $this->randomMachineName()]);
// Test if media/add displays two media type options.
$this->drupalGet('media/add');
@@ -173,6 +178,7 @@ class MediaUiFunctionalTest extends MediaFunctionalTestBase {
$this->drupalGet('media/' . $first_media_item->id());
$assert_session->statusCodeEquals(200);
$assert_session->pageTextContains($first_media_item->getName());
$assert_session->elementsCount('css', '.media--view-mode-full', 1);
// Go to second media item.
$this->drupalGet('media/' . $second_media_item->id());
@@ -280,7 +286,10 @@ class MediaUiFunctionalTest extends MediaFunctionalTestBase {
$create_media_types[] = "media_type_$id";
$permissions[] = "create media_type_$id media";
}
$this->createMediaType(['bundle' => "media_type_$id"]);
$this->createMediaType('test', [
'id' => "media_type_$id",
'label' => "media_type_$id",
]);
$media_types["media_type_$id"] = "media_type_$id";
}
@@ -427,6 +436,49 @@ class MediaUiFunctionalTest extends MediaFunctionalTestBase {
}
}
/**
* Tests the redirect URL after creating a media item.
*/
public function testMediaCreateRedirect() {
$session = $this->getSession();
$page = $session->getPage();
$assert_session = $this->assertSession();
$this->createMediaType('test', [
'queue_thumbnail_downloads' => FALSE,
]);
// Test a redirect to the media canonical URL for a user without the 'access
// media overview' permission.
$this->drupalLogin($this->drupalCreateUser([
'view media',
'create media',
]));
$this->drupalGet('media/add');
$page->fillField('name[0][value]', $this->randomMachineName());
$page->fillField('field_media_test[0][value]', $this->randomString());
$page->pressButton('Save');
$media_id = $this->container->get('entity_type.manager')
->getStorage('media')
->getQuery()
->execute();
$media_id = reset($media_id);
$assert_session->addressEquals('media/' . $media_id);
// Test a redirect to the media overview for a user with the 'access media
// overview' permission.
$this->drupalLogin($this->drupalCreateUser([
'view media',
'create media',
'access media overview',
]));
$this->drupalGet('media/add');
$page->fillField('name[0][value]', $this->randomMachineName());
$page->fillField('field_media_test[0][value]', $this->randomString());
$page->pressButton('Save');
$assert_session->addressEquals('admin/content/media');
}
/**
* Asserts that the given texts are present exactly once.
*
@@ -480,7 +532,7 @@ class MediaUiFunctionalTest extends MediaFunctionalTestBase {
$this->assertNotEmpty($link);
foreach ($attributes as $attribute => $value) {
$this->assertEquals($link->getAttribute($attribute), $value);
$this->assertSame($link->getAttribute($attribute), $value);
}
}
@@ -509,7 +561,7 @@ class MediaUiFunctionalTest extends MediaFunctionalTestBase {
$this->container->get('module_installer')->uninstall(['views']);
// Create a media type and media item.
$media_type = $this->createMediaType();
$media_type = $this->createMediaType('test');
$media = $media_storage->create([
'bundle' => $media_type->id(),
'name' => 'Unnamed',
@@ -0,0 +1,89 @@
<?php
namespace Drupal\Tests\media\Functional;
use Drupal\media\OEmbed\ProviderException;
/**
* Tests the oEmbed provider repository.
*
* @covers \Drupal\media\OEmbed\ProviderRepository
*
* @group media
*/
class ProviderRepositoryTest extends MediaFunctionalTestBase {
/**
* Tests that provider discovery fails if the provider database is empty.
*
* @param string $content
* The expected JSON content of the provider database.
*
* @dataProvider providerEmptyProviderList
*/
public function testEmptyProviderList($content) {
$response = $this->prophesize('\GuzzleHttp\Psr7\Response');
$response->getBody()->willReturn($content);
$client = $this->createMock('\GuzzleHttp\Client');
$client->method('request')->withAnyParameters()->willReturn($response->reveal());
$this->container->set('http_client', $client);
$this->setExpectedException(ProviderException::class, 'Remote oEmbed providers database returned invalid or empty list.');
$this->container->get('media.oembed.provider_repository')->getAll();
}
/**
* Data provider for testEmptyProviderList().
*
* @see ::testEmptyProviderList()
*
* @return array
*/
public function providerEmptyProviderList() {
return [
'empty array' => ['[]'],
'empty string' => [''],
];
}
/**
* Tests that provider discovery fails with a non-existent provider database.
*
* @param string $providers_url
* The URL of the provider database.
* @param string $exception_message
* The expected exception message.
*
* @dataProvider providerNonExistingProviderDatabase
*/
public function testNonExistingProviderDatabase($providers_url, $exception_message) {
$this->config('media.settings')
->set('oembed_providers_url', $providers_url)
->save();
$this->setExpectedException(ProviderException::class, $exception_message);
$this->container->get('media.oembed.provider_repository')->getAll();
}
/**
* Data provider for testEmptyProviderList().
*
* @see ::testEmptyProviderList()
*
* @return array
*/
public function providerNonExistingProviderDatabase() {
return [
[
'http://oembed1.com/providers.json',
'Could not retrieve the oEmbed provider database from http://oembed1.com/providers.json',
],
[
'http://oembed.com/providers1.json',
'Could not retrieve the oEmbed provider database from http://oembed.com/providers1.json',
],
];
}
}
@@ -0,0 +1,72 @@
<?php
namespace Drupal\Tests\media\Functional;
use Drupal\media\OEmbed\Resource;
use Drupal\Tests\media\Traits\OEmbedTestTrait;
/**
* Tests the oEmbed resource fetcher service.
*
* @coversDefaultClass \Drupal\media\OEmbed\ResourceFetcher
*
* @group media
*/
class ResourceFetcherTest extends MediaFunctionalTestBase {
use OEmbedTestTrait;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->useFixtureProviders();
$this->lockHttpClientToFixtures();
}
/**
* Data provider for testFetchResource().
*
* @return array
*/
public function providerFetchResource() {
return [
'JSON resource' => [
'video_vimeo.json',
'Vimeo',
'Drupal Rap Video - Schipulcon09',
],
'XML resource' => [
'video_collegehumor.xml',
'CollegeHumor',
"Let's Not Get a Drink Sometime",
],
];
}
/**
* Tests resource fetching.
*
* @param string $resource_url
* The URL of the resource to fetch, relative to the base URL.
* @param string $provider_name
* The expected name of the resource provider.
* @param string $title
* The expected title of the resource.
*
* @covers ::fetchResource
*
* @dataProvider providerFetchResource
*/
public function testFetchResource($resource_url, $provider_name, $title) {
/** @var \Drupal\media\OEmbed\Resource $resource */
$resource = $this->container->get('media.oembed.resource_fetcher')
->fetchResource($resource_url);
$this->assertInstanceOf(Resource::class, $resource);
$this->assertSame($provider_name, $resource->getProvider()->getName());
$this->assertSame($title, $resource->getTitle());
}
}
@@ -0,0 +1,24 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
/**
* @group rest
*/
class MediaJsonAnonTest extends MediaResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
}
@@ -0,0 +1,34 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group rest
*/
class MediaJsonBasicAuthTest extends MediaResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}
@@ -0,0 +1,29 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group rest
*/
class MediaJsonCookieTest extends MediaResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}
@@ -0,0 +1,431 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\media\Entity\Media;
use Drupal\media\Entity\MediaType;
use Drupal\rest\RestResourceConfigInterface;
use Drupal\Tests\rest\Functional\BcTimestampNormalizerUnixTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase;
use Drupal\user\Entity\Role;
use Drupal\user\Entity\User;
use Drupal\user\RoleInterface;
use GuzzleHttp\RequestOptions;
abstract class MediaResourceTestBase extends EntityResourceTestBase {
use BcTimestampNormalizerUnixTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['media'];
/**
* {@inheritdoc}
*/
protected static $entityTypeId = 'media';
/**
* @var \Drupal\media\MediaInterface
*/
protected $entity;
/**
* {@inheritdoc}
*/
protected static $patchProtectedFieldNames = [
'changed' => NULL,
];
/**
* {@inheritdoc}
*/
protected function setUpAuthorization($method) {
switch ($method) {
case 'GET':
$this->grantPermissionsToTestedRole(['view media']);
break;
case 'POST':
$this->grantPermissionsToTestedRole(['create camelids media', 'access content']);
break;
case 'PATCH':
$this->grantPermissionsToTestedRole(['edit any camelids media']);
// @todo Remove this in https://www.drupal.org/node/2824851.
$this->grantPermissionsToTestedRole(['access content']);
break;
case 'DELETE':
$this->grantPermissionsToTestedRole(['delete any camelids media']);
break;
}
}
/**
* {@inheritdoc}
*/
protected function createEntity() {
if (!MediaType::load('camelids')) {
// Create a "Camelids" media type.
$media_type = MediaType::create([
'name' => 'Camelids',
'id' => 'camelids',
'description' => 'Camelids are large, strictly herbivorous animals with slender necks and long legs.',
'source' => 'file',
]);
$media_type->save();
// Create the source field.
$source_field = $media_type->getSource()->createSourceField($media_type);
$source_field->getFieldStorageDefinition()->save();
$source_field->save();
$media_type
->set('source_configuration', [
'source_field' => $source_field->getName(),
])
->save();
}
// Create a file to upload.
$file = File::create([
'uri' => 'public://llama.txt',
]);
$file->setPermanent();
$file->save();
// Create a "Llama" media item.
$media = Media::create([
'bundle' => 'camelids',
'field_media_file' => [
'target_id' => $file->id(),
],
]);
$media
->setName('Llama')
->setPublished()
->setCreatedTime(123456789)
->setOwnerId(static::$auth ? $this->account->id() : 0)
->setRevisionUserId(static::$auth ? $this->account->id() : 0)
->save();
return $media;
}
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedEntity() {
$file = File::load(1);
$thumbnail = File::load(2);
$author = User::load($this->entity->getOwnerId());
return [
'mid' => [
[
'value' => 1,
],
],
'uuid' => [
[
'value' => $this->entity->uuid(),
],
],
'vid' => [
[
'value' => 1,
],
],
'langcode' => [
[
'value' => 'en',
],
],
'bundle' => [
[
'target_id' => 'camelids',
'target_type' => 'media_type',
'target_uuid' => MediaType::load('camelids')->uuid(),
],
],
'name' => [
[
'value' => 'Llama',
],
],
'field_media_file' => [
[
'description' => NULL,
'display' => NULL,
'target_id' => (int) $file->id(),
'target_type' => 'file',
'target_uuid' => $file->uuid(),
'url' => $file->url(),
],
],
'thumbnail' => [
[
'alt' => 'Thumbnail',
'width' => 180,
'height' => 180,
'target_id' => (int) $thumbnail->id(),
'target_type' => 'file',
'target_uuid' => $thumbnail->uuid(),
'title' => 'Llama',
'url' => $thumbnail->url(),
],
],
'status' => [
[
'value' => TRUE,
],
],
'created' => [
$this->formatExpectedTimestampItemValues(123456789),
],
'changed' => [
$this->formatExpectedTimestampItemValues($this->entity->getChangedTime()),
],
'revision_created' => [
$this->formatExpectedTimestampItemValues((int) $this->entity->getRevisionCreationTime()),
],
'default_langcode' => [
[
'value' => TRUE,
],
],
'uid' => [
[
'target_id' => (int) $author->id(),
'target_type' => 'user',
'target_uuid' => $author->uuid(),
'url' => base_path() . 'user/' . $author->id(),
],
],
'revision_user' => [
[
'target_id' => (int) $author->id(),
'target_type' => 'user',
'target_uuid' => $author->uuid(),
'url' => base_path() . 'user/' . $author->id(),
],
],
'revision_log_message' => [],
'revision_translation_affected' => [
[
'value' => TRUE,
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPostEntity() {
return [
'bundle' => [
[
'target_id' => 'camelids',
],
],
'name' => [
[
'value' => 'Dramallama',
],
],
'field_media_file' => [
[
'description' => NULL,
'display' => NULL,
'target_id' => 3,
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPatchEntity() {
return array_diff_key($this->getNormalizedPostEntity(), ['field_media_file' => TRUE]);
}
/**
* {@inheritdoc}
*/
protected function getExpectedUnauthorizedAccessMessage($method) {
if ($this->config('rest.settings')->get('bc_entity_resource_permissions')) {
return parent::getExpectedUnauthorizedAccessMessage($method);
}
switch ($method) {
case 'GET';
return "The 'view media' permission is required and the media item must be published.";
case 'POST':
return "The following permissions are required: 'administer media' OR 'create media' OR 'create camelids media'.";
case 'PATCH':
return "The following permissions are required: 'update any media' OR 'update own media' OR 'camelids: edit any media' OR 'camelids: edit own media'.";
case 'DELETE':
return "The following permissions are required: 'delete any media' OR 'delete own media' OR 'camelids: delete any media' OR 'camelids: delete own media'.";
default:
return parent::getExpectedUnauthorizedAccessMessage($method);
}
}
/**
* {@inheritdoc}
*/
public function testPost() {
$file_storage = $this->container->get('entity_type.manager')->getStorage('file');
// Step 1: upload file, results in File entity marked temporary.
$this->uploadFile();
$file = $file_storage->loadUnchanged(3);
$this->assertTrue($file->isTemporary());
$this->assertFalse($file->isPermanent());
// Step 2: create Media entity using the File, makes File entity permanent.
parent::testPost();
$file = $file_storage->loadUnchanged(3);
$this->assertFalse($file->isTemporary());
$this->assertTrue($file->isPermanent());
}
/**
* This duplicates some of the 'file_upload' REST resource plugin test
* coverage, to be able to test it on a concrete use case.
*/
protected function uploadFile() {
// Enable the 'file_upload' REST resource for the current format + auth.
$this->resourceConfigStorage->create([
'id' => 'file.upload',
'granularity' => RestResourceConfigInterface::RESOURCE_GRANULARITY,
'configuration' => [
'methods' => ['POST'],
'formats' => [static::$format],
'authentication' => isset(static::$auth) ? [static::$auth] : [],
],
'status' => TRUE,
])->save();
$this->refreshTestStateAfterRestConfigChange();
$this->initAuthentication();
// POST to create a File entity.
$url = Url::fromUri('base:file/upload/media/camelids/field_media_file');
$url->setOption('query', ['_format' => static::$format]);
$request_options = [];
$request_options[RequestOptions::HEADERS] = [
// Set the required (and only accepted) content type for the request.
'Content-Type' => 'application/octet-stream',
// Set the required Content-Disposition header for the file name.
'Content-Disposition' => 'file; filename="drupal rocks 🤘.txt"',
];
$request_options[RequestOptions::BODY] = 'Drupal is the best!';
$request_options = NestedArray::mergeDeep($request_options, $this->getAuthenticationRequestOptions('POST'));
$response = $this->request('POST', $url, $request_options);
$this->assertResourceErrorResponse(403, $this->getExpectedUnauthorizedAccessMessage('POST'), $response);
// Grant necessary permission, retry.
$this->grantPermissionsToTestedRole(['create camelids media']);
$response = $this->request('POST', $url, $request_options);
$this->assertSame(201, $response->getStatusCode());
$expected = $this->getExpectedNormalizedFileEntity();
static::recursiveKSort($expected);
$actual = $this->serializer->decode((string) $response->getBody(), static::$format);
static::recursiveKSort($actual);
$this->assertSame($expected, $actual);
// To still run the complete test coverage for POSTing a Media entity, we
// must revoke the additional permissions that we granted.
$role = Role::load(static::$auth ? RoleInterface::AUTHENTICATED_ID : RoleInterface::AUTHENTICATED_ID);
$role->revokePermission('create camelids media');
$role->trustData()->save();
}
/**
* Gets the expected file entity.
*
* @return array
* The expected normalized data array.
*/
protected function getExpectedNormalizedFileEntity() {
$file = File::load(3);
$owner = static::$auth ? $this->account : User::load(0);
return [
'fid' => [
[
'value' => 3,
],
],
'uuid' => [
[
'value' => $file->uuid(),
],
],
'langcode' => [
[
'value' => 'en',
],
],
'uid' => [
[
'target_id' => (int) $owner->id(),
'target_type' => 'user',
'target_uuid' => $owner->uuid(),
'url' => base_path() . 'user/' . $owner->id(),
],
],
'filename' => [
[
'value' => 'drupal rocks 🤘.txt',
],
],
'uri' => [
[
'value' => 'public://' . date('Y-m') . '/drupal rocks 🤘.txt',
'url' => base_path() . $this->siteDirectory . '/files/' . date('Y-m') . '/drupal%20rocks%20%F0%9F%A4%98.txt',
],
],
'filemime' => [
[
'value' => 'text/plain',
],
],
'filesize' => [
[
'value' => 19,
],
],
'status' => [
[
'value' => FALSE,
],
],
'created' => [
$this->formatExpectedTimestampItemValues($file->getCreatedTime()),
],
'changed' => [
$this->formatExpectedTimestampItemValues($file->getChangedTime()),
],
];
}
/**
* {@inheritdoc}
*/
protected function getExpectedUnauthorizedAccessCacheability() {
// @see \Drupal\media\MediaAccessControlHandler::checkAccess()
return parent::getExpectedUnauthorizedAccessCacheability()
->addCacheTags(['media:1']);
}
}
@@ -0,0 +1,24 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
/**
* @group rest
*/
class MediaTypeJsonAnonTest extends MediaTypeResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
}
@@ -0,0 +1,34 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group rest
*/
class MediaTypeJsonBasicAuthTest extends MediaTypeResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}
@@ -0,0 +1,29 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group rest
*/
class MediaTypeJsonCookieTest extends MediaTypeResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}
@@ -0,0 +1,78 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\media\Entity\MediaType;
use Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase;
abstract class MediaTypeResourceTestBase extends EntityResourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['media'];
/**
* {@inheritdoc}
*/
protected static $entityTypeId = 'media_type';
/**
* @var \Drupal\media\MediaTypeInterface
*/
protected $entity;
/**
* {@inheritdoc}
*/
protected function setUpAuthorization($method) {
$this->grantPermissionsToTestedRole(['administer media types']);
}
/**
* {@inheritdoc}
*/
protected function createEntity() {
// Create a "Camelids" media type.
$camelids = MediaType::create([
'name' => 'Camelids',
'id' => 'camelids',
'description' => 'Camelids are large, strictly herbivorous animals with slender necks and long legs.',
'source' => 'file',
]);
$camelids->save();
return $camelids;
}
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedEntity() {
return [
'dependencies' => [],
'description' => 'Camelids are large, strictly herbivorous animals with slender necks and long legs.',
'field_map' => [],
'id' => 'camelids',
'label' => NULL,
'langcode' => 'en',
'new_revision' => FALSE,
'queue_thumbnail_downloads' => FALSE,
'source' => 'file',
'source_configuration' => [
'source_field' => '',
],
'status' => TRUE,
'uuid' => $this->entity->uuid(),
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPostEntity() {
// @todo Update in https://www.drupal.org/node/2300677.
}
}
@@ -0,0 +1,26 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class MediaTypeXmlAnonTest extends MediaTypeResourceTestBase {
use AnonResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
}
@@ -0,0 +1,36 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class MediaTypeXmlBasicAuthTest extends MediaTypeResourceTestBase {
use BasicAuthResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}
@@ -0,0 +1,31 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class MediaTypeXmlCookieTest extends MediaTypeResourceTestBase {
use CookieResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}
@@ -0,0 +1,26 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class MediaXmlAnonTest extends MediaResourceTestBase {
use AnonResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
}
@@ -0,0 +1,36 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class MediaXmlBasicAuthTest extends MediaResourceTestBase {
use BasicAuthResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}
@@ -0,0 +1,31 @@
<?php
namespace Drupal\Tests\media\Functional\Rest;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class MediaXmlCookieTest extends MediaResourceTestBase {
use CookieResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}
@@ -9,6 +9,7 @@ use Drupal\user\Entity\Role;
* Tests that media settings are properly updated during database updates.
*
* @group media
* @group legacy
*/
class MediaUpdateTest extends UpdatePathTestBase {
@@ -17,8 +18,9 @@ class MediaUpdateTest extends UpdatePathTestBase {
*/
protected function setDatabaseDumpFiles() {
$this->databaseDumpFiles = [
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
__DIR__ . '/../../../fixtures/update/drupal-8.media-enabled.php',
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.4.0.bare.standard.php.gz',
__DIR__ . '/../../../fixtures/update/drupal-8.4.0-media_installed.php',
__DIR__ . '/../../../fixtures/update/drupal-8.media-add-additional-permissions.php',
];
}
@@ -28,16 +30,6 @@ class MediaUpdateTest extends UpdatePathTestBase {
* @see media_update_8500()
*/
public function testBundlePermission() {
$role = Role::load(Role::AUTHENTICATED_ID);
$this->grantPermissions($role, [
'update media',
'update any media',
'delete media',
'delete any media',
'create media',
]);
$this->runUpdates();
/** @var \Drupal\user\RoleInterface $role */
@@ -53,4 +45,21 @@ class MediaUpdateTest extends UpdatePathTestBase {
}
}
/**
* Tests that media.settings config is updated with oEmbed configuration.
*
* @see media_update_8600()
*/
public function testOEmbedConfig() {
$config = $this->config('media.settings');
$this->assertNull($config->get('oembed_providers_url'));
$this->assertNull($config->get('iframe_domain'));
$this->runUpdates();
$config = $this->config('media.settings');
$this->assertSame('https://oembed.com/providers.json', $config->get('oembed_providers_url'));
$this->assertSame('', $config->get('iframe_domain'));
}
}
@@ -0,0 +1,133 @@
<?php
namespace Drupal\Tests\media\Functional;
use Drupal\Tests\media\Traits\OEmbedTestTrait;
/**
* Tests the oEmbed URL resolver service.
*
* @coversDefaultClass \Drupal\media\OEmbed\UrlResolver
*
* @group media
*/
class UrlResolverTest extends MediaFunctionalTestBase {
use OEmbedTestTrait;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->lockHttpClientToFixtures();
$this->useFixtureProviders();
}
/**
* Data provider for testEndpointMatching().
*
* @see ::testEndpointMatching()
*
* @return array
*/
public function providerEndpointMatching() {
return [
'match by endpoint: Twitter' => [
'https://twitter.com/Dries/status/999985431595880448',
'https://publish.twitter.com/oembed?url=https%3A//twitter.com/Dries/status/999985431595880448',
],
'match by endpoint: Vimeo' => [
'https://vimeo.com/14782834',
'https://vimeo.com/api/oembed.json?url=https%3A//vimeo.com/14782834',
],
'match by endpoint: CollegeHumor' => [
'http://www.collegehumor.com/video/40002870/lets-not-get-a-drink-sometime',
'http://www.collegehumor.com/oembed.json?url=http%3A//www.collegehumor.com/video/40002870/lets-not-get-a-drink-sometime',
],
];
}
/**
* Tests resource URL resolution when the asset URL can be matched to a
* provider endpoint.
*
* @covers ::getProviderByUrl
* @covers ::getResourceUrl
*
* @param string $url
* The asset URL to resolve.
* @param string $resource_url
* The expected oEmbed resource URL of the asset.
*
* @dataProvider providerEndpointMatching
*/
public function testEndpointMatching($url, $resource_url) {
$this->assertSame(
$resource_url,
$this->container->get('media.oembed.url_resolver')->getResourceUrl($url)
);
}
/**
* Tests that hook_oembed_resource_url_alter() is invoked.
*
* @depends testEndpointMatching
*/
public function testResourceUrlAlterHook() {
$this->container->get('module_installer')->install(['media_test_oembed']);
$resource_url = $this->container->get('media.oembed.url_resolver')
->getResourceUrl('https://vimeo.com/14782834');
$this->assertContains('altered=1', parse_url($resource_url, PHP_URL_QUERY));
}
/**
* Data provider for testUrlDiscovery().
*
* @see ::testUrlDiscovery()
*
* @return array
*/
public function providerUrlDiscovery() {
return [
'JSON resource' => [
'video_vimeo.html',
'https://vimeo.com/api/oembed.json?url=video_vimeo.html',
],
'XML resource' => [
'video_collegehumor.html',
// The endpoint does not explicitly declare that it supports XML, so
// only JSON support is assumed, which is why the discovered URL
// contains '.json'. However, the fetched HTML file contains a
// relationship to an XML representation of the resource, with the
// application/xml+oembed MIME type.
'http://www.collegehumor.com/oembed.json?url=video_collegehumor.html',
],
];
}
/**
* Tests URL resolution when the resource URL must be actively discovered by
* scanning the asset.
*
* @param string $url
* The asset URL to resolve.
* @param string $resource_url
* The expected oEmbed resource URL of the asset.
*
* @covers ::discoverResourceUrl
* @covers ::getProviderByUrl
* @covers ::getResourceUrl
*
* @dataProvider providerUrlDiscovery
*/
public function testUrlDiscovery($url, $resource_url) {
$this->assertSame(
$this->container->get('media.oembed.url_resolver')->getResourceUrl($url),
$resource_url
);
}
}
@@ -39,7 +39,7 @@ class MediaDisplayTest extends MediaJavascriptTestBase {
$assert_session = $this->assertSession();
$page = $this->getSession()->getPage();
$media_type = $this->createMediaType();
$media_type = $this->createMediaType('test');
// Create a media item.
$media = Media::create([
@@ -54,6 +54,8 @@ class MediaDisplayTest extends MediaJavascriptTestBase {
// Enable the field on the display and verify it becomes visible on the UI.
$this->drupalGet("/admin/structure/media/manage/{$media_type->id()}/display");
$assert_session->buttonExists('Show row weights')->press();
$this->assertSession()->waitForElementVisible('css', '[name="fields[name][region]"]');
$page->selectFieldOption('fields[name][region]', 'content');
$assert_session->waitForElementVisible('css', '#edit-fields-name-settings-edit');
$page->pressButton('Save');
@@ -61,33 +63,39 @@ class MediaDisplayTest extends MediaJavascriptTestBase {
// Verify the name is present, and its text matches what is expected.
$assert_session->elementExists('css', '.field--name-name');
$name_field = $page->find('css', '.field--name-name .field__item');
$this->assertEquals($media->label(), $name_field->getText());
$this->assertSame($media->label(), $name_field->getText());
// In the standard profile, there are some pre-cooked types. Make sure the
// elements configured on their displays are the expected ones.
$this->drupalGet('media/add/image');
$image_media_name = 'Fantastic image asset!';
$page->fillField('name[0][value]', $image_media_name);
$page->attachFileToField('files[field_media_image_0]', \Drupal::root() . '/core/modules/media/tests/fixtures/example_1.jpeg');
$page->attachFileToField('files[field_media_image_0]', $this->root . '/core/modules/media/tests/fixtures/example_1.jpeg');
$result = $assert_session->waitForButton('Remove');
$this->assertNotEmpty($result);
$page->fillField('field_media_image[0][alt]', 'Image Alt Text 1');
$page->pressButton('Save');
$image_media_id = $this->container->get('entity.query')->get('media')
$image_media_id = $this->container
->get('entity_type.manager')
->getStorage('media')
->getQuery()
->sort('mid', 'DESC')
->execute();
$image_media_id = reset($image_media_id);
// Go to the media entity view.
$this->drupalGet('/media/' . $image_media_id);
// Here we expect to see only the image, nothing else.
// Assert only one element in the content region.
$this->assertEquals(1, count($page->findAll('css', '.media--type-image > div')));
$this->assertSame(1, count($page->findAll('css', '.media--type-image > div')));
// Assert the image is present inside the media element.
$media_item = $assert_session->elementExists('css', '.media--type-image > div');
$assert_session->elementExists('css', 'img', $media_item);
// Assert that the image src is the original image and not an image style.
$media_image = $assert_session->elementExists('css', '.media--type-image img');
$expected_image_src = file_url_transform_relative(file_create_url(\Drupal::token()->replace('public://[date:custom:Y]-[date:custom:m]/example_1.jpeg')));
$this->assertEquals($expected_image_src, $media_image->getAttribute('src'));
$this->assertSame($expected_image_src, $media_image->getAttribute('src'));
$test_filename = $this->randomMachineName() . '.txt';
$test_filepath = 'public://' . $test_filename;
@@ -99,13 +107,16 @@ class MediaDisplayTest extends MediaJavascriptTestBase {
$this->assertNotEmpty($result);
$page->pressButton('Save');
// Go to the media entity view.
$this->drupalGet($this->assertLinkToCreatedMedia());
// Here we expect to see only the linked filename.
// Assert only one element in the content region.
$this->assertEquals(1, count($page->findAll('css', 'article.media--type-file > div')));
$this->assertSame(1, count($page->findAll('css', 'article.media--type-file > div')));
// Assert the file link is present, and its text matches the filename.
$assert_session->elementExists('css', 'article.media--type-file .field--name-field-media-file a');
$link = $page->find('css', 'article.media--type-file .field--name-field-media-file a');
$this->assertEquals($test_filename, $link->getText());
$this->assertSame($test_filename, $link->getText());
// Create a node type "page" to use as host entity.
$node_type = NodeType::create([
@@ -165,7 +176,7 @@ class MediaDisplayTest extends MediaJavascriptTestBase {
$assert_session->elementNotExists('css', '.field--name-name');
$assert_session->pageTextNotContains($image_media_name);
// Only one element is present inside the media container.
$this->assertEquals(1, count($page->findAll('css', '.field--name-field-related-media article.media--type-image > div')));
$this->assertSame(1, count($page->findAll('css', '.field--name-field-related-media article.media--type-image > div')));
// Assert the image is present.
$assert_session->elementExists('css', '.field--name-field-related-media article.media--type-image img');
}
@@ -2,17 +2,17 @@
namespace Drupal\Tests\media\FunctionalJavascript;
use Drupal\FunctionalJavascriptTests\JavascriptTestBase;
use Drupal\Tests\media\Functional\MediaFunctionalTestCreateMediaTypeTrait;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
use Drupal\Tests\media\Functional\MediaFunctionalTestTrait;
use Drupal\Tests\media\Traits\MediaTypeCreationTrait;
/**
* Base class for Media functional JavaScript tests.
*/
abstract class MediaJavascriptTestBase extends JavascriptTestBase {
abstract class MediaJavascriptTestBase extends WebDriverTestBase {
use MediaFunctionalTestTrait;
use MediaFunctionalTestCreateMediaTypeTrait;
use MediaTypeCreationTrait;
/**
* Modules to enable.
@@ -43,4 +43,21 @@ abstract class MediaJavascriptTestBase extends JavascriptTestBase {
$this->assertJsCondition($condition, $timeout, $message);
}
/**
* Asserts that a link to a new media item is displayed in the messages area.
*
* @return string
* The link URL.
*/
protected function assertLinkToCreatedMedia() {
$assert_session = $this->assertSession();
$selector = '.messages a';
// Get the canonical media entity URL from the creation message.
$link = $assert_session->elementExists('css', $selector);
$assert_session->elementAttributeExists('css', $selector, 'href');
return $link->getAttribute('href');
}
}
@@ -49,7 +49,7 @@ class MediaReferenceFieldHelpTest extends MediaJavascriptTestBase {
$page->selectFieldOption('edit-new-storage-type', $field_name);
$field_description_element = $assert_session->elementExists('css', '#edit-description-' . Html::cleanCssIdentifier($field_name));
$this->assertTrue($field_description_element->isVisible());
$this->assertEquals($help_text, $field_description_element->getText());
$this->assertSame($help_text, $field_description_element->getText());
}
}
@@ -39,7 +39,7 @@ class MediaSourceAudioVideoTest extends MediaSourceTestBase {
$formatter = $display->getComponent($field_name)['type'];
$this->assertSame('file_audio', $formatter);
// Create a media asset and verify that the <audio> tag is present.
// Create a media asset.
file_put_contents('public://file.mp3', str_repeat('t', 10));
$file = File::create([
'uri' => 'public://file.mp3',
@@ -54,7 +54,12 @@ class MediaSourceAudioVideoTest extends MediaSourceTestBase {
$this->assertNotEmpty($result);
$page->pressButton('Save');
// Verify that there is a creation message and that it contains a link to
// the media entity.
$assert_session->pageTextContains("$type_name Audio media asset has been created.");
$this->drupalGet($this->assertLinkToCreatedMedia());
// Verify that the <audio> tag is present on the media entity view.
$assert_session->elementExists('css', "audio > source[type='audio/mpeg']");
}
@@ -83,7 +88,7 @@ class MediaSourceAudioVideoTest extends MediaSourceTestBase {
$formatter = $display->getComponent($field_name)['type'];
$this->assertSame('file_video', $formatter);
// Create a media asset and verify that the <video> tag is present.
// Create a media asset.
file_put_contents('public://file.mp4', str_repeat('t', 10));
$file = File::create([
'uri' => 'public://file.mp4',
@@ -98,7 +103,12 @@ class MediaSourceAudioVideoTest extends MediaSourceTestBase {
$this->assertNotEmpty($result);
$page->pressButton('Save');
// Verify that there is a creation message and that it contains a link to
// the media entity.
$assert_session->pageTextContains("$type_name Video media asset has been created.");
$this->drupalGet($this->assertLinkToCreatedMedia());
// Verify that the <video> tag is present on the media entity view.
$assert_session->elementExists('css', "video > source[type='video/mp4']");
}
@@ -19,6 +19,7 @@ class MediaSourceFileTest extends MediaSourceTestBase {
$media_type_id = 'test_media_file_type';
$source_field_id = 'field_media_file';
$provided_fields = [
File::METADATA_ATTRIBUTE_NAME,
File::METADATA_ATTRIBUTE_SIZE,
File::METADATA_ATTRIBUTE_MIME,
];
@@ -40,6 +41,7 @@ class MediaSourceFileTest extends MediaSourceTestBase {
$this->hideMediaTypeFieldWidget('name', $media_type_id);
$this->drupalGet("admin/structure/media/manage/{$media_type_id}");
$page->selectFieldOption("field_map[" . File::METADATA_ATTRIBUTE_NAME . "]", 'name');
$page->selectFieldOption("field_map[" . File::METADATA_ATTRIBUTE_SIZE . "]", 'field_string_file_size');
$page->selectFieldOption("field_map[" . File::METADATA_ATTRIBUTE_MIME . "]", 'field_string_mime_type');
$page->pressButton('Save');
@@ -55,7 +57,10 @@ class MediaSourceFileTest extends MediaSourceTestBase {
$this->assertNotEmpty($result);
$page->pressButton('Save');
$assert_session->addressEquals('media/1');
$assert_session->addressEquals('admin/content/media');
// Get the media entity view URL from the creation message.
$this->drupalGet($this->assertLinkToCreatedMedia());
// Make sure the thumbnail is displayed.
$assert_session->elementAttributeContains('css', '.image-style-thumbnail', 'src', 'generic.png');
@@ -69,9 +74,9 @@ class MediaSourceFileTest extends MediaSourceTestBase {
// Load the media and check that all the fields are properly populated.
$media = Media::load(1);
$this->assertEquals($test_filename, $media->getName());
$this->assertEquals('8', $media->get('field_string_file_size')->value);
$this->assertEquals('text/plain', $media->get('field_string_mime_type')->value);
$this->assertSame($test_filename, $media->getName());
$this->assertSame('8', $media->get('field_string_file_size')->value);
$this->assertSame('text/plain', $media->get('field_string_mime_type')->value);
// Test the MIME type icon.
$icon_base = \Drupal::config('media.settings')->get('icon_base_uri');
@@ -82,6 +87,23 @@ class MediaSourceFileTest extends MediaSourceTestBase {
$this->assertNotEmpty($result);
$page->pressButton('Save');
$assert_session->elementAttributeContains('css', '.image-style-thumbnail', 'src', 'text--plain.png');
// Check if the mapped name is automatically updated.
$new_filename = $this->randomMachineName() . '.txt';
$new_filepath = 'public://' . $new_filename;
file_put_contents($new_filepath, $this->randomMachineName());
$this->drupalGet("media/1/edit");
$page->pressButton('Remove');
$result = $assert_session->waitForField("files[{$source_field_id}_0]");
$this->assertNotEmpty($result);
$page->attachFileToField("files[{$source_field_id}_0]", \Drupal::service('file_system')->realpath($new_filepath));
$result = $assert_session->waitForButton('Remove');
$this->assertNotEmpty($result);
$page->pressButton('Save');
/** @var \Drupal\media\MediaInterface $media */
$media = \Drupal::entityTypeManager()->getStorage('media')->loadUnchanged(1);
$this->assertEquals($new_filename, $media->getName());
$assert_session->pageTextContains("$new_filename has been updated.");
}
}
@@ -46,22 +46,25 @@ class MediaSourceImageTest extends MediaSourceTestBase {
// Create a media item.
$this->drupalGet("media/add/{$media_type_id}");
$page->attachFileToField("files[{$source_field_id}_0]", \Drupal::root() . '/core/modules/media/tests/fixtures/example_1.jpeg');
$page->attachFileToField("files[{$source_field_id}_0]", $this->root . '/core/modules/media/tests/fixtures/example_1.jpeg');
$result = $assert_session->waitForButton('Remove');
$this->assertNotEmpty($result);
$page->fillField("{$source_field_id}[0][alt]", 'Image Alt Text 1');
$page->pressButton('Save');
$assert_session->addressEquals('media/1');
$assert_session->addressEquals('admin/content/media');
// Get the media entity view URL from the creation message.
$this->drupalGet($this->assertLinkToCreatedMedia());
// Make sure the thumbnail is displayed from uploaded image.
$assert_session->elementAttributeContains('css', '.image-style-thumbnail', 'src', 'example_1.jpeg');
// Load the media and check that all fields are properly populated.
$media = Media::load(1);
$this->assertEquals('example_1.jpeg', $media->getName());
$this->assertEquals('200', $media->get('field_string_width')->value);
$this->assertEquals('89', $media->get('field_string_height')->value);
$this->assertSame('example_1.jpeg', $media->getName());
$this->assertSame('200', $media->get('field_string_width')->value);
$this->assertSame('89', $media->get('field_string_height')->value);
}
}
@@ -0,0 +1,217 @@
<?php
namespace Drupal\Tests\media\FunctionalJavascript;
use Drupal\Core\Session\AccountInterface;
use Drupal\media\Entity\Media;
use Drupal\media_test_oembed\Controller\ResourceController;
use Drupal\Tests\media\Traits\OEmbedTestTrait;
use Drupal\user\Entity\Role;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Tests the oembed:video media source.
*
* @group media
*/
class MediaSourceOEmbedVideoTest extends MediaSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['media_test_oembed'];
use OEmbedTestTrait;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->lockHttpClientToFixtures();
}
/**
* {@inheritdoc}
*/
protected function initConfig(ContainerInterface $container) {
parent::initConfig($container);
// Enable twig debugging to make testing template usage easy.
$parameters = $container->getParameter('twig.config');
$parameters['debug'] = TRUE;
$this->setContainerParameter('twig.config', $parameters);
}
/**
* Tests the oembed media source.
*/
public function testMediaOEmbedVideoSource() {
$media_type_id = 'test_media_oembed_type';
$provided_fields = [
'type',
'title',
'default_name',
'author_name',
'author_url',
'provider_name',
'provider_url',
'cache_age',
'thumbnail_uri',
'thumbnail_width',
'thumbnail_height',
'url',
'width',
'height',
'html',
];
$session = $this->getSession();
$page = $session->getPage();
$assert_session = $this->assertSession();
$this->doTestCreateMediaType($media_type_id, 'oembed:video', $provided_fields);
// Create custom fields for the media type to store metadata attributes.
$fields = [
'field_string_width' => 'string',
'field_string_height' => 'string',
'field_string_author_name' => 'string',
];
$this->createMediaTypeFields($fields, $media_type_id);
// Hide the name field widget to test default name generation.
$this->hideMediaTypeFieldWidget('name', $media_type_id);
$this->drupalGet("admin/structure/media/manage/$media_type_id");
// Only accept Vimeo videos.
$page->checkField("source_configuration[providers][Vimeo]");
$assert_session->selectExists('field_map[width]')->setValue('field_string_width');
$assert_session->selectExists('field_map[height]')->setValue('field_string_height');
$assert_session->selectExists('field_map[author_name]')->setValue('field_string_author_name');
$assert_session->buttonExists('Save')->press();
$this->hijackProviderEndpoints();
$video_url = 'https://vimeo.com/7073899';
ResourceController::setResourceUrl($video_url, $this->getFixturesDirectory() . '/video_vimeo.json');
// Create a media item.
$this->drupalGet("media/add/$media_type_id");
$assert_session->fieldExists('Remote video URL')->setValue($video_url);
$assert_session->buttonExists('Save')->press();
$assert_session->addressEquals('admin/content/media');
// Get the media entity view URL from the creation message.
$this->drupalGet($this->assertLinkToCreatedMedia());
/** @var \Drupal\media\MediaInterface $media */
$media = Media::load(1);
// The thumbnail should have been downloaded.
$thumbnail = $media->getSource()->getMetadata($media, 'thumbnail_uri');
$this->assertFileExists($thumbnail);
// Ensure the iframe exists and that its src attribute contains a coherent
// URL with the query parameters we expect.
$iframe_url = $assert_session->elementExists('css', 'iframe')->getAttribute('src');
$iframe_url = parse_url($iframe_url);
$this->assertStringEndsWith('/media/oembed', $iframe_url['path']);
$this->assertNotEmpty($iframe_url['query']);
$query = [];
parse_str($iframe_url['query'], $query);
$this->assertSame($video_url, $query['url']);
$this->assertNotEmpty($query['hash']);
// Make sure the thumbnail is displayed from uploaded image.
$assert_session->elementAttributeContains('css', '.image-style-thumbnail', 'src', '/oembed_thumbnails/' . basename($thumbnail));
// Load the media and check that all fields are properly populated.
$media = Media::load(1);
$this->assertSame('Drupal Rap Video - Schipulcon09', $media->getName());
$this->assertSame('480', $media->field_string_width->value);
$this->assertSame('360', $media->field_string_height->value);
// Try to create a media asset from a disallowed provider.
$this->drupalGet("media/add/$media_type_id");
$assert_session->fieldExists('Remote video URL')->setValue('http://www.collegehumor.com/video/40003213/grant-and-katie-are-starting-their-own-company');
$page->pressButton('Save');
$assert_session->pageTextContains('The CollegeHumor provider is not allowed.');
// Test anonymous access to media via iframe.
$this->drupalLogout();
// Without a hash should be denied.
$no_hash_query = array_diff_key($query, ['hash' => '']);
$this->drupalGet('media/oembed', ['query' => $no_hash_query]);
$assert_session->pageTextNotContains('By the power of Greyskull, Vimeo works!');
$assert_session->pageTextContains('Access denied');
// A correct query should be allowed because the anonymous role has the
// 'view media' permission.
$this->drupalGet('media/oembed', ['query' => $query]);
$assert_session->pageTextContains('By the power of Greyskull, Vimeo works!');
$this->assertRaw('core/themes/stable/templates/content/media-oembed-iframe.html.twig');
$this->assertNoRaw('core/modules/media/templates/media-oembed-iframe.html.twig');
// Test themes not inheriting from stable.
\Drupal::service('theme_handler')->install(['stark']);
$this->config('system.theme')->set('default', 'stark')->save();
$this->drupalGet('media/oembed', ['query' => $query]);
$assert_session->pageTextContains('By the power of Greyskull, Vimeo works!');
$this->assertNoRaw('core/themes/stable/templates/content/media-oembed-iframe.html.twig');
$this->assertRaw('core/modules/media/templates/media-oembed-iframe.html.twig');
// Remove the 'view media' permission to test that this restricts access.
$role = Role::load(AccountInterface::ANONYMOUS_ROLE);
$role->revokePermission('view media');
$role->save();
$this->drupalGet('media/oembed', ['query' => $query]);
$assert_session->pageTextNotContains('By the power of Greyskull, Vimeo works!');
$assert_session->pageTextContains('Access denied');
}
/**
* Test that a security warning appears if iFrame domain is not set.
*/
public function testOEmbedSecurityWarning() {
$media_type_id = 'test_media_oembed_type';
$source_id = 'oembed:video';
$session = $this->getSession();
$page = $session->getPage();
$assert_session = $this->assertSession();
$this->drupalGet('admin/structure/media/add');
$page->fillField('label', $media_type_id);
$this->getSession()
->wait(5000, "jQuery('.machine-name-value').text() === '{$media_type_id}'");
// Make sure the source is available.
$assert_session->fieldExists('Media source');
$assert_session->optionExists('Media source', $source_id);
$page->selectFieldOption('Media source', $source_id);
$result = $assert_session->waitForElementVisible('css', 'fieldset[data-drupal-selector="edit-source-configuration"]');
$this->assertNotEmpty($result);
$assert_session->pageTextContains('It is potentially insecure to display oEmbed content in a frame');
$this->config('media.settings')->set('iframe_domain', 'http://example.com')->save();
$this->drupalGet('admin/structure/media/add');
$page->fillField('label', $media_type_id);
$this->getSession()
->wait(5000, "jQuery('.machine-name-value').text() === '{$media_type_id}'");
// Make sure the source is available.
$assert_session->fieldExists('Media source');
$assert_session->optionExists('Media source', $source_id);
$page->selectFieldOption('Media source', $source_id);
$result = $assert_session->waitForElementVisible('css', 'fieldset[data-drupal-selector="edit-source-configuration"]');
$this->assertNotEmpty($result);
$assert_session->pageTextNotContains('It is potentially insecure to display oEmbed content in a frame');
}
}
@@ -11,6 +11,45 @@ use Drupal\Component\Utility\Html;
*/
class MediaTypeCreationTest extends MediaJavascriptTestBase {
/**
* Tests the source field behavior on the add media type form.
*/
public function testSourceChangeOnMediaTypeCreationForm() {
$session = $this->getSession();
$page = $session->getPage();
$assert_session = $this->assertSession();
$label = 'Type with Default Field';
$mediaTypeMachineName = str_replace(' ', '_', strtolower($label));
$this->drupalGet('admin/structure/media/add');
// Fill in a label to the media type.
$page->fillField('label', $label);
$this->assertNotEmpty(
$assert_session->waitForElementVisible('css', '.machine-name-value')
);
// Select the media source used by our media type.
$assert_session->selectExists('Media source')->selectOption('test_different_displays');
$this->assertNotEmpty(
$assert_session->waitForElementVisible('css', 'fieldset[data-drupal-selector="edit-source-configuration"]')
);
// Change the media source.
$assert_session->selectExists('Media source')->selectOption('test');
$this->assertNotEmpty(
$assert_session->waitForElement('css', 'fieldset[data-drupal-selector="edit-source-configuration"] .fieldset-wrapper .placeholder:contains("Text (plain)")')
);
$page->pressButton('Save');
// Check that source can not be changed anymore.
$this->drupalGet("admin/structure/media/manage/{$mediaTypeMachineName}");
$assert_session->pageTextContains('The media source cannot be changed after the media type is created');
$assert_session->fieldDisabled('Media source');
}
/**
* Tests the media type creation form.
*/
@@ -24,19 +63,21 @@ class MediaTypeCreationTest extends MediaJavascriptTestBase {
$this->drupalGet('admin/structure/media/add');
// Fill in a label to the media type.
$page->fillField('label', $label);
// Wait for machine name generation. Default: waitUntilVisible(), does not
// work properly.
$session->wait(5000, "jQuery('.machine-name-value').text() === '{$mediaTypeMachineName}'");
// Select the media source used by our media type.
// Select the media source used by our media type. Do this before setting
// the label or machine name in order to guard against the regression in
// https://www.drupal.org/project/drupal/issues/2557299.
$assert_session->fieldExists('Media source');
$assert_session->optionExists('Media source', 'test');
$page->selectFieldOption('Media source', 'test');
$result = $assert_session->waitForElementVisible('css', 'fieldset[data-drupal-selector="edit-source-configuration"]');
$this->assertNotEmpty($result);
// Fill in a label to the media type.
$page->fillField('label', $label);
// Wait for machine name generation. Default: waitUntilVisible(), does not
// work properly.
$session->wait(5000, "jQuery('.machine-name-value').text() === '{$mediaTypeMachineName}'");
$page->pressButton('Save');
// Check whether the source field was correctly created.
@@ -97,11 +138,12 @@ class MediaTypeCreationTest extends MediaJavascriptTestBase {
// Create a new media type, which should create a new field we can reuse.
$this->drupalGet('/admin/structure/media/add');
$page->fillField('label', 'Pastafazoul');
$session->wait(5000, "jQuery('.machine-name-value').text() === 'pastafazoul'");
// Choose the source plugin before setting the label and machine name.
$page->selectFieldOption('Media source', 'test');
$result = $assert_session->waitForElementVisible('css', 'fieldset[data-drupal-selector="edit-source-configuration"]');
$this->assertNotEmpty($result);
$page->fillField('label', 'Pastafazoul');
$session->wait(5000, "jQuery('.machine-name-value').text() === 'pastafazoul'");
$page->pressButton('Save');
$label = 'Type reusing Default Field';
@@ -109,6 +151,16 @@ class MediaTypeCreationTest extends MediaJavascriptTestBase {
$this->drupalGet('admin/structure/media/add');
// Select the media source used by our media type. Do this before setting
// the label and machine name.
$assert_session->fieldExists('Media source');
$assert_session->optionExists('Media source', 'test');
$page->selectFieldOption('Media source', 'test');
$result = $assert_session->waitForElementVisible('css', 'fieldset[data-drupal-selector="edit-source-configuration"]');
$this->assertNotEmpty($result);
// Select the existing field for re-use.
$page->selectFieldOption('source_configuration[source_field]', 'field_media_test');
// Fill in a label to the media type.
$page->fillField('label', $label);
@@ -116,14 +168,6 @@ class MediaTypeCreationTest extends MediaJavascriptTestBase {
// work properly.
$session->wait(5000, "jQuery('.machine-name-value').text() === '{$mediaTypeMachineName}'");
// Select the media source used by our media type.
$assert_session->fieldExists('Media source');
$assert_session->optionExists('Media source', 'test');
$page->selectFieldOption('Media source', 'test');
$result = $assert_session->waitForElementVisible('css', 'fieldset[data-drupal-selector="edit-source-configuration"]');
$this->assertNotEmpty($result);
// Select the existing field for re-use.
$page->selectFieldOption('source_configuration[source_field]', 'field_media_test');
$page->pressButton('Save');
// Check that no new fields were created.
@@ -160,15 +160,15 @@ class MediaUiJavascriptTest extends MediaJavascriptTestBase {
$loaded_media_type = $this->container->get('entity_type.manager')
->getStorage('media_type')
->load($this->testMediaType->id());
$this->assertEquals($loaded_media_type->id(), $this->testMediaType->id());
$this->assertEquals($loaded_media_type->label(), $new_name);
$this->assertEquals($loaded_media_type->getDescription(), $new_description);
$this->assertEquals($loaded_media_type->getSource()->getPluginId(), 'test');
$this->assertEquals($loaded_media_type->getSource()->getConfiguration()['test_config_value'], 'This is new config value.');
$this->assertSame($loaded_media_type->id(), $this->testMediaType->id());
$this->assertSame($loaded_media_type->label(), $new_name);
$this->assertSame($loaded_media_type->getDescription(), $new_description);
$this->assertSame($loaded_media_type->getSource()->getPluginId(), 'test');
$this->assertSame($loaded_media_type->getSource()->getConfiguration()['test_config_value'], 'This is new config value.');
$this->assertTrue($loaded_media_type->shouldCreateNewRevision());
$this->assertTrue($loaded_media_type->thumbnailDownloadsAreQueued());
$this->assertFalse($loaded_media_type->getStatus());
$this->assertEquals($loaded_media_type->getFieldMap(), ['attribute_1' => 'name']);
$this->assertSame($loaded_media_type->getFieldMap(), ['attribute_1' => 'name']);
// We need to clear the statically cached field definitions to account for
// fields that have been created by API calls in this test, since they exist
@@ -191,7 +191,7 @@ class MediaUiJavascriptTest extends MediaJavascriptTestBase {
// Test that the system for preventing the deletion of media types works
// (they cannot be deleted if there is media content of that type/bundle).
$media_type2 = $this->createMediaType();
$media_type2 = $this->createMediaType('test');
$label2 = $media_type2->label();
$media = Media::create(['name' => 'lorem ipsum', 'bundle' => $media_type2->id()]);
$media->save();
@@ -22,7 +22,7 @@ class MediaViewsWizardTest extends MediaJavascriptTestBase {
$page = $session->getPage();
$assert_session = $this->assertSession();
$this->createMediaType();
$this->createMediaType('test');
$view_id = strtolower($this->randomMachineName(16));
$this->drupalGet('admin/structure/views/add');
@@ -34,19 +34,19 @@ class MediaViewsWizardTest extends MediaJavascriptTestBase {
$page->checkField('page[create]');
$page->fillField('page[path]', $this->randomMachineName(16));
$page->pressButton('Save and edit');
$this->assertEquals($session->getCurrentUrl(), $this->baseUrl . '/admin/structure/views/view/' . $view_id);
$this->assertSame($session->getCurrentUrl(), $this->baseUrl . '/admin/structure/views/view/' . $view_id);
$view = Views::getView($view_id);
$view->initHandlers();
$row = $view->display_handler->getOption('row');
$this->assertEquals($row['type'], 'fields');
$this->assertSame($row['type'], 'fields');
// Check for the default filters.
$this->assertEquals($view->filter['status']->table, 'media_field_data');
$this->assertEquals($view->filter['status']->field, 'status');
$this->assertSame($view->filter['status']->table, 'media_field_data');
$this->assertSame($view->filter['status']->field, 'status');
$this->assertTrue($view->filter['status']->value);
// Check for the default fields.
$this->assertEquals($view->field['name']->table, 'media_field_data');
$this->assertEquals($view->field['name']->field, 'name');
$this->assertSame($view->field['name']->table, 'media_field_data');
$this->assertSame($view->field['name']->field, 'name');
}
@@ -67,23 +67,23 @@ class MediaViewsWizardTest extends MediaJavascriptTestBase {
$page->checkField('page[create]');
$page->fillField('page[path]', $this->randomMachineName(16));
$page->pressButton('Save and edit');
$this->assertEquals($session->getCurrentUrl(), $this->baseUrl . '/admin/structure/views/view/' . $view_id);
$this->assertSame($session->getCurrentUrl(), $this->baseUrl . '/admin/structure/views/view/' . $view_id);
$view = Views::getView($view_id);
$view->initHandlers();
$row = $view->display_handler->getOption('row');
$this->assertEquals($row['type'], 'fields');
$this->assertSame($row['type'], 'fields');
// Check for the default filters.
$this->assertEquals($view->filter['status']->table, 'media_field_revision');
$this->assertEquals($view->filter['status']->field, 'status');
$this->assertSame($view->filter['status']->table, 'media_field_revision');
$this->assertSame($view->filter['status']->field, 'status');
$this->assertTrue($view->filter['status']->value);
// Check for the default fields.
$this->assertEquals($view->field['name']->table, 'media_field_revision');
$this->assertEquals($view->field['name']->field, 'name');
$this->assertEquals($view->field['changed']->table, 'media_field_revision');
$this->assertEquals($view->field['changed']->field, 'changed');
$this->assertSame($view->field['name']->table, 'media_field_revision');
$this->assertSame($view->field['name']->field, 'name');
$this->assertSame($view->field['changed']->table, 'media_field_revision');
$this->assertSame($view->field['changed']->field, 'changed');
}
}
@@ -28,13 +28,13 @@ class MediaCreationTest extends MediaKernelTestBase {
$this->container->get('module_installer')->install(['media_test_type']);
$test_media_type = $media_type_storage->load('test');
$this->assertInstanceOf(MediaTypeInterface::class, $test_media_type, 'The media type from default configuration has not been created in the database.');
$this->assertEquals('Test type', $test_media_type->get('label'), 'Could not assure the correct type name.');
$this->assertEquals('Test type.', $test_media_type->get('description'), 'Could not assure the correct type description.');
$this->assertEquals('test', $test_media_type->get('source'), 'Could not assure the correct media source.');
$this->assertSame('Test type', $test_media_type->get('label'), 'Could not assure the correct type name.');
$this->assertSame('Test type.', $test_media_type->get('description'), 'Could not assure the correct type description.');
$this->assertSame('test', $test_media_type->get('source'), 'Could not assure the correct media source.');
// Source field is not set on the media source, but it should never
// be created automatically when a config is being imported.
$this->assertEquals(['source_field' => '', 'test_config_value' => 'Kakec'], $test_media_type->get('source_configuration'), 'Could not assure the correct media source configuration.');
$this->assertEquals(['metadata_attribute' => 'field_attribute_config_test'], $test_media_type->get('field_map'), 'Could not assure the correct field map.');
$this->assertSame(['source_field' => '', 'test_config_value' => 'Kakec'], $test_media_type->get('source_configuration'), 'Could not assure the correct media source configuration.');
$this->assertSame(['metadata_attribute' => 'field_attribute_config_test'], $test_media_type->get('field_map'), 'Could not assure the correct field map.');
// Check the Media Type access handler behavior.
// We grant access to the 'view label' operation to all users having
// permission to 'view media'.
@@ -72,10 +72,10 @@ class MediaCreationTest extends MediaKernelTestBase {
$this->assertNotInstanceOf(MediaInterface::class, Media::load(rand(1000, 9999)), 'Failed asserting a non-existent media.');
$this->assertInstanceOf(MediaInterface::class, Media::load($media->id()), 'The new media item has not been created in the database.');
$this->assertEquals($this->testMediaType->id(), $media->bundle(), 'The media item was not created with the correct type.');
$this->assertEquals('Unnamed', $media->getName(), 'The media item was not created with the correct name.');
$this->assertSame($this->testMediaType->id(), $media->bundle(), 'The media item was not created with the correct type.');
$this->assertSame('Unnamed', $media->getName(), 'The media item was not created with the correct name.');
$source_field_name = $media->bundle->entity->getSource()->getSourceFieldDefinition($media->bundle->entity)->getName();
$this->assertEquals('Nation of sheep, ruled by wolves, owned by pigs.', $media->get($source_field_name)->value, 'Source returns incorrect source field value.');
$this->assertSame('Nation of sheep, ruled by wolves, owned by pigs.', $media->get($source_field_name)->value, 'Source returns incorrect source field value.');
}
}
@@ -5,8 +5,8 @@ namespace Drupal\Tests\media\Kernel;
use Drupal\file\Entity\File;
use Drupal\KernelTests\KernelTestBase;
use Drupal\media\Entity\Media;
use Drupal\media\Entity\MediaType;
use Drupal\media\MediaTypeInterface;
use Drupal\Tests\media\Traits\MediaTypeCreationTrait;
use Drupal\user\Entity\User;
use org\bovigo\vfs\vfsStream;
@@ -15,6 +15,8 @@ use org\bovigo\vfs\vfsStream;
*/
abstract class MediaKernelTestBase extends KernelTestBase {
use MediaTypeCreationTrait;
/**
* Modules to install.
*
@@ -77,37 +79,6 @@ abstract class MediaKernelTestBase extends KernelTestBase {
$this->container->get('current_user')->setAccount($this->user);
}
/**
* Create a media type for a source plugin.
*
* @param string $media_source_name
* The name of the media source.
*
* @return \Drupal\media\MediaTypeInterface
* A media type.
*/
protected function createMediaType($media_source_name) {
$id = strtolower($this->randomMachineName());
$media_type = MediaType::create([
'id' => $id,
'label' => $id,
'source' => $media_source_name,
'new_revision' => FALSE,
]);
$media_type->save();
$source_field = $media_type->getSource()->createSourceField($media_type);
// The media type form creates a source field if it does not exist yet. The
// same must be done in a kernel test, since it does not use that form.
// @see \Drupal\media\MediaTypeForm::save()
$source_field->getFieldStorageDefinition()->save();
// The source field storage has been created, now the field can be saved.
$source_field->save();
$media_type->set('source_configuration', [
'source_field' => $source_field->getName(),
])->save();
return $media_type;
}
/**
* Helper to generate a media item.
*
@@ -18,7 +18,7 @@ class MediaSourceFileTest extends MediaKernelTestBase {
$media = $this->generateMedia('test.patch', $mediaType);
$result = $media->validate();
$this->assertCount(1, $result);
$this->assertEquals('field_media_file.0', $result->get(0)->getPropertyPath());
$this->assertSame('field_media_file.0', $result->get(0)->getPropertyPath());
$this->assertContains('Only files with the following extensions are allowed:', (string) $result->get(0)->getMessage());
// Create a random file that should pass.
@@ -15,6 +15,73 @@ use Drupal\media\Entity\MediaType;
*/
class MediaSourceTest extends MediaKernelTestBase {
/**
* Tests that metadata is correctly mapped irrespective of how media is saved.
*/
public function testSave() {
$field_storage = FieldStorageConfig::create([
'entity_type' => 'media',
'field_name' => 'field_to_map_to',
'type' => 'string',
]);
$field_storage->save();
FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => $this->testMediaType->id(),
'label' => 'Field to map to',
])->save();
// Set an arbitrary metadata value to be mapped.
$this->container->get('state')
->set('media_source_test_attributes', [
'attribute_to_map' => [
'title' => 'Attribute to map',
'value' => 'Snowball',
],
'thumbnail_uri' => [
'title' => 'Thumbnail',
'value' => 'public://TheSisko.png',
],
]);
$this->testMediaType->setFieldMap([
'attribute_to_map' => 'field_to_map_to',
])->save();
/** @var \Drupal\Core\Entity\EntityStorageInterface $storage */
$storage = $this->container->get('entity_type.manager')
->getStorage('media');
/** @var \Drupal\media\MediaInterface $a */
$a = $storage->create([
'bundle' => $this->testMediaType->id(),
]);
/** @var \Drupal\media\MediaInterface $b */
$b = $storage->create([
'bundle' => $this->testMediaType->id(),
]);
// Set a random source value on both items.
$a->set($a->getSource()->getSourceFieldDefinition($a->bundle->entity)->getName(), $this->randomString());
$b->set($b->getSource()->getSourceFieldDefinition($b->bundle->entity)->getName(), $this->randomString());
$a->save();
$storage->save($b);
// Assert that the default name was mapped into the name field for both
// media items.
$this->assertFalse($a->get('name')->isEmpty());
$this->assertFalse($b->get('name')->isEmpty());
// Assert that arbitrary metadata was mapped correctly.
$this->assertFalse($a->get('field_to_map_to')->isEmpty());
$this->assertFalse($b->get('field_to_map_to')->isEmpty());
// Assert that the thumbnail was mapped correctly from the source.
$this->assertSame('public://TheSisko.png', $a->thumbnail->entity->getFileUri());
$this->assertSame('public://TheSisko.png', $b->thumbnail->entity->getFileUri());
}
/**
* Tests default media name functionality.
*/
@@ -23,13 +90,13 @@ class MediaSourceTest extends MediaKernelTestBase {
/** @var \Drupal\media\MediaInterface $media */
$media = Media::create(['bundle' => $this->testMediaType->id()]);
$media_source = $media->getSource();
$this->assertEquals('default_name', $media_source->getPluginDefinition()['default_name_metadata_attribute'], 'Default metadata attribute is not used for the default name.');
$this->assertEquals('media:' . $media->bundle() . ':' . $media->uuid(), $media_source->getMetadata($media, 'default_name'), 'Value of the default name metadata attribute does not look correct.');
$this->assertEquals('media:' . $media->bundle() . ':' . $media->uuid(), $media->getName(), 'Default name was not used correctly by getName().');
$this->assertEquals($media->getName(), $media->label(), 'Default name and label are not the same.');
$this->assertSame('default_name', $media_source->getPluginDefinition()['default_name_metadata_attribute'], 'Default metadata attribute is not used for the default name.');
$this->assertSame('media:' . $media->bundle() . ':' . $media->uuid(), $media_source->getMetadata($media, 'default_name'), 'Value of the default name metadata attribute does not look correct.');
$this->assertSame('media:' . $media->bundle() . ':' . $media->uuid(), $media->getName(), 'Default name was not used correctly by getName().');
$this->assertSame($media->getName(), $media->label(), 'Default name and label are not the same.');
$media->save();
$this->assertEquals('media:' . $media->bundle() . ':' . $media->uuid(), $media->getName(), 'Default name was not saved correctly.');
$this->assertEquals($media->getName(), $media->label(), 'The label changed during save.');
$this->assertSame('media:' . $media->bundle() . ':' . $media->uuid(), $media->getName(), 'Default name was not saved correctly.');
$this->assertSame($media->getName(), $media->label(), 'The label changed during save.');
// Make sure that the user-supplied name is used.
/** @var \Drupal\media\MediaInterface $media */
@@ -39,11 +106,11 @@ class MediaSourceTest extends MediaKernelTestBase {
'name' => $name,
]);
$media_source = $media->getSource();
$this->assertEquals('default_name', $media_source->getPluginDefinition()['default_name_metadata_attribute'], 'Default metadata attribute is not used for the default name.');
$this->assertEquals('media:' . $media->bundle() . ':' . $media->uuid(), $media_source->getMetadata($media, 'default_name'), 'Value of the default name metadata attribute does not look correct.');
$this->assertSame('default_name', $media_source->getPluginDefinition()['default_name_metadata_attribute'], 'Default metadata attribute is not used for the default name.');
$this->assertSame('media:' . $media->bundle() . ':' . $media->uuid(), $media_source->getMetadata($media, 'default_name'), 'Value of the default name metadata attribute does not look correct.');
$media->save();
$this->assertEquals($name, $media->getName(), 'User-supplied name was not set correctly.');
$this->assertEquals($media->getName(), $media->label(), 'The user-supplied name does not match the label.');
$this->assertSame($name, $media->getName(), 'User-supplied name was not set correctly.');
$this->assertSame($media->getName(), $media->label(), 'The user-supplied name does not match the label.');
// Change the default name attribute and see if it is used to set the name.
$name = 'Old Major';
@@ -52,11 +119,11 @@ class MediaSourceTest extends MediaKernelTestBase {
/** @var \Drupal\media\MediaInterface $media */
$media = Media::create(['bundle' => $this->testMediaType->id()]);
$media_source = $media->getSource();
$this->assertEquals('alternative_name', $media_source->getPluginDefinition()['default_name_metadata_attribute'], 'Correct metadata attribute is not used for the default name.');
$this->assertEquals($name, $media_source->getMetadata($media, 'alternative_name'), 'Value of the default name metadata attribute does not look correct.');
$this->assertSame('alternative_name', $media_source->getPluginDefinition()['default_name_metadata_attribute'], 'Correct metadata attribute is not used for the default name.');
$this->assertSame($name, $media_source->getMetadata($media, 'alternative_name'), 'Value of the default name metadata attribute does not look correct.');
$media->save();
$this->assertEquals($name, $media->getName(), 'Default name was not set correctly.');
$this->assertEquals($media->getName(), $media->label(), 'The default name does not match the label.');
$this->assertSame($name, $media->getName(), 'Default name was not set correctly.');
$this->assertSame($media->getName(), $media->label(), 'The default name does not match the label.');
}
/**
@@ -109,25 +176,25 @@ class MediaSourceTest extends MediaKernelTestBase {
'field_media_test' => 'some_value',
]);
$media_source = $media->getSource();
$this->assertEquals('Snowball', $media_source->getMetadata($media, $attribute_name), 'Value of the metadata attribute is not correct.');
$this->assertSame('Snowball', $media_source->getMetadata($media, $attribute_name), 'Value of the metadata attribute is not correct.');
$media->save();
$this->assertEquals('Snowball', $media->get($field_name)->value, 'Metadata attribute was not mapped to the field.');
$this->assertSame('Snowball', $media->get($field_name)->value, 'Metadata attribute was not mapped to the field.');
// Change the metadata attribute value and re-save the entity. Field value
// should stay the same.
\Drupal::state()->set('media_source_test_attributes', [
$attribute_name => ['title' => 'Attribute to map', 'value' => 'Pinkeye'],
]);
$this->assertEquals('Pinkeye', $media_source->getMetadata($media, $attribute_name), 'Value of the metadata attribute is not correct.');
$this->assertSame('Pinkeye', $media_source->getMetadata($media, $attribute_name), 'Value of the metadata attribute is not correct.');
$media->save();
$this->assertEquals('Snowball', $media->get($field_name)->value, 'Metadata attribute was not mapped to the field.');
$this->assertSame('Snowball', $media->get($field_name)->value, 'Metadata attribute was not mapped to the field.');
// Now change the value of the source field and make sure that the mapped
// values update too.
$this->assertEquals('Pinkeye', $media_source->getMetadata($media, $attribute_name), 'Value of the metadata attribute is not correct.');
$this->assertSame('Pinkeye', $media_source->getMetadata($media, $attribute_name), 'Value of the metadata attribute is not correct.');
$media->set('field_media_test', 'some_new_value');
$media->save();
$this->assertEquals('Pinkeye', $media->get($field_name)->value, 'Metadata attribute was not mapped to the field.');
$this->assertSame('Pinkeye', $media->get($field_name)->value, 'Metadata attribute was not mapped to the field.');
// Remove the value of the mapped field and make sure that it is re-mapped
// on save.
@@ -135,9 +202,9 @@ class MediaSourceTest extends MediaKernelTestBase {
$attribute_name => ['title' => 'Attribute to map', 'value' => 'Snowball'],
]);
$media->{$field_name}->value = NULL;
$this->assertEquals('Snowball', $media_source->getMetadata($media, $attribute_name), 'Value of the metadata attribute is not correct.');
$this->assertSame('Snowball', $media_source->getMetadata($media, $attribute_name), 'Value of the metadata attribute is not correct.');
$media->save();
$this->assertEquals('Snowball', $media->get($field_name)->value, 'Metadata attribute was not mapped to the field.');
$this->assertSame('Snowball', $media->get($field_name)->value, 'Metadata attribute was not mapped to the field.');
}
/**
@@ -172,10 +239,10 @@ class MediaSourceTest extends MediaKernelTestBase {
'field_media_test' => 'some_value',
]);
$media_source = $media->getSource();
$this->assertEquals('public://thumbnail1.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
$this->assertSame('public://thumbnail1.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
$media->save();
$this->assertEquals('public://thumbnail1.jpg', $media->thumbnail->entity->getFileUri(), 'Thumbnail was not added to the media item.');
$this->assertEquals('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertSame('public://thumbnail1.jpg', $media->thumbnail->entity->getFileUri(), 'Thumbnail was not added to the media item.');
$this->assertSame('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertEquals('Thumbnail', $media->thumbnail->alt, 'Alt text was not set on the thumbnail.');
// Now change the metadata attribute and make sure that the thumbnail stays
@@ -183,18 +250,18 @@ class MediaSourceTest extends MediaKernelTestBase {
\Drupal::state()->set('media_source_test_attributes', [
'thumbnail_uri' => ['title' => 'Thumbnail', 'value' => 'public://thumbnail2.jpg'],
]);
$this->assertEquals('public://thumbnail2.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
$this->assertSame('public://thumbnail2.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
$media->save();
$this->assertEquals('public://thumbnail1.jpg', $media->thumbnail->entity->getFileUri(), 'Thumbnail was not preserved.');
$this->assertEquals('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertSame('public://thumbnail1.jpg', $media->thumbnail->entity->getFileUri(), 'Thumbnail was not preserved.');
$this->assertSame('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertEquals('Thumbnail', $media->thumbnail->alt, 'Alt text was not set on the thumbnail.');
// Remove the thumbnail and make sure that it is auto-updated on save.
$media->thumbnail->target_id = NULL;
$this->assertEquals('public://thumbnail2.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
$this->assertSame('public://thumbnail2.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
$media->save();
$this->assertEquals('public://thumbnail2.jpg', $media->thumbnail->entity->getFileUri(), 'New thumbnail was not added to the media item.');
$this->assertEquals('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertSame('public://thumbnail2.jpg', $media->thumbnail->entity->getFileUri(), 'New thumbnail was not added to the media item.');
$this->assertSame('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertEquals('Thumbnail', $media->thumbnail->alt, 'Alt text was not set on the thumbnail.');
// Change the metadata attribute again, change the source field value too
@@ -203,10 +270,10 @@ class MediaSourceTest extends MediaKernelTestBase {
'thumbnail_uri' => ['title' => 'Thumbnail', 'value' => 'public://thumbnail1.jpg'],
]);
$media->field_media_test->value = 'some_new_value';
$this->assertEquals('public://thumbnail1.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
$this->assertSame('public://thumbnail1.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
$media->save();
$this->assertEquals('public://thumbnail1.jpg', $media->thumbnail->entity->getFileUri(), 'New thumbnail was not added to the media item.');
$this->assertEquals('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertSame('public://thumbnail1.jpg', $media->thumbnail->entity->getFileUri(), 'New thumbnail was not added to the media item.');
$this->assertSame('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertEquals('Thumbnail', $media->thumbnail->alt, 'Alt text was not set on the thumbnail.');
// Change the thumbnail metadata attribute and make sure that the thumbnail
@@ -222,11 +289,11 @@ class MediaSourceTest extends MediaKernelTestBase {
'field_media_test' => 'some_value',
]);
$media_source = $media->getSource();
$this->assertEquals('public://thumbnail1.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the metadata attribute is not correct.');
$this->assertEquals('public://thumbnail2.jpg', $media_source->getMetadata($media, 'alternative_thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
$this->assertSame('public://thumbnail1.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the metadata attribute is not correct.');
$this->assertSame('public://thumbnail2.jpg', $media_source->getMetadata($media, 'alternative_thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
$media->save();
$this->assertEquals('public://thumbnail2.jpg', $media->thumbnail->entity->getFileUri(), 'Correct metadata attribute was not used for the thumbnail.');
$this->assertEquals('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertSame('public://thumbnail2.jpg', $media->thumbnail->entity->getFileUri(), 'Correct metadata attribute was not used for the thumbnail.');
$this->assertSame('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertEquals('Thumbnail', $media->thumbnail->alt, 'Alt text was not set on the thumbnail.');
// Enable queued thumbnails and make sure that the entity gets the default
@@ -241,10 +308,10 @@ class MediaSourceTest extends MediaKernelTestBase {
'name' => 'Mr. Jones',
'field_media_test' => 'some_value',
]);
$this->assertEquals('public://thumbnail1.jpg', $media->getSource()->getMetadata($media, 'thumbnail_uri'), 'Value of the metadata attribute is not correct.');
$this->assertSame('public://thumbnail1.jpg', $media->getSource()->getMetadata($media, 'thumbnail_uri'), 'Value of the metadata attribute is not correct.');
$media->save();
$this->assertEquals('public://media-icons/generic/generic.png', $media->thumbnail->entity->getFileUri(), 'Default thumbnail was not set initially.');
$this->assertEquals('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertSame('public://media-icons/generic/generic.png', $media->thumbnail->entity->getFileUri(), 'Default thumbnail was not set initially.');
$this->assertSame('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertEquals('Thumbnail', $media->thumbnail->alt, 'Alt text was not set on the thumbnail.');
// Process the queue item and make sure that the thumbnail was updated too.
@@ -252,19 +319,19 @@ class MediaSourceTest extends MediaKernelTestBase {
/** @var \Drupal\Core\Queue\QueueWorkerInterface $queue_worker */
$queue_worker = \Drupal::service('plugin.manager.queue_worker')->createInstance($queue_name);
$queue = \Drupal::queue($queue_name);
$this->assertEquals(1, $queue->numberOfItems(), 'Item was not added to the queue.');
$this->assertSame(1, $queue->numberOfItems(), 'Item was not added to the queue.');
$item = $queue->claimItem();
$this->assertEquals($media->id(), $item->data['id'], 'Queue item that was created does not belong to the correct entity.');
$this->assertSame($media->id(), $item->data['id'], 'Queue item that was created does not belong to the correct entity.');
$queue_worker->processItem($item->data);
$queue->deleteItem($item);
$this->assertEquals(0, $queue->numberOfItems(), 'Item was not removed from the queue.');
$this->assertSame(0, $queue->numberOfItems(), 'Item was not removed from the queue.');
$media = Media::load($media->id());
$this->assertEquals('public://thumbnail1.jpg', $media->thumbnail->entity->getFileUri(), 'Thumbnail was not updated by the queue.');
$this->assertEquals('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertEquals('Thumbnail', $media->thumbnail->alt, 'Alt text was not set on the thumbnail.');
$this->assertSame('public://thumbnail1.jpg', $media->thumbnail->entity->getFileUri(), 'Thumbnail was not updated by the queue.');
$this->assertSame('Mr. Jones', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertSame('Thumbnail', $media->thumbnail->alt, 'Alt text was not set on the thumbnail.');
// Set alt and title metadata attributes and make sure they are used for the
// thumbnail.
@@ -282,9 +349,9 @@ class MediaSourceTest extends MediaKernelTestBase {
'field_media_test' => 'some_value',
]);
$media->save();
$this->assertEquals('Boxer', $media->getName(), 'Correct name was not set on the media item.');
$this->assertEquals('This will be title.', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertEquals('This will be alt.', $media->thumbnail->alt, 'Alt text was not set on the thumbnail.');
$this->assertSame('Boxer', $media->getName(), 'Correct name was not set on the media item.');
$this->assertSame('This will be title.', $media->thumbnail->title, 'Title text was not set on the thumbnail.');
$this->assertSame('This will be alt.', $media->thumbnail->alt, 'Alt text was not set on the thumbnail.');
}
/**
@@ -373,17 +440,17 @@ class MediaSourceTest extends MediaKernelTestBase {
// Test field storage.
$this->assertTrue($field_storage->isNew(), 'Field storage is saved automatically.');
$this->assertFalse($field_storage->isLocked(), 'Field storage is not locked.');
$this->assertEquals('string', $field_storage->getType(), 'Field is not of correct type.');
$this->assertEquals('field_media_test_1', $field_storage->getName(), 'Incorrect field name is used.');
$this->assertEquals('media', $field_storage->getTargetEntityTypeId(), 'Field is not targeting media entities.');
$this->assertSame('string', $field_storage->getType(), 'Field is not of correct type.');
$this->assertSame('field_media_test_1', $field_storage->getName(), 'Incorrect field name is used.');
$this->assertSame('media', $field_storage->getTargetEntityTypeId(), 'Field is not targeting media entities.');
// Test field.
$this->assertTrue($field->isNew(), 'Field is saved automatically.');
$this->assertEquals('field_media_test_1', $field->getName(), 'Incorrect field name is used.');
$this->assertEquals('string', $field->getType(), 'Field is of incorrect type.');
$this->assertSame('field_media_test_1', $field->getName(), 'Incorrect field name is used.');
$this->assertSame('string', $field->getType(), 'Field is of incorrect type.');
$this->assertTrue($field->isRequired(), 'Field is not required.');
$this->assertEquals('Test source', $field->label(), 'Incorrect label is used.');
$this->assertEquals('test_type', $field->getTargetBundle(), 'Field is not targeting correct bundle.');
$this->assertSame('test_type', $field->getTargetBundle(), 'Field is not targeting correct bundle.');
// Fields should be automatically saved only when creating the media type
// using the media type creation form. Make sure that they are not saved
@@ -408,17 +475,17 @@ class MediaSourceTest extends MediaKernelTestBase {
// Test field storage.
$this->assertTrue($field_storage->isNew(), 'Field storage is saved automatically.');
$this->assertFalse($field_storage->isLocked(), 'Field storage is not locked.');
$this->assertEquals('string_long', $field_storage->getType(), 'Field is of incorrect type.');
$this->assertEquals('field_media_test_constraints_1', $field_storage->getName(), 'Incorrect field name is used.');
$this->assertEquals('media', $field_storage->getTargetEntityTypeId(), 'Field is not targeting media entities.');
$this->assertSame('string_long', $field_storage->getType(), 'Field is of incorrect type.');
$this->assertSame('field_media_test_constraints_1', $field_storage->getName(), 'Incorrect field name is used.');
$this->assertSame('media', $field_storage->getTargetEntityTypeId(), 'Field is not targeting media entities.');
// Test field.
$this->assertTrue($field->isNew(), 'Field is saved automatically.');
$this->assertEquals('field_media_test_constraints_1', $field->getName(), 'Incorrect field name is used.');
$this->assertEquals('string_long', $field->getType(), 'Field is of incorrect type.');
$this->assertSame('field_media_test_constraints_1', $field->getName(), 'Incorrect field name is used.');
$this->assertSame('string_long', $field->getType(), 'Field is of incorrect type.');
$this->assertTrue($field->isRequired(), 'Field is not required.');
$this->assertEquals('Test source with constraints', $field->label(), 'Incorrect label is used.');
$this->assertEquals('test_constraints_type', $field->getTargetBundle(), 'Field is not targeting correct bundle.');
$this->assertSame('test_constraints_type', $field->getTargetBundle(), 'Field is not targeting correct bundle.');
}
/**
@@ -434,26 +501,26 @@ class MediaSourceTest extends MediaKernelTestBase {
/** @var \Drupal\media\MediaSourceInterface $source */
$source = $manager->createInstance('test', []);
$source->submitConfigurationForm($form, $form_state);
$expected = ['test_config_value' => 'Somewhere over the rainbow.', 'source_field' => 'field_media_test_1'];
$this->assertEquals($expected, $source->getConfiguration(), 'Submitted values were saved correctly.');
$expected = ['source_field' => 'field_media_test_1', 'test_config_value' => 'Somewhere over the rainbow.'];
$this->assertSame($expected, $source->getConfiguration(), 'Submitted values were saved correctly.');
// Try to save a NULL value.
$form_state->setValue('test_config_value', NULL);
$source->submitConfigurationForm($form, $form_state);
$expected['test_config_value'] = NULL;
$this->assertEquals($expected, $source->getConfiguration(), 'Submitted values were saved correctly.');
$this->assertSame($expected, $source->getConfiguration(), 'Submitted values were saved correctly.');
// Make sure that the config keys are determined correctly even if the
// existing value is NULL.
$form_state->setValue('test_config_value', 'Somewhere over the rainbow.');
$source->submitConfigurationForm($form, $form_state);
$expected['test_config_value'] = 'Somewhere over the rainbow.';
$this->assertEquals($expected, $source->getConfiguration(), 'Submitted values were saved correctly.');
$this->assertSame($expected, $source->getConfiguration(), 'Submitted values were saved correctly.');
// Make sure that a non-relevant value will be skipped.
$form_state->setValue('not_relevant', 'Should not be saved in the plugin.');
$source->submitConfigurationForm($form, $form_state);
$this->assertEquals($expected, $source->getConfiguration(), 'Submitted values were saved correctly.');
$this->assertSame($expected, $source->getConfiguration(), 'Submitted values were saved correctly.');
}
/**
@@ -31,7 +31,7 @@ class MediaTest extends MediaKernelTestBase {
// Ensure media name is configurable on manage display.
$this->assertTrue($field_definitions['name']->isDisplayConfigurable('view'));
// Ensure it is not visible by default.
$this->assertEquals($field_definitions['name']->getDisplayOptions('view'), ['region' => 'hidden']);
$this->assertSame($field_definitions['name']->getDisplayOptions('view'), ['region' => 'hidden']);
}
}
@@ -93,10 +93,10 @@ class MediaTranslationTest extends MediaKernelTestBase {
$result = $result && $item['value'] == $media_translation->{$source_field_definition->getName()}[$delta]->value;
}
$this->assertTrue($result, new FormattableMarkup('%language translation field value not correct.', ['%language' => $langcode]));
$this->assertEquals('public://' . $langcode . '.png', $media_translation->getSource()->getMetadata($media_translation, 'thumbnail_uri'), new FormattableMarkup('%language translation thumbnail metadata attribute is not correct.', ['%language' => $langcode]));
$this->assertEquals('public://' . $langcode . '.png', $media_translation->get('thumbnail')->entity->getFileUri(), new FormattableMarkup('%language translation thumbnail value is not correct.', ['%language' => $langcode]));
$this->assertSame('public://' . $langcode . '.png', $media_translation->getSource()->getMetadata($media_translation, 'thumbnail_uri'), new FormattableMarkup('%language translation thumbnail metadata attribute is not correct.', ['%language' => $langcode]));
$this->assertSame('public://' . $langcode . '.png', $media_translation->get('thumbnail')->entity->getFileUri(), new FormattableMarkup('%language translation thumbnail value is not correct.', ['%language' => $langcode]));
$this->assertEquals('Test Thumbnail ' . $langcode, $media_translation->getSource()->getMetadata($media_translation, 'test_thumbnail_alt'), new FormattableMarkup('%language translation thumbnail alt metadata attribute is not correct.', ['%language' => $langcode]));
$this->assertEquals('Test Thumbnail ' . $langcode, $media_translation->get('thumbnail')->alt, new FormattableMarkup('%language translation thumbnail alt value is not correct.', ['%language' => $langcode]));
$this->assertSame('Test Thumbnail ' . $langcode, $media_translation->get('thumbnail')->alt, new FormattableMarkup('%language translation thumbnail alt value is not correct.', ['%language' => $langcode]));
}
}
@@ -0,0 +1,56 @@
<?php
namespace Drupal\Tests\media\Kernel;
use Symfony\Component\HttpFoundation\Request;
/**
* @coversDefaultClass \Drupal\media\Controller\OEmbedIframeController
*
* @group media
*/
class OEmbedIframeControllerTest extends MediaKernelTestBase {
/**
* Data provider for testBadHashParameter().
*
* @return array
*/
public function providerBadHashParameter() {
return [
'no hash' => [
'',
],
'invalid hash' => [
$this->randomString(),
],
];
}
/**
* Tests validation of the 'hash' query string parameter.
*
* @param string $hash
* The 'hash' query string parameter.
*
* @dataProvider providerBadHashParameter
*
* @covers ::render
*/
public function testBadHashParameter($hash) {
/** @var callable $controller */
$controller = $this->container
->get('controller_resolver')
->getControllerFromDefinition('\Drupal\media\Controller\OEmbedIframeController::render');
$this->assertInternalType('callable', $controller);
$this->setExpectedException('\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException', 'This resource is not available');
$request = new Request([
'url' => 'https://example.com/path/to/resource',
'hash' => $hash,
]);
$controller($request);
}
}
@@ -0,0 +1,76 @@
<?php
namespace Drupal\Tests\media\Traits;
use Drupal\media\Entity\MediaType;
/**
* Provides methods to create a media type from given values.
*
* This trait is meant to be used only by test classes.
*/
trait MediaTypeCreationTrait {
/**
* Create a media type for a source plugin.
*
* @param string $source_plugin_id
* The media source plugin ID.
* @param mixed[] $values
* (optional) Additional values for the media type entity:
* - id: The ID of the media type. If none is provided, a random value will
* be used.
* - label: The human-readable label of the media type. If none is provided,
* a random value will be used.
* - bundle: (deprecated) The ID of the media type, for backwards
* compatibility purposes. Use 'id' instead.
* See \Drupal\media\MediaTypeInterface and \Drupal\media\Entity\MediaType
* for full documentation of the media type properties.
*
* @return \Drupal\media\MediaTypeInterface
* A media type.
*
* @see \Drupal\media\MediaTypeInterface
* @see \Drupal\media\Entity\MediaType
*/
protected function createMediaType($source_plugin_id, array $values = []) {
if (isset($values['bundle'])) {
@trigger_error('Setting the "bundle" key when creating a test media type is deprecated in Drupal 8.6.0 and will be removed before Drupal 9.0.0. Set the "id" key instead. See https://www.drupal.org/node/2981614.', E_USER_DEPRECATED);
$values['id'] = $values['bundle'];
unset($values['bundle']);
}
$values += [
'id' => $this->randomMachineName(),
'label' => $this->randomString(),
'source' => $source_plugin_id,
];
/** @var \Drupal\media\MediaTypeInterface $media_type */
$media_type = MediaType::create($values);
$this->assertSame(SAVED_NEW, $media_type->save());
$source = $media_type->getSource();
$source_field = $source->createSourceField($media_type);
// The media type form creates a source field if it does not exist yet. The
// same must be done in a kernel test, since it does not use that form.
// @see \Drupal\media\MediaTypeForm::save()
$source_field->getFieldStorageDefinition()->save();
// The source field storage has been created, now the field can be saved.
$source_field->save();
$source_configuration = $source->getConfiguration();
$source_configuration['source_field'] = $source_field->getName();
$source->setConfiguration($source_configuration);
$this->assertSame(SAVED_UPDATED, $media_type->save());
// Add the source field to the form display for the media type.
$form_display = entity_get_form_display('media', $media_type->id(), 'default');
$source->prepareFormDisplay($media_type, $form_display);
$form_display->save();
return $media_type;
}
}
@@ -0,0 +1,89 @@
<?php
namespace Drupal\Tests\media\Traits;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Url;
use Drupal\media\OEmbed\Provider;
/**
* Contains helper functions for testing oEmbed functionality in isolation.
*/
trait OEmbedTestTrait {
/**
* Returns the relative path to the oEmbed fixtures directory.
*
* @return string
*/
protected function getFixturesDirectory() {
return drupal_get_path('module', 'media') . '/tests/fixtures/oembed';
}
/**
* Returns the absolute URL of the oEmbed fixtures directory.
*
* @return string
*/
protected function getFixturesUrl() {
return $this->baseUrl . '/' . $this->getFixturesDirectory();
}
/**
* Forces Media to use the provider database in the fixtures directory.
*/
protected function useFixtureProviders() {
$this->config('media.settings')
->set('oembed_providers_url', $this->getFixturesUrl() . '/providers.json')
->save();
}
/**
* Configures the http_client service so that all requests are carried out
* relative to the URL of the fixtures directory. For example, after calling
* this method, a request for foobar.html will actually request
* http://test-site/path/to/fuxtures/foobar.html.
*/
protected function lockHttpClientToFixtures() {
$this->writeSettings([
'settings' => [
'http_client_config' => [
'base_uri' => (object) [
'value' => $this->getFixturesUrl() . '/',
'required' => TRUE,
],
],
],
]);
}
/**
* Ensures that all oEmbed provider endpoints defined in the fixture
* providers.json will use the media_test_oembed.resource.get route as their
* URL.
*
* This requires the media_test_oembed module in order to work.
*/
protected function hijackProviderEndpoints() {
$providers = $this->getFixturesDirectory() . '/providers.json';
$providers = file_get_contents($providers);
$providers = Json::decode($providers);
$endpoint_url = Url::fromRoute('media_test_oembed.resource.get')
->setAbsolute()
->toString();
/** @var \Drupal\media_test_oembed\ProviderRepository $provider_repository */
$provider_repository = $this->container->get('media.oembed.provider_repository');
foreach ($providers as &$provider) {
foreach ($provider['endpoints'] as &$endpoint) {
$endpoint['url'] = $endpoint_url;
}
$provider_repository->setProvider(
new Provider($provider['provider_name'], $provider['provider_url'], $provider['endpoints'])
);
}
}
}
@@ -0,0 +1,89 @@
<?php
namespace Drupal\Tests\media\Unit;
use Drupal\Core\PrivateKey;
use Drupal\Core\Routing\RequestContext;
use Drupal\media\IFrameUrlHelper;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\media\IFrameUrlHelper
*
* @group media
*/
class IFrameUrlHelperTest extends UnitTestCase {
/**
* Data provider for testIsSecure().
*
* @see ::testIsSecure()
*
* @return array
*/
public function providerIsSecure() {
return [
'no domain' => [
'/path/to/media.php',
'http://www.example.com/',
FALSE,
],
'no base URL domain' => [
'http://www.example.com/media.php',
'/invalid/base/url',
FALSE,
],
'same domain' => [
'http://www.example.com/media.php',
'http://www.example.com/',
FALSE,
],
'different domain' => [
'http://www.example.com/media.php',
'http://www.example-assets.com/',
TRUE,
],
'same subdomain' => [
'http://foo.example.com/media.php',
'http://foo.example.com/',
FALSE,
],
'different subdomain' => [
'http://assets.example.com/media.php',
'http://foo.example.com/',
TRUE,
],
'subdomain and top-level domain' => [
'http://assets.example.com/media.php',
'http://example.com/',
TRUE,
],
];
}
/**
* Tests that isSecure() behaves properly.
*
* @param string $url
* The URL to test for security.
* @param string $base_url
* The base URL to compare $url against.
* @param bool $secure
* The expected result of isSecure().
*
* @covers ::isSecure
*
* @dataProvider providerIsSecure
*/
public function testIsSecure($url, $base_url, $secure) {
$request_context = $this->prophesize(RequestContext::class);
$request_context->getCompleteBaseUrl()->willReturn($base_url);
$url_helper = new IFrameUrlHelper(
$request_context->reveal(),
$this->prophesize(PrivateKey::class)->reveal()
);
$this->assertSame($secure, $url_helper->isSecure($url));
}
}