Update to Drupal 8.2.2. For more information, see https://www.drupal.org/project/drupal/releases/8.2.2

This commit is contained in:
Pantheon Automation 2016-11-02 11:43:31 -07:00 committed by Greg Anderson
parent 23ffed3665
commit 507b45a0ed
378 changed files with 11434 additions and 5542 deletions

View file

@ -0,0 +1,85 @@
<?php
namespace Drupal\FunctionalJavascriptTests\Ajax;
use Drupal\FunctionalJavascriptTests\JavascriptTestBase;
/**
* Tests AJAX responses.
*
* @group Ajax
*/
class AjaxTest extends JavascriptTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['ajax_test'];
public function testAjaxWithAdminRoute() {
\Drupal::service('theme_installer')->install(['stable', 'seven']);
$theme_config = \Drupal::configFactory()->getEditable('system.theme');
$theme_config->set('admin', 'seven');
$theme_config->set('default', 'stable');
$theme_config->save();
$account = $this->drupalCreateUser(['view the administration theme']);
$this->drupalLogin($account);
// First visit the site directly via the URL. This should render it in the
// admin theme.
$this->drupalGet('admin/ajax-test/theme');
$assert = $this->assertSession();
$assert->pageTextContains('Current theme: seven');
// Now click the modal, which should also use the admin theme.
$this->drupalGet('ajax-test/dialog');
$assert->pageTextNotContains('Current theme: stable');
$this->clickLink('Link 8 (ajax)');
$assert->assertWaitOnAjaxRequest();
$assert->pageTextContains('Current theme: stable');
$assert->pageTextNotContains('Current theme: seven');
}
/**
* Test that AJAX loaded libraries are not retained between requests.
*
* @see https://www.drupal.org/node/2647916
*/
public function testDrupalSettingsCachingRegression() {
$this->drupalGet('ajax-test/dialog');
$assert = $this->assertSession();
$session = $this->getSession();
// Insert a fake library into the already loaded library settings.
$fake_library = 'fakeLibrary/fakeLibrary';
$session->evaluateScript("drupalSettings.ajaxPageState.libraries = drupalSettings.ajaxPageState.libraries + ',$fake_library';");
$libraries = $session->evaluateScript('drupalSettings.ajaxPageState.libraries');
// Test that the fake library is set.
$this->assertContains($fake_library, $libraries);
// Click on the AJAX link.
$this->clickLink('Link 8 (ajax)');
$assert->assertWaitOnAjaxRequest();
// Test that the fake library is still set after the AJAX call.
$libraries = $session->evaluateScript('drupalSettings.ajaxPageState.libraries');
$this->assertContains($fake_library, $libraries);
// Reload the page, this should reset the loaded libraries and remove the
// fake library.
$this->drupalGet('ajax-test/dialog');
$libraries = $session->evaluateScript('drupalSettings.ajaxPageState.libraries');
$this->assertNotContains($fake_library, $libraries);
// Click on the AJAX link again, and the libraries should still not contain
// the fake library.
$this->clickLink('Link 8 (ajax)');
$assert->assertWaitOnAjaxRequest();
$libraries = $session->evaluateScript('drupalSettings.ajaxPageState.libraries');
$this->assertNotContains($fake_library, $libraries);
}
}

View file

@ -1,45 +0,0 @@
<?php
namespace Drupal\FunctionalJavascriptTests\Ajax;
use Drupal\FunctionalJavascriptTests\JavascriptTestBase;
/**
* Tests that AJAX responses use the current theme.
*
* @group Ajax
*/
class AjaxThemeTest extends JavascriptTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['ajax_test'];
public function testAjaxWithAdminRoute() {
\Drupal::service('theme_installer')->install(['stable', 'seven']);
$theme_config = \Drupal::configFactory()->getEditable('system.theme');
$theme_config->set('admin', 'seven');
$theme_config->set('default', 'stable');
$theme_config->save();
$account = $this->drupalCreateUser(['view the administration theme']);
$this->drupalLogin($account);
// First visit the site directly via the URL. This should render it in the
// admin theme.
$this->drupalGet('admin/ajax-test/theme');
$assert = $this->assertSession();
$assert->pageTextContains('Current theme: seven');
// Now click the modal, which should also use the admin theme.
$this->drupalGet('ajax-test/dialog');
$assert->pageTextNotContains('Current theme: stable');
$this->clickLink('Link 8 (ajax)');
$assert->assertWaitOnAjaxRequest();
$assert->pageTextContains('Current theme: stable');
$assert->pageTextNotContains('Current theme: seven');
}
}

View file

@ -0,0 +1,116 @@
<?php
namespace Drupal\FunctionalJavascriptTests\Core;
use Drupal\FunctionalJavascriptTests\JavascriptTestBase;
/**
* Tests for the machine name field.
*
* @group field
*/
class MachineNameTest extends JavascriptTestBase {
/**
* Required modules.
*
* Node is required because the machine name callback checks for
* access_content.
*
* @var array
*/
public static $modules = ['node', 'form_test'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$account = $this->drupalCreateUser(array(
'access content',
));
$this->drupalLogin($account);
}
/**
* Tests that machine name field functions.
*
* Makes sure that the machine name field automatically provides a valid
* machine name and that the manual editing mode functions.
*/
public function testMachineName() {
// Visit the machine name test page which contains two machine name fields.
$this->drupalGet('form-test/machine-name');
// Test values for conversion.
$test_values = [
[
'input' => 'Test value !0-9@',
'message' => 'A title that should be transliterated must be equal to the php generated machine name',
'expected' => 'test_value_0_9_',
],
[
'input' => 'Test value',
'message' => 'A title that should not be transliterated must be equal to the php generated machine name',
'expected' => 'test_value',
],
];
// Get page and session.
$page = $this->getSession()->getPage();
$assert_session = $this->assertSession();
// Get elements from the page.
$title_1 = $page->findField('machine_name_1_label');
$machine_name_1_field = $page->findField('machine_name_1');
$machine_name_2_field = $page->findField('machine_name_2');
$machine_name_1_wrapper = $machine_name_1_field->getParent();
$machine_name_2_wrapper = $machine_name_2_field->getParent();
$machine_name_1_value = $page->find('css', '#edit-machine-name-1-label-machine-name-suffix .machine-name-value');
$machine_name_2_value = $page->find('css', '#edit-machine-name-2-label-machine-name-suffix .machine-name-value');
$button_1 = $page->find('css', '#edit-machine-name-1-label-machine-name-suffix button.link');
// Assert both fields are initialized correctly.
$this->assertNotEmpty($machine_name_1_value, 'Machine name field 1 must be initialized');
$this->assertNotEmpty($machine_name_2_value, 'Machine name field 2 must be initialized');
// Field must be present for the rest of the test to work.
if (empty($machine_name_1_value)) {
$this->fail('Cannot finish test, missing machine name field');
}
// Test each value for conversion to a machine name.
foreach ($test_values as $test_info) {
// Set the value for the field, triggering the machine name update.
$title_1->setValue($test_info['input']);
// Wait the set timeout for fetching the machine name.
$this->getSession()->wait(1000, 'jQuery("#edit-machine-name-1-label-machine-name-suffix .machine-name-value").html() == "' . $test_info['expected'] . '"');
// Validate the generated machine name.
$this->assertEquals($test_info['expected'], $machine_name_1_value->getHtml(), $test_info['message']);
// Validate the second machine name field is empty.
$this->assertEmpty($machine_name_2_value->getHtml(), 'The second machine name field should still be empty');
}
// Validate the machine name field is hidden. Elements are visually hidden
// using positioning, isVisible() will therefore not work.
$this->assertEquals(TRUE, $machine_name_1_wrapper->hasClass('visually-hidden'), 'The ID field must not be visible');
$this->assertEquals(TRUE, $machine_name_2_wrapper->hasClass('visually-hidden'), 'The ID field must not be visible');
// Test switching back to the manual editing mode by clicking the edit link.
$button_1->click();
// Validate the visibility of the machine name field.
$this->assertEquals(FALSE, $machine_name_1_wrapper->hasClass('visually-hidden'), 'The ID field must now be visible');
// Validate the visibility of the second machine name field.
$this->assertEquals(TRUE, $machine_name_2_wrapper->hasClass('visually-hidden'), 'The ID field must not be visible');
// Validate if the element contains the correct value.
$this->assertEquals($test_values[1]['expected'], $machine_name_1_field->getValue(), 'The ID field value must be equal to the php generated machine name');
}
}

View file

@ -0,0 +1,102 @@
<?php
namespace Drupal\FunctionalJavascriptTests\EntityReference;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
use Drupal\FunctionalJavascriptTests\JavascriptTestBase;
use Drupal\simpletest\ContentTypeCreationTrait;
use Drupal\simpletest\NodeCreationTrait;
/**
* Tests the output of entity reference autocomplete widgets.
*
* @group entity_reference
*/
class EntityReferenceAutocompleteWidgetTest extends JavascriptTestBase {
use ContentTypeCreationTrait;
use EntityReferenceTestTrait;
use NodeCreationTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['node'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Create a Content type and two test nodes.
$this->createContentType(['type' => 'page']);
$this->createNode(['title' => 'Test page']);
$this->createNode(['title' => 'Page test']);
$user = $this->drupalCreateUser([
'access content',
'create page content',
]);
$this->drupalLogin($user);
}
/**
* Tests that the default autocomplete widget return the correct results.
*/
public function testEntityReferenceAutocompleteWidget() {
// Create an entity reference field and use the default 'CONTAINS' match
// operator.
$field_name = 'field_test';
$this->createEntityReferenceField('node', 'page', $field_name, $field_name, 'node', 'default', ['target_bundles' => ['page']]);
entity_get_form_display('node', 'page', 'default')
->setComponent($field_name, [
'type' => 'entity_reference_autocomplete',
'settings' => array(
'match_operator' => 'CONTAINS',
),
])
->save();
// Visit the node add page.
$this->drupalGet('node/add/page');
$page = $this->getSession()->getPage();
$assert_session = $this->assertSession();
$autocomplete_field = $page->findField($field_name . '[0][target_id]');
$autocomplete_field->setValue('Test');
$this->getSession()->getDriver()->keyDown($autocomplete_field->getXpath(), ' ');
$assert_session->waitOnAutocomplete();
$results = $page->findAll('css', '.ui-autocomplete li');
$this->assertCount(2, $results);
$assert_session->pageTextContains('Test page');
$assert_session->pageTextContains('Page test');
// Now switch the autocomplete widget to the 'STARTS_WITH' match operator.
entity_get_form_display('node', 'page', 'default')
->setComponent($field_name, [
'type' => 'entity_reference_autocomplete',
'settings' => array(
'match_operator' => 'STARTS_WITH',
),
])
->save();
$this->drupalGet('node/add/page');
$page = $this->getSession()->getPage();
$autocomplete_field = $page->findField($field_name . '[0][target_id]');
$autocomplete_field->setValue('Test');
$this->getSession()->getDriver()->keyDown($autocomplete_field->getXpath(), ' ');
$assert_session->waitOnAutocomplete();
$results = $page->findAll('css', '.ui-autocomplete li');
$this->assertCount(1, $results);
$assert_session->pageTextContains('Test page');
$assert_session->pageTextNotContains('Page test');
}
}

View file

@ -28,4 +28,15 @@ class JSWebAssert extends WebAssert {
}
}
/**
* Waits for the jQuery autocomplete delay duration.
*
* @see https://api.jqueryui.com/autocomplete/#option-delay
*/
public function waitOnAutocomplete() {
// Drupal is using the default delay value of 300 milliseconds.
$this->session->wait(300);
$this->assertWaitOnAjaxRequest();
}
}

View file

@ -113,6 +113,19 @@ class FetchTest extends DatabaseTestBase {
$this->assertIdentical(count($records), 1, 'There is only one record.');
}
/**
* Confirms that we can fetch all records into an array explicitly.
*/
public function testQueryFetchAllColumn() {
$query = db_select('test');
$query->addField('test', 'name');
$query->orderBy('name');
$query_result = $query->execute()->fetchAll(\PDO::FETCH_COLUMN);
$expected_result = ['George', 'John', 'Paul', 'Ringo'];
$this->assertEqual($query_result, $expected_result, 'Returned the correct result.');
}
/**
* Confirms that we can fetch an entire column of a result set at once.
*/

View file

@ -0,0 +1,92 @@
<?php
namespace Drupal\KernelTests\Core\Datetime;
use Drupal\KernelTests\KernelTestBase;
use Drupal\language\Entity\ConfigurableLanguage;
/**
* Tests date formatting.
*
* @group Common
*/
class FormatDateTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['language', 'system'];
/**
* Arbitrary langcode for a custom language.
*/
const LANGCODE = 'xx';
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(['system']);
$this->setSetting('locale_custom_strings_' . self::LANGCODE, [
'' => ['Sunday' => 'domingo'],
'Long month name' => ['March' => 'marzo'],
]);
$formats = $this->container->get('entity.manager')
->getStorage('date_format')
->loadMultiple(['long', 'medium', 'short']);
$formats['long']->setPattern('l, j. F Y - G:i')->save();
$formats['medium']->setPattern('j. F Y - G:i')->save();
$formats['short']->setPattern('Y M j - g:ia')->save();
ConfigurableLanguage::createFromLangcode(static::LANGCODE)->save();
}
/**
* Tests the format_date() function.
*/
public function testFormatDate() {
/** @var \Drupal\Core\Datetime\DateFormatterInterface $formatter */
$formatter = $this->container->get('date.formatter');
$timestamp = strtotime('2007-03-26T00:00:00+00:00');
$this->assertSame('Sunday, 25-Mar-07 17:00:00 PDT', $formatter->format($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', 'en'), 'Test all parameters.');
$this->assertSame('domingo, 25-Mar-07 17:00:00 PDT', $formatter->format($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'Test translated format.');
$this->assertSame('l, 25-Mar-07 17:00:00 PDT', $formatter->format($timestamp, 'custom', '\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'Test an escaped format string.');
$this->assertSame('\\domingo, 25-Mar-07 17:00:00 PDT', $formatter->format($timestamp, 'custom', '\\\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'Test format containing backslash character.');
$this->assertSame('\\l, 25-Mar-07 17:00:00 PDT', $formatter->format($timestamp, 'custom', '\\\\\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'Test format containing backslash followed by escaped format string.');
$this->assertSame('Monday, 26-Mar-07 01:00:00 BST', $formatter->format($timestamp, 'custom', 'l, d-M-y H:i:s T', 'Europe/London', 'en'), 'Test a different time zone.');
// Change the default language and timezone.
$this->config('system.site')->set('default_langcode', static::LANGCODE)->save();
date_default_timezone_set('America/Los_Angeles');
// Reset the language manager so new negotiations attempts will fall back on
// on the new language.
$this->container->get('language_manager')->reset();
$this->assertSame('Sunday, 25-Mar-07 17:00:00 PDT', $formatter->format($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', 'en'), 'Test a different language.');
$this->assertSame('Monday, 26-Mar-07 01:00:00 BST', $formatter->format($timestamp, 'custom', 'l, d-M-y H:i:s T', 'Europe/London'), 'Test a different time zone.');
$this->assertSame('domingo, 25-Mar-07 17:00:00 PDT', $formatter->format($timestamp, 'custom', 'l, d-M-y H:i:s T'), 'Test custom date format.');
$this->assertSame('domingo, 25. marzo 2007 - 17:00', $formatter->format($timestamp, 'long'), 'Test long date format.');
$this->assertSame('25. marzo 2007 - 17:00', $formatter->format($timestamp, 'medium'), 'Test medium date format.');
$this->assertSame('2007 Mar 25 - 5:00pm', $formatter->format($timestamp, 'short'), 'Test short date format.');
$this->assertSame('25. marzo 2007 - 17:00', $formatter->format($timestamp), 'Test default date format.');
// Test HTML time element formats.
$this->assertSame('2007-03-25T17:00:00-0700', $formatter->format($timestamp, 'html_datetime'), 'Test html_datetime date format.');
$this->assertSame('2007-03-25', $formatter->format($timestamp, 'html_date'), 'Test html_date date format.');
$this->assertSame('17:00:00', $formatter->format($timestamp, 'html_time'), 'Test html_time date format.');
$this->assertSame('03-25', $formatter->format($timestamp, 'html_yearless_date'), 'Test html_yearless_date date format.');
$this->assertSame('2007-W12', $formatter->format($timestamp, 'html_week'), 'Test html_week date format.');
$this->assertSame('2007-03', $formatter->format($timestamp, 'html_month'), 'Test html_month date format.');
$this->assertSame('2007', $formatter->format($timestamp, 'html_year'), 'Test html_year date format.');
// HTML is not escaped by the date formatter, it must be escaped later.
$this->assertSame("<script>alert('2007');</script>", $formatter->format($timestamp, 'custom', '\<\s\c\r\i\p\t\>\a\l\e\r\t\(\'Y\'\)\;\<\/\s\c\r\i\p\t\>'), 'Script tags not removed from dates.');
$this->assertSame('<em>2007</em>', $formatter->format($timestamp, 'custom', '\<\e\m\>Y\<\/\e\m\>'), 'Em tags are not removed from dates.');
}
}

View file

@ -161,4 +161,17 @@ class DirectoryTest extends FileTestBase {
$this->assertEqual($config->get('path.temporary'), $tmp_directory);
}
/**
* Tests directory creation.
*/
public function testDirectoryCreation() {
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = $this->container->get('file_system');
// mkdir() recursion should work with or without a trailing slash.
$dir = $this->siteDirectory . '/files';
$this->assertTrue($file_system->mkdir($dir . '/foo/bar', 0775, TRUE));
$this->assertTrue($file_system->mkdir($dir . '/foo/baz/', 0775, TRUE));
}
}

View file

@ -528,10 +528,11 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
* The file path.
*/
public static function filePreDeleteCallback($path) {
$success = @chmod($path, 0700);
if (!$success) {
trigger_error("Can not make $path writable whilst cleaning up test directory. The webserver and phpunit are probably not being run by the same user.");
}
// When the webserver runs with the same system user as phpunit, we can
// make read-only files writable again. If not, chmod will fail while the
// file deletion still works if file permissions have been configured
// correctly. Thus, we ignore any problems while running chmod.
@chmod($path, 0700);
}
/**

View file

@ -86,7 +86,7 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
$path = substr($path, strlen($this->root) + 1);
$this->libraryDiscoveryParser->setPaths('module', 'example_module', $path);
$libraries = $this->libraryDiscoveryParser->buildByExtension('example_module', 'example');
$libraries = $this->libraryDiscoveryParser->buildByExtension('example_module');
$library = $libraries['example'];
$this->assertCount(0, $library['js']);

View file

@ -0,0 +1,85 @@
<?php
namespace Drupal\Tests\Core\Cache\Context;
use Drupal\Core\Cache\Context\SessionCacheContext;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* @coversDefaultClass \Drupal\Core\Cache\Context\SessionCacheContext
* @group Cache
*/
class SessionCacheContextTest extends \PHPUnit_Framework_TestCase {
/**
* The request stack.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* The session object.
*
* @var \Symfony\Component\HttpFoundation\Session\SessionInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $session;
/**
* The session cache context.
*
* @var \Drupal\Core\Cache\Context\SessionCacheContext
*/
protected $cacheContext;
public function setUp() {
$request = new Request();
$this->requestStack = new RequestStack();
$this->requestStack->push($request);
$this->session = $this->getMock('\Symfony\Component\HttpFoundation\Session\SessionInterface');
$request->setSession($this->session);
$this->cacheContext = new SessionCacheContext($this->requestStack);
}
/**
* @covers ::getContext
*/
public function testSameContextForSameSession() {
$session_id = 'aSebeZ52bbM6SvADurQP89SFnEpxY6j8';
$this->session->expects($this->exactly(2))
->method('getId')
->will($this->returnValue($session_id));
$context1 = $this->cacheContext->getContext();
$context2 = $this->cacheContext->getContext();
$this->assertSame($context1, $context2);
$this->assertSame(FALSE, strpos($context1, $session_id), 'Session ID not contained in cache context');
}
/**
* @covers ::getContext
*/
public function testDifferentContextForDifferentSession() {
$session1_id = 'pjH_8aSoofyCDQiuVYXJcbfyr-CPtkUY';
$this->session->expects($this->at(0))
->method('getId')
->will($this->returnValue($session1_id));
$session2_id = 'aSebeZ52bbM6SvADurQP89SFnEpxY6j8';
$this->session->expects($this->at(1))
->method('getId')
->will($this->returnValue($session2_id));
$context1 = $this->cacheContext->getContext();
$context2 = $this->cacheContext->getContext();
$this->assertNotEquals($context1, $context2);
$this->assertSame(FALSE, strpos($context1, $session1_id), 'Session ID not contained in cache context');
$this->assertSame(FALSE, strpos($context2, $session2_id), 'Session ID not contained in cache context');
}
}

View file

@ -416,6 +416,27 @@ class EntityResolverManagerTest extends UnitTestCase {
$this->assertEquals($expect, $parameters);
}
/**
* Tests setRouteOptions() with an _entity_form route for an add form.
*
* @covers ::setRouteOptions
* @covers ::getControllerClass
* @covers ::getEntityTypes
* @covers ::setParametersFromReflection
* @covers ::setParametersFromEntityInformation
*/
public function testSetRouteOptionsWithEntityAddFormRoute() {
$this->setupEntityTypes();
$route = new Route('/example/add', array(
'_entity_form' => 'entity_test.add',
));
$defaults = $route->getDefaults();
$this->entityResolverManager->setRouteOptions($route);
$this->assertEquals($defaults, $route->getDefaults());
$this->assertFalse($route->hasOption('parameters'));
}
/**
* Creates the entity manager mock returning entity type objects.
*/

View file

@ -43,6 +43,11 @@ class PathRootsSubscriberTest extends UnitTestCase {
* @covers ::onRouteFinished
*/
public function testSubscribing() {
// Ensure that onRouteFinished can be called without throwing notices
// when no path roots got set.
$this->pathRootsSubscriber->onRouteFinished();
$route_collection = new RouteCollection();
$route_collection->add('test_route1', new Route('/test/bar'));
$route_collection->add('test_route2', new Route('/test/baz'));

View file

@ -568,6 +568,29 @@ class FormBuilderTest extends FormTestBase {
$this->formBuilder->buildForm($form_arg, $form_state);
}
/**
* @covers ::buildForm
*/
public function testGetPostAjaxRequest() {
$request = new Request([FormBuilderInterface::AJAX_FORM_REQUEST => TRUE], ['form_id' => 'different_form_id']);
$request->setMethod('POST');
$this->requestStack->push($request);
$form_state = (new FormState())
->setUserInput([FormBuilderInterface::AJAX_FORM_REQUEST => TRUE])
->setMethod('get')
->setAlwaysProcess()
->disableRedirect()
->set('ajax', TRUE);
$form_id = '\Drupal\Tests\Core\Form\TestForm';
$expected_form = (new TestForm())->buildForm([], $form_state);
$form = $this->formBuilder->buildForm($form_id, $form_state);
$this->assertFormElement($expected_form, $form, 'test');
$this->assertSame('test-form', $form['#id']);
}
/**
* @covers ::buildForm
*

View file

@ -4,12 +4,16 @@ namespace Drupal\Tests\Core\Routing;
use Drupal\Core\Routing\ContentTypeHeaderMatcher;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
/**
* Confirm that the content types partial matcher is functioning properly.
*
* @group Routing
*
* @coversDefaultClass \Drupal\Core\Routing\ContentTypeHeaderMatcher
*/
class ContentTypeHeaderMatcherTest extends UnitTestCase {
@ -88,8 +92,7 @@ class ContentTypeHeaderMatcherTest extends UnitTestCase {
/**
* Confirms that the matcher throws an exception for no-route.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException
* @expectedExceptionMessage No route found that matches "Content-Type: application/hal+json"
* @covers ::filter
*/
public function testNoRouteFound() {
$matcher = new ContentTypeHeaderMatcher();
@ -97,8 +100,24 @@ class ContentTypeHeaderMatcherTest extends UnitTestCase {
$routes = $this->fixtures->contentRouteCollection();
$request = Request::create('path/two', 'POST');
$request->headers->set('Content-type', 'application/hal+json');
$this->setExpectedException(UnsupportedMediaTypeHttpException::class, 'No route found that matches "Content-Type: application/hal+json"');
$matcher->filter($routes, $request);
}
/**
* Confirms that the matcher throws an exception for missing request header.
*
* @covers ::filter
*/
public function testContentTypeRequestHeaderMissing() {
$matcher = new ContentTypeHeaderMatcher();
$routes = $this->fixtures->contentRouteCollection();
$request = Request::create('path/two', 'POST');
// Delete all request headers that Request::create() sets by default.
$request->headers = new ParameterBag();
$this->setExpectedException(UnsupportedMediaTypeHttpException::class, 'No "Content-Type" request header specified');
$matcher->filter($routes, $request);
$this->fail('No exception was thrown.');
}
}