Drupal 8.0.0 beta 12. More info: https://www.drupal.org/node/2514176

This commit is contained in:
Pantheon Automation 2015-08-17 17:00:26 -07:00 committed by Greg Anderson
commit 9921556621
13277 changed files with 1459781 additions and 0 deletions

View file

@ -0,0 +1,336 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Controller\ViewAjaxControllerTest.
*/
namespace Drupal\Tests\views\Unit\Controller {
use Drupal\Tests\UnitTestCase;
use Drupal\views\Ajax\ViewAjaxResponse;
use Drupal\views\Controller\ViewAjaxController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* @coversDefaultClass \Drupal\views\Controller\ViewAjaxController
* @group views
*/
class ViewAjaxControllerTest extends UnitTestCase {
/**
* The mocked view entity storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $viewStorage;
/**
* The mocked executable factory.
*
* @var \Drupal\views\ViewExecutableFactory|\PHPUnit_Framework_MockObject_MockObject
*/
protected $executableFactory;
/**
* The tested views ajax controller.
*
* @var \Drupal\views\Controller\ViewAjaxController
*/
protected $viewAjaxController;
/**
* The mocked current path.
*
* @var \Drupal\Core\Path\CurrentPathStack|\PHPUnit_Framework_MockObject_MockObject
*/
protected $currentPath;
/**
* The redirect destination.
*
* @var \Drupal\Core\Routing\RedirectDestinationInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $redirectDestination;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $renderer;
/**
* {@inheritdoc}
*/
protected function setUp() {
$this->viewStorage = $this->getMock('Drupal\Core\Entity\EntityStorageInterface');
$this->executableFactory = $this->getMockBuilder('Drupal\views\ViewExecutableFactory')
->disableOriginalConstructor()
->getMock();
$this->renderer = $this->getMock('\Drupal\Core\Render\RendererInterface');
$this->renderer->expects($this->any())
->method('render')
->will($this->returnCallback(function(array &$elements) {
$elements['#attached'] = [];
return isset($elements['#markup']) ? $elements['#markup'] : '';
}));
$this->currentPath = $this->getMockBuilder('Drupal\Core\Path\CurrentPathStack')
->disableOriginalConstructor()
->getMock();
$this->redirectDestination = $this->getMock('\Drupal\Core\Routing\RedirectDestinationInterface');
$this->viewAjaxController = new ViewAjaxController($this->viewStorage, $this->executableFactory, $this->renderer, $this->currentPath, $this->redirectDestination);
$this->renderer = $this->getMockBuilder('Drupal\Core\Render\Renderer')
->disableOriginalConstructor()
->setMethods(NULL)
->getMock();
$container = new ContainerBuilder();
$container->set('renderer', $this->renderer);
\Drupal::setContainer($container);
}
/**
* Tests missing view_name and view_display_id
*
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testMissingViewName() {
$request = new Request();
$this->viewAjaxController->ajaxView($request);
}
/**
* Tests with view_name and view_display_id but not existing view.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testMissingView() {
$request = new Request();
$request->request->set('view_name', 'test_view');
$request->request->set('view_display_id', 'page_1');
$this->viewStorage->expects($this->once())
->method('load')
->with('test_view')
->will($this->returnValue(FALSE));
$this->viewAjaxController->ajaxView($request);
}
/**
* Tests a view without having access to it.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testAccessDeniedView() {
$request = new Request();
$request->request->set('view_name', 'test_view');
$request->request->set('view_display_id', 'page_1');
$view = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->getMock();
$this->viewStorage->expects($this->once())
->method('load')
->with('test_view')
->will($this->returnValue($view));
$executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$executable->expects($this->once())
->method('access')
->will($this->returnValue(FALSE));
$this->executableFactory->expects($this->once())
->method('get')
->with($view)
->will($this->returnValue($executable));
$this->viewAjaxController->ajaxView($request);
}
/**
* Tests a valid view without arguments pagers etc.
*/
public function testAjaxView() {
$request = new Request();
$request->request->set('view_name', 'test_view');
$request->request->set('view_display_id', 'page_1');
list($view, $executable) = $this->setupValidMocks();
$display_handler = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
// Ensure that the pager element is not set.
$display_handler->expects($this->never())
->method('setOption');
$display_collection = $this->getMockBuilder('Drupal\views\DisplayPluginCollection')
->disableOriginalConstructor()
->getMock();
$display_collection->expects($this->any())
->method('get')
->with('page_1')
->will($this->returnValue($display_handler));
$executable->displayHandlers = $display_collection;
$response = $this->viewAjaxController->ajaxView($request);
$this->assertTrue($response instanceof ViewAjaxResponse);
$this->assertSame($response->getView(), $executable);
$this->assertViewResultCommand($response);
}
/**
* Tests a valid view with arguments.
*/
public function testAjaxViewWithArguments() {
$request = new Request();
$request->request->set('view_name', 'test_view');
$request->request->set('view_display_id', 'page_1');
$request->request->set('view_args', 'arg1/arg2');
list($view, $executable) = $this->setupValidMocks();
$executable->expects($this->once())
->method('preview')
->with('page_1', array('arg1', 'arg2'));
$response = $this->viewAjaxController->ajaxView($request);
$this->assertTrue($response instanceof ViewAjaxResponse);
$this->assertViewResultCommand($response);
}
/**
* Tests a valid view with arguments.
*/
public function testAjaxViewWithEmptyArguments() {
$request = new Request();
$request->request->set('view_name', 'test_view');
$request->request->set('view_display_id', 'page_1');
// Simulate a request that has a second, empty argument.
$request->request->set('view_args', 'arg1/');
list($view, $executable) = $this->setupValidMocks();
$executable->expects($this->once())
->method('preview')
->with('page_1', $this->identicalTo(array('arg1', NULL)));
$response = $this->viewAjaxController->ajaxView($request);
$this->assertTrue($response instanceof ViewAjaxResponse);
$this->assertViewResultCommand($response);
}
/**
* Tests a valid view with a pager.
*/
public function testAjaxViewWithPager() {
$request = new Request();
$request->request->set('view_name', 'test_view');
$request->request->set('view_display_id', 'page_1');
$dom_id = $this->randomMachineName(20);
$request->request->set('view_dom_id', $dom_id);
$request->request->set('pager_element', '0');
list($view, $executable) = $this->setupValidMocks();
$display_handler = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$display_handler->expects($this->once())
->method('setOption', '0')
->with($this->equalTo('pager_element'));
$display_collection = $this->getMockBuilder('Drupal\views\DisplayPluginCollection')
->disableOriginalConstructor()
->getMock();
$display_collection->expects($this->any())
->method('get')
->with('page_1')
->will($this->returnValue($display_handler));
$executable->displayHandlers = $display_collection;
$response = $this->viewAjaxController->ajaxView($request);
$this->assertTrue($response instanceof ViewAjaxResponse);
$commands = $this->getCommands($response);
$this->assertEquals('viewsScrollTop', $commands[0]['command']);
$this->assertEquals('.js-view-dom-id-' . $dom_id, $commands[0]['selector']);
$this->assertViewResultCommand($response, 1);
}
/**
* Sets up a bunch of valid mocks like the view entity and executable.
*/
protected function setupValidMocks() {
$view = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->getMock();
$this->viewStorage->expects($this->once())
->method('load')
->with('test_view')
->will($this->returnValue($view));
$executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$executable->expects($this->once())
->method('access')
->will($this->returnValue(TRUE));
$executable->expects($this->once())
->method('preview')
->will($this->returnValue(array('#markup' => 'View result')));
$this->executableFactory->expects($this->once())
->method('get')
->with($view)
->will($this->returnValue($executable));
return array($view, $executable);
}
/**
* Gets the commands entry from the response object.
*
* @param \Drupal\views\Ajax\ViewAjaxResponse $response
* The views ajax response object.
*
* @return mixed
* Returns the commands.
*/
protected function getCommands(ViewAjaxResponse $response) {
$reflection_property = new \ReflectionProperty('Drupal\views\Ajax\ViewAjaxResponse', 'commands');
$reflection_property->setAccessible(TRUE);
$commands = $reflection_property->getValue($response);
return $commands;
}
/**
* Ensures that the main view content command is added.
*
* @param \Drupal\views\Ajax\ViewAjaxResponse $response
* The response object.
* @param int $position
* The position where the view content command is expected.
*/
protected function assertViewResultCommand(ViewAjaxResponse $response, $position = 0) {
$commands = $this->getCommands($response);
$this->assertEquals('insert', $commands[$position]['command']);
$this->assertEquals('View result', $commands[$position]['data']);
}
}
}

View file

@ -0,0 +1,942 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\EntityViewsDataTest.
*/
namespace Drupal\Tests\views\Unit {
use Drupal\Core\Config\Entity\ConfigEntityType;
use Drupal\Core\Entity\ContentEntityType;
use Drupal\Core\Entity\EntityType;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\Core\Field\Plugin\Field\FieldType\IntegerItem;
use Drupal\Core\Field\Plugin\Field\FieldType\LanguageItem;
use Drupal\Core\Field\Plugin\Field\FieldType\StringItem;
use Drupal\Core\Field\Plugin\Field\FieldType\UriItem;
use Drupal\Core\Field\Plugin\Field\FieldType\UuidItem;
use Drupal\text\Plugin\Field\FieldType\TextLongItem;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\entity_test\Entity\EntityTestMul;
use Drupal\entity_test\Entity\EntityTestMulRev;
use Drupal\Tests\UnitTestCase;
use Drupal\views\EntityViewsData;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* @coversDefaultClass \Drupal\views\EntityViewsData
* @group Views
*/
class EntityViewsDataTest extends UnitTestCase {
/**
* Entity info to use in this test.
*
* @var \Drupal\Core\Entity\EntityTypeInterface|\Drupal\Tests\views\Unit\TestEntityType
*/
protected $baseEntityType;
/**
* The mocked entity storage.
*
* @var \Drupal\Core\Entity\Sql\SqlContentEntityStorage|\PHPUnit_Framework_MockObject_MockObject
*/
protected $entityStorage;
/**
* The mocked entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $entityManager;
/**
* The mocked module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $moduleHandler;
/**
* The mocked translation manager.
*
* @var \Drupal\Core\StringTranslation\TranslationInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $translationManager;
/**
* The tested entity views controller.
*
* @var \Drupal\Tests\views\Unit\TestEntityViewsData
*/
protected $viewsData;
/**
* {@inheritdoc}
*/
protected function setUp() {
$this->entityStorage = $this->getMockBuilder('Drupal\Core\Entity\Sql\SqlContentEntityStorage')
->disableOriginalConstructor()
->getMock();
$this->entityManager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface');
$typed_data_manager = $this->getMockBuilder('Drupal\Core\TypedData\TypedDataManager')
->disableOriginalConstructor()
->getMock();
$typed_data_manager->expects($this->any())
->method('createDataDefinition')
->willReturn($this->getMock('Drupal\Core\TypedData\DataDefinitionInterface'));
$this->baseEntityType = new TestEntityType([
'base_table' => 'entity_test',
'id' => 'entity_test',
'label' => 'Entity test',
'entity_keys' => ['id' => 'id', 'langcode' => 'langcode'],
'provider' => 'entity_test',
'list_cache_contexts' => ['entity_test_list_cache_context'],
]);
$this->translationManager = $this->getStringTranslationStub();
$this->moduleHandler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');
$this->viewsData = new TestEntityViewsData($this->baseEntityType, $this->entityStorage, $this->entityManager, $this->moduleHandler, $this->translationManager);
$field_type_manager = $this->getMockBuilder('Drupal\Core\Field\FieldTypePluginManager')
->disableOriginalConstructor()
->getMock();
$field_type_manager->expects($this->any())
->method('getDefaultStorageSettings')
->willReturn([]);
$field_type_manager->expects($this->any())
->method('getDefaultFieldSettings')
->willReturn([]);
$container = new ContainerBuilder();
$container->set('plugin.manager.field.field_type', $field_type_manager);
$container->set('entity.manager', $this->entityManager);
$container->set('typed_data_manager', $typed_data_manager);
\Drupal::setContainer($container);
}
/**
* Helper method to setup base fields.
*
* @param \Drupal\Core\Field\BaseFieldDefinition[] $base_fields
* The base fields which are adapted.
*
* @return \Drupal\Core\Field\BaseFieldDefinition[]
* The setup base fields.
*/
protected function setupBaseFields(array $base_fields) {
// Add a description field to the fields supplied by the EntityTest
// classes. This example comes from the taxonomy Term entity.
$base_fields['description'] = BaseFieldDefinition::create('text_long')
->setLabel(t('Description'))
->setDescription(t('A description of the term.'))
->setTranslatable(TRUE)
->setDisplayOptions('view', array(
'label' => 'hidden',
'type' => 'text_default',
'weight' => 0,
))
->setDisplayConfigurable('view', TRUE)
->setDisplayOptions('form', array(
'type' => 'text_textfield',
'weight' => 0,
))
->setDisplayConfigurable('form', TRUE);
// Add a URL field; this example is from the Comment entity.
$base_fields['homepage'] = BaseFieldDefinition::create('uri')
->setLabel(t('Homepage'))
->setDescription(t("The comment author's home page address."))
->setTranslatable(TRUE)
->setSetting('max_length', 255);
foreach ($base_fields as $name => $base_field) {
$base_field->setName($name);
}
return $base_fields;
}
/**
* Tests base tables.
*/
public function testBaseTables() {
$data = $this->viewsData->getViewsData();
$this->assertEquals('entity_test', $data['entity_test']['table']['entity type']);
$this->assertEquals(FALSE, $data['entity_test']['table']['entity revision']);
$this->assertEquals('Entity test', $data['entity_test']['table']['group']);
$this->assertEquals('entity_test', $data['entity_test']['table']['provider']);
$this->assertEquals('id', $data['entity_test']['table']['base']['field']);
$this->assertEquals(['entity_test_list_cache_context'], $data['entity_test']['table']['base']['cache_contexts']);
$this->assertEquals('Entity test', $data['entity_test']['table']['base']['title']);
$this->assertFalse(isset($data['entity_test']['table']['defaults']));
$this->assertFalse(isset($data['entity_test_mul_property_data']));
$this->assertFalse(isset($data['revision_table']));
$this->assertFalse(isset($data['revision_data_table']));
}
/**
* Tests data_table support.
*/
public function testDataTable() {
$entity_type = $this->baseEntityType
->set('data_table', 'entity_test_mul_property_data')
->set('id', 'entity_test_mul')
->setKey('label', 'label');
$this->viewsData->setEntityType($entity_type);
// Tests the join definition between the base and the data table.
$data = $this->viewsData->getViewsData();
$base_views_data = $data['entity_test'];
// Ensure that the base table is set to the data table.
$this->assertEquals('id', $data['entity_test_mul_property_data']['table']['base']['field']);
$this->assertEquals('Entity test', $data['entity_test_mul_property_data']['table']['base']['title']);
$this->assertFalse(isset($data['entity_test']['table']['base']));
$this->assertEquals('entity_test_mul', $data['entity_test_mul_property_data']['table']['entity type']);
$this->assertEquals(FALSE, $data['entity_test_mul_property_data']['table']['entity revision']);
$this->assertEquals('Entity test', $data['entity_test_mul_property_data']['table']['group']);
$this->assertEquals('entity_test', $data['entity_test']['table']['provider']);
$this->assertEquals(['field' => 'label', 'table' => 'entity_test_mul_property_data'], $data['entity_test_mul_property_data']['table']['base']['defaults']);
// Ensure the join information is set up properly.
$this->assertCount(1, $base_views_data['table']['join']);
$this->assertEquals(['entity_test_mul_property_data' => ['left_field' => 'id', 'field' => 'id', 'type' => 'INNER']], $base_views_data['table']['join']);
$this->assertFalse(isset($data['revision_table']));
$this->assertFalse(isset($data['revision_data_table']));
}
/**
* Tests revision table without data table support.
*/
public function testRevisionTableWithoutDataTable() {
$entity_type = $this->baseEntityType
->set('revision_table', 'entity_test_mulrev_revision')
->set('revision_data_table', NULL)
->set('id', 'entity_test_mulrev')
->setKey('revision', 'revision_id')
;
$this->viewsData->setEntityType($entity_type);
$data = $this->viewsData->getViewsData();
$this->assertEquals('Entity test revisions', $data['entity_test_mulrev_revision']['table']['base']['title']);
$this->assertEquals('revision_id', $data['entity_test_mulrev_revision']['table']['base']['field']);
$this->assertEquals(FALSE, $data['entity_test']['table']['entity revision']);
$this->assertEquals('entity_test_mulrev', $data['entity_test_mulrev_revision']['table']['entity type']);
$this->assertEquals(TRUE, $data['entity_test_mulrev_revision']['table']['entity revision']);
$this->assertEquals('entity_test_mulrev', $data['entity_test_mulrev_revision']['table']['entity type']);
$this->assertEquals(TRUE, $data['entity_test_mulrev_revision']['table']['entity revision']);
$this->assertEquals('Entity test revision', $data['entity_test_mulrev_revision']['table']['group']);
$this->assertEquals('entity_test', $data['entity_test']['table']['provider']);
// Ensure the join information is set up properly.
// Tests the join definition between the base and the revision table.
$revision_data = $data['entity_test_mulrev_revision'];
$this->assertCount(1, $revision_data['table']['join']);
$this->assertEquals(['entity_test' => ['left_field' => 'revision_id', 'field' => 'revision_id', 'type' => 'INNER']], $revision_data['table']['join']);
$this->assertFalse(isset($data['data_table']));
}
/**
* Tests revision table with data table support.
*/
public function testRevisionTableWithRevisionDataTableAndDataTable() {
$entity_type = $this->baseEntityType
->set('data_table', 'entity_test_mul_property_data')
->set('revision_table', 'entity_test_mulrev_revision')
->set('revision_data_table', 'entity_test_mulrev_property_revision')
->set('id', 'entity_test_mulrev')
->setKey('revision', 'revision_id')
;
$this->viewsData->setEntityType($entity_type);
$data = $this->viewsData->getViewsData();
$this->assertEquals('Entity test revisions', $data['entity_test_mulrev_property_revision']['table']['base']['title']);
$this->assertEquals('revision_id', $data['entity_test_mulrev_property_revision']['table']['base']['field']);
$this->assertFalse(isset($data['entity_test_mulrev_revision']['table']['base']));
$this->assertEquals('entity_test_mulrev', $data['entity_test_mulrev_property_revision']['table']['entity type']);
$this->assertEquals('Entity test revision', $data['entity_test_mulrev_revision']['table']['group']);
$this->assertEquals('entity_test', $data['entity_test']['table']['provider']);
// Ensure the join information is set up properly.
// Tests the join definition between the base and the revision table.
$revision_data = $data['entity_test_mulrev_property_revision'];
$this->assertCount(2, $revision_data['table']['join']);
$this->assertEquals([
'entity_test_mul_property_data' => [
'left_field' => 'revision_id', 'field' => 'revision_id', 'type' => 'INNER'
],
'entity_test_mulrev_revision' => [
'left_field' => 'revision_id', 'field' => 'revision_id', 'type' => 'INNER'
],
], $revision_data['table']['join']);
$this->assertFalse(isset($data['data_table']));
}
/**
* Tests revision table with data table support.
*/
public function testRevisionTableWithRevisionDataTable() {
$entity_type = $this->baseEntityType
->set('revision_table', 'entity_test_mulrev_revision')
->set('revision_data_table', 'entity_test_mulrev_property_revision')
->set('id', 'entity_test_mulrev')
->setKey('revision', 'revision_id')
;
$this->viewsData->setEntityType($entity_type);
$data = $this->viewsData->getViewsData();
$this->assertEquals('Entity test revisions', $data['entity_test_mulrev_property_revision']['table']['base']['title']);
$this->assertEquals('revision_id', $data['entity_test_mulrev_property_revision']['table']['base']['field']);
$this->assertFalse(isset($data['entity_test_mulrev_revision']['table']['base']));
$this->assertEquals('entity_test_mulrev', $data['entity_test_mulrev_property_revision']['table']['entity type']);
$this->assertEquals('Entity test revision', $data['entity_test_mulrev_revision']['table']['group']);
$this->assertEquals('entity_test', $data['entity_test']['table']['provider']);
// Ensure the join information is set up properly.
// Tests the join definition between the base and the revision table.
$revision_data = $data['entity_test_mulrev_property_revision'];
$this->assertCount(2, $revision_data['table']['join']);
$this->assertEquals([
'entity_test' => ['left_field' => 'revision_id', 'field' => 'revision_id', 'type' => 'INNER'],
'entity_test_mulrev_revision' => ['left_field' => 'revision_id', 'field' => 'revision_id', 'type' => 'INNER'],
], $revision_data['table']['join']);
$this->assertFalse(isset($data['data_table']));
}
/**
* Helper method to mock all store definitions.
*/
protected function setupFieldStorageDefinition() {
$id_field_storage_definition = $this->getMock('Drupal\Core\Field\FieldStorageDefinitionInterface');
$id_field_storage_definition->expects($this->any())
->method('getSchema')
->willReturn(IntegerItem::schema($id_field_storage_definition));
$uuid_field_storage_definition = $this->getMock('Drupal\Core\Field\FieldStorageDefinitionInterface');
$uuid_field_storage_definition->expects($this->any())
->method('getSchema')
->willReturn(UuidItem::schema($uuid_field_storage_definition));
$type_field_storage_definition = $this->getMock('Drupal\Core\Field\FieldStorageDefinitionInterface');
$type_field_storage_definition->expects($this->any())
->method('getSchema')
->willReturn(StringItem::schema($type_field_storage_definition));
$langcode_field_storage_definition = $this->getMock('Drupal\Core\Field\FieldStorageDefinitionInterface');
$langcode_field_storage_definition->expects($this->any())
->method('getSchema')
->willReturn(LanguageItem::schema($langcode_field_storage_definition));
$name_field_storage_definition = $this->getMock('Drupal\Core\Field\FieldStorageDefinitionInterface');
$name_field_storage_definition->expects($this->any())
->method('getSchema')
->willReturn(StringItem::schema($name_field_storage_definition));
$description_field_storage_definition = $this->getMock('Drupal\Core\Field\FieldStorageDefinitionInterface');
$description_field_storage_definition->expects($this->any())
->method('getSchema')
->willReturn(TextLongItem::schema($description_field_storage_definition));
$homepage_field_storage_definition = $this->getMock('Drupal\Core\Field\FieldStorageDefinitionInterface');
$homepage_field_storage_definition->expects($this->any())
->method('getSchema')
->willReturn(UriItem::schema($homepage_field_storage_definition));
// Setup the user_id entity reference field.
$this->entityManager->expects($this->any())
->method('getDefinition')
->willReturnMap([
['user', TRUE, static::userEntityInfo()],
]
);
$user_id_field_storage_definition = $this->getMock('Drupal\Core\Field\FieldStorageDefinitionInterface');
$user_id_field_storage_definition->expects($this->any())
->method('getSetting')
->with('target_type')
->willReturn('user');
$user_id_field_storage_definition->expects($this->any())
->method('getSettings')
->willReturn(['target_type' => 'user']);
$user_id_field_storage_definition->expects($this->any())
->method('getSchema')
->willReturn(EntityReferenceItem::schema($user_id_field_storage_definition));
$revision_id_field_storage_definition = $this->getMock('Drupal\Core\Field\FieldStorageDefinitionInterface');
$revision_id_field_storage_definition->expects($this->any())
->method('getSchema')
->willReturn(IntegerItem::schema($revision_id_field_storage_definition));
$this->entityManager->expects($this->any())
->method('getFieldStorageDefinitions')
->willReturn([
'id' => $id_field_storage_definition,
'uuid' => $uuid_field_storage_definition,
'type' => $type_field_storage_definition,
'langcode' => $langcode_field_storage_definition,
'name' => $name_field_storage_definition,
'description' => $description_field_storage_definition,
'homepage' => $homepage_field_storage_definition,
'user_id' => $user_id_field_storage_definition,
'revision_id' => $revision_id_field_storage_definition,
]);
}
/**
* Tests fields on the base table.
*/
public function testBaseTableFields() {
$base_field_definitions = $this->setupBaseFields(EntityTest::baseFieldDefinitions($this->baseEntityType));
$user_base_field_definitions = [
'uid' => BaseFieldDefinition::create('integer')
->setLabel(t('ID'))
->setDescription(t('The ID of the user entity.'))
->setReadOnly(TRUE)
->setSetting('unsigned', TRUE)
];
$this->entityManager->expects($this->any())
->method('getBaseFieldDefinitions')
->will($this->returnValueMap([
['user', $user_base_field_definitions],
['entity_test', $base_field_definitions],
]));
// Setup the table mapping.
$table_mapping = $this->getMock('Drupal\Core\Entity\Sql\TableMappingInterface');
$table_mapping->expects($this->any())
->method('getTableNames')
->willReturn(['entity_test']);
$table_mapping->expects($this->any())
->method('getColumnNames')
->willReturnMap([
['id', ['value' => 'id']],
['uuid', ['value' => 'uuid']],
['type', ['value' => 'type']],
['langcode', ['value' => 'langcode']],
['name', ['value' => 'name']],
['description', ['value' => 'description__value', 'format' => 'description__format']],
['homepage', ['value' => 'homepage']],
['user_id', ['target_id' => 'user_id']],
]);
$table_mapping->expects($this->any())
->method('getFieldNames')
->willReturnMap([
['entity_test', ['id', 'uuid', 'type', 'langcode', 'name', 'description', 'homepage', 'user_id']]
]);
$this->entityStorage->expects($this->once())
->method('getTableMapping')
->willReturn($table_mapping);
$this->setupFieldStorageDefinition();
$data = $this->viewsData->getViewsData();
$this->assertNumericField($data['entity_test']['id']);
$this->assertField($data['entity_test']['id'], 'id');
$this->assertUuidField($data['entity_test']['uuid']);
$this->assertField($data['entity_test']['uuid'], 'uuid');
$this->assertStringField($data['entity_test']['type']);
$this->assertEquals('type', $data['entity_test']['type']['entity field']);
$this->assertLanguageField($data['entity_test']['langcode']);
$this->assertField($data['entity_test']['langcode'], 'langcode');
$this->assertEquals('Original language', $data['entity_test']['langcode']['title']);
$this->assertStringField($data['entity_test']['name']);
$this->assertField($data['entity_test']['name'], 'name');
$this->assertLongTextField($data['entity_test'], 'description');
$this->assertField($data['entity_test']['description__value'], 'description');
$this->assertField($data['entity_test']['description__format'], 'description');
$this->assertUriField($data['entity_test']['homepage']);
$this->assertField($data['entity_test']['homepage'], 'homepage');
$this->assertEntityReferenceField($data['entity_test']['user_id']);
$this->assertField($data['entity_test']['user_id'], 'user_id');
$relationship = $data['entity_test']['user_id']['relationship'];
$this->assertEquals('users_field_data', $relationship['base']);
$this->assertEquals('uid', $relationship['base field']);
}
/**
* Tests fields on the data table.
*/
public function testDataTableFields() {
$entity_type = $this->baseEntityType
->set('data_table', 'entity_test_mul_property_data')
->set('base_table', 'entity_test_mul')
->set('id', 'entity_test_mul')
->setKey('bundle', 'type')
;
$base_field_definitions = $this->setupBaseFields(EntityTestMul::baseFieldDefinitions($this->baseEntityType));
$base_field_definitions['type'] = BaseFieldDefinition::create('entity_reference')
->setLabel('entity test type')
->setSettings(array('target_type' => 'entity_test_bundle'))
->setTranslatable(TRUE);
$base_field_definitions = $this->setupBaseFields($base_field_definitions);
$user_base_field_definitions = [
'uid' => BaseFieldDefinition::create('integer')
->setLabel(t('ID'))
->setDescription(t('The ID of the user entity.'))
->setReadOnly(TRUE)
->setSetting('unsigned', TRUE)
];
$entity_test_type = new ConfigEntityType(['id' => 'entity_test_bundle']);
$this->entityManager->expects($this->any())
->method('getBaseFieldDefinitions')
->will($this->returnValueMap([
['user', $user_base_field_definitions],
['entity_test_mul', $base_field_definitions],
]));
$this->viewsData->setEntityType($entity_type);
// Setup the table mapping.
$table_mapping = $this->getMock('Drupal\Core\Entity\Sql\TableMappingInterface');
$table_mapping->expects($this->any())
->method('getTableNames')
->willReturn(['entity_test_mul', 'entity_test_mul_property_data']);
$table_mapping->expects($this->any())
->method('getColumnNames')
->willReturnMap([
['id', ['value' => 'id']],
['uuid', ['value' => 'uuid']],
['type', ['value' => 'type']],
['langcode', ['value' => 'langcode']],
['name', ['value' => 'name']],
['description', ['value' => 'description__value', 'format' => 'description__format']],
['homepage', ['value' => 'homepage']],
['user_id', ['target_id' => 'user_id']],
]);
$table_mapping->expects($this->any())
->method('getFieldNames')
->willReturnMap([
['entity_test_mul', ['id', 'uuid', 'type', 'langcode']],
['entity_test_mul_property_data', ['id', 'langcode', 'name', 'description', 'homepage', 'user_id']],
]);
$this->entityStorage->expects($this->once())
->method('getTableMapping')
->willReturn($table_mapping);
$this->setupFieldStorageDefinition();
$user_entity_type = static::userEntityInfo();
$this->entityManager->expects($this->any())
->method('getDefinition')
->will($this->returnValueMap([
['user', TRUE, $user_entity_type],
['entity_test_bundle', TRUE, $entity_test_type],
]));
$data = $this->viewsData->getViewsData();
// Check the base fields.
$this->assertNumericField($data['entity_test_mul']['id']);
$this->assertField($data['entity_test_mul']['id'], 'id');
$this->assertUuidField($data['entity_test_mul']['uuid']);
$this->assertField($data['entity_test_mul']['uuid'], 'uuid');
$this->assertBundleField($data['entity_test_mul']['type']);
$this->assertField($data['entity_test_mul']['type'], 'type');
$this->assertFalse(isset($data['entity_test_mul']['type']['relationship']));
$this->assertLanguageField($data['entity_test_mul']['langcode']);
$this->assertField($data['entity_test_mul']['langcode'], 'langcode');
// Also ensure that field_data only fields don't appear on the base table.
$this->assertFalse(isset($data['entity_test_mul']['name']));
$this->assertFalse(isset($data['entity_test_mul']['description']));
$this->assertFalse(isset($data['entity_test_mul']['description__value']));
$this->assertFalse(isset($data['entity_test_mul']['description__format']));
$this->assertFalse(isset($data['entity_test_mul']['user_id']));
$this->assertFalse(isset($data['entity_test_mul']['homepage']));
// Check the data fields.
$this->assertNumericField($data['entity_test_mul_property_data']['id']);
$this->assertField($data['entity_test_mul_property_data']['id'], 'id');
$this->assertLanguageField($data['entity_test_mul_property_data']['langcode']);
$this->assertField($data['entity_test_mul_property_data']['langcode'], 'langcode');
$this->assertEquals('Translation language', $data['entity_test_mul_property_data']['langcode']['title']);
$this->assertStringField($data['entity_test_mul_property_data']['name']);
$this->assertField($data['entity_test_mul_property_data']['name'], 'name');
$this->assertLongTextField($data['entity_test_mul_property_data'], 'description');
$this->assertField($data['entity_test_mul_property_data']['description__value'], 'description');
$this->assertField($data['entity_test_mul_property_data']['description__format'], 'description');
$this->assertUriField($data['entity_test_mul_property_data']['homepage']);
$this->assertField($data['entity_test_mul_property_data']['homepage'], 'homepage');
$this->assertEntityReferenceField($data['entity_test_mul_property_data']['user_id']);
$this->assertField($data['entity_test_mul_property_data']['user_id'], 'user_id');
$relationship = $data['entity_test_mul_property_data']['user_id']['relationship'];
$this->assertEquals('users_field_data', $relationship['base']);
$this->assertEquals('uid', $relationship['base field']);
}
/**
* Tests fields on the revision table.
*/
public function testRevisionTableFields() {
$entity_type = $this->baseEntityType
->set('base_table', 'entity_test_mulrev')
->set('revision_table', 'entity_test_mulrev_revision')
->set('data_table', 'entity_test_mulrev_property_data')
->set('revision_data_table', 'entity_test_mulrev_property_revision')
->set('id', 'entity_test_mulrev');
$base_field_definitions = $this->setupBaseFields(EntityTestMulRev::baseFieldDefinitions($this->baseEntityType));
$user_base_field_definitions = [
'uid' => BaseFieldDefinition::create('integer')
->setLabel(t('ID'))
->setDescription(t('The ID of the user entity.'))
->setReadOnly(TRUE)
->setSetting('unsigned', TRUE)
];
$this->entityManager->expects($this->any())
->method('getBaseFieldDefinitions')
->will($this->returnValueMap([
['user', $user_base_field_definitions],
['entity_test_mulrev', $base_field_definitions],
]));
$this->viewsData->setEntityType($entity_type);
// Setup the table mapping.
$table_mapping = $this->getMock('Drupal\Core\Entity\Sql\TableMappingInterface');
$table_mapping->expects($this->any())
->method('getTableNames')
->willReturn(['entity_test_mulrev', 'entity_test_mulrev_revision', 'entity_test_mulrev_property_data', 'entity_test_mulrev_property_revision']);
$table_mapping->expects($this->any())
->method('getColumnNames')
->willReturnMap([
['id', ['value' => 'id']],
['uuid', ['value' => 'uuid']],
['type', ['value' => 'type']],
['langcode', ['value' => 'langcode']],
['name', ['value' => 'name']],
['description', ['value' => 'description__value', 'format' => 'description__format']],
['homepage', ['value' => 'homepage']],
['user_id', ['target_id' => 'user_id']],
['revision_id', ['value' => 'id']],
]);
$table_mapping->expects($this->any())
->method('getFieldNames')
->willReturnMap([
['entity_test_mulrev', ['id', 'revision_id', 'uuid', 'type']],
['entity_test_mulrev_revision', ['id', 'revision_id', 'langcode']],
['entity_test_mulrev_property_data', ['id', 'revision_id', 'langcode', 'name', 'description', 'homepage', 'user_id']],
['entity_test_mulrev_property_revision', ['id', 'revision_id', 'langcode', 'name', 'description', 'homepage', 'user_id']],
]);
$this->entityStorage->expects($this->once())
->method('getTableMapping')
->willReturn($table_mapping);
$this->setupFieldStorageDefinition();
$data = $this->viewsData->getViewsData();
// Check the base fields.
$this->assertNumericField($data['entity_test_mulrev']['id']);
$this->assertField($data['entity_test_mulrev']['id'], 'id');
$this->assertNumericField($data['entity_test_mulrev']['revision_id']);
$this->assertField($data['entity_test_mulrev']['revision_id'], 'revision_id');
$this->assertUuidField($data['entity_test_mulrev']['uuid']);
$this->assertField($data['entity_test_mulrev']['uuid'], 'uuid');
$this->assertStringField($data['entity_test_mulrev']['type']);
$this->assertField($data['entity_test_mulrev']['type'], 'type');
// Also ensure that field_data only fields don't appear on the base table.
$this->assertFalse(isset($data['entity_test_mulrev']['name']));
$this->assertFalse(isset($data['entity_test_mul']['description']));
$this->assertFalse(isset($data['entity_test_mul']['description__value']));
$this->assertFalse(isset($data['entity_test_mul']['description__format']));
$this->assertFalse(isset($data['entity_test_mul']['homepage']));
$this->assertFalse(isset($data['entity_test_mulrev']['langcode']));
$this->assertFalse(isset($data['entity_test_mulrev']['user_id']));
// Check the revision fields.
$this->assertNumericField($data['entity_test_mulrev_revision']['id']);
$this->assertField($data['entity_test_mulrev_revision']['id'], 'id');
$this->assertNumericField($data['entity_test_mulrev_revision']['revision_id']);
$this->assertField($data['entity_test_mulrev_revision']['revision_id'], 'revision_id');
$this->assertLanguageField($data['entity_test_mulrev_revision']['langcode']);
$this->assertField($data['entity_test_mulrev_revision']['langcode'], 'langcode');
$this->assertEquals('Original language', $data['entity_test_mulrev_revision']['langcode']['title']);
// Also ensure that field_data only fields don't appear on the revision table.
$this->assertFalse(isset($data['entity_test_mulrev_revision']['name']));
$this->assertFalse(isset($data['entity_test_mulrev_revision']['description']));
$this->assertFalse(isset($data['entity_test_mulrev_revision']['description__value']));
$this->assertFalse(isset($data['entity_test_mulrev_revision']['description__format']));
$this->assertFalse(isset($data['entity_test_mulrev_revision']['homepage']));
$this->assertFalse(isset($data['entity_test_mulrev_revision']['user_id']));
// Check the data fields.
$this->assertNumericField($data['entity_test_mulrev_property_data']['id']);
$this->assertField($data['entity_test_mulrev_property_data']['id'], 'id');
$this->assertLanguageField($data['entity_test_mulrev_property_data']['langcode']);
$this->assertField($data['entity_test_mulrev_property_data']['langcode'], 'langcode');
$this->assertStringField($data['entity_test_mulrev_property_data']['name']);
$this->assertField($data['entity_test_mulrev_property_data']['name'], 'name');
$this->assertLongTextField($data['entity_test_mulrev_property_data'], 'description');
$this->assertField($data['entity_test_mulrev_property_data']['description__value'], 'description');
$this->assertField($data['entity_test_mulrev_property_data']['description__format'], 'description');
$this->assertUriField($data['entity_test_mulrev_property_data']['homepage']);
$this->assertField($data['entity_test_mulrev_property_data']['homepage'], 'homepage');
$this->assertEntityReferenceField($data['entity_test_mulrev_property_data']['user_id']);
$this->assertField($data['entity_test_mulrev_property_data']['user_id'], 'user_id');
$relationship = $data['entity_test_mulrev_property_data']['user_id']['relationship'];
$this->assertEquals('users_field_data', $relationship['base']);
$this->assertEquals('uid', $relationship['base field']);
// Check the property data fields.
$this->assertNumericField($data['entity_test_mulrev_property_revision']['id']);
$this->assertField($data['entity_test_mulrev_property_revision']['id'], 'id');
$this->assertLanguageField($data['entity_test_mulrev_property_revision']['langcode']);
$this->assertField($data['entity_test_mulrev_property_revision']['langcode'], 'langcode');
$this->assertEquals('Translation language', $data['entity_test_mulrev_property_revision']['langcode']['title']);
$this->assertStringField($data['entity_test_mulrev_property_revision']['name']);
$this->assertField($data['entity_test_mulrev_property_revision']['name'], 'name');
$this->assertLongTextField($data['entity_test_mulrev_property_revision'], 'description');
$this->assertField($data['entity_test_mulrev_property_revision']['description__value'], 'description');
$this->assertField($data['entity_test_mulrev_property_revision']['description__format'], 'description');
$this->assertUriField($data['entity_test_mulrev_property_revision']['homepage']);
$this->assertField($data['entity_test_mulrev_property_revision']['homepage'], 'homepage');
$this->assertEntityReferenceField($data['entity_test_mulrev_property_revision']['user_id']);
$this->assertField($data['entity_test_mulrev_property_revision']['user_id'], 'user_id');
$relationship = $data['entity_test_mulrev_property_revision']['user_id']['relationship'];
$this->assertEquals('users_field_data', $relationship['base']);
$this->assertEquals('uid', $relationship['base field']);
}
/**
* Tests generic stuff per field.
*
* @param array $data
* The views data to check.
* @param string $field_name
* The entity field name.
*/
protected function assertField($data, $field_name) {
$this->assertEquals($field_name, $data['entity field']);
}
/**
* Tests add link types.
*/
public function testEntityLinks() {
$this->baseEntityType->setLinkTemplate('canonical', '/entity_test/{entity_test}');
$this->baseEntityType->setLinkTemplate('edit-form', '/entity_test/{entity_test}/edit');
$this->baseEntityType->setLinkTemplate('delete-form', '/entity_test/{entity_test}/delete');
$data = $this->viewsData->getViewsData();
$this->assertEquals('entity_link', $data['entity_test']['view_entity_test']['field']['id']);
$this->assertEquals('entity_link_edit', $data['entity_test']['edit_entity_test']['field']['id']);
$this->assertEquals('entity_link_delete', $data['entity_test']['delete_entity_test']['field']['id']);
}
/**
* Tests additional edit links.
*/
public function testEntityLinksJustEditForm() {
$this->baseEntityType->setLinkTemplate('edit-form', '/entity_test/{entity_test}/edit');
$data = $this->viewsData->getViewsData();
$this->assertFalse(isset($data['entity_test']['view_entity_test']));
$this->assertFalse(isset($data['entity_test']['delete_entity_test']));
$this->assertEquals('entity_link_edit', $data['entity_test']['edit_entity_test']['field']['id']);
}
/**
* Tests views data for a string field.
*
* @param $data
* The views data to check.
*/
protected function assertStringField($data) {
$this->assertEquals('field', $data['field']['id']);
$this->assertEquals('string', $data['filter']['id']);
$this->assertEquals('string', $data['argument']['id']);
$this->assertEquals('standard', $data['sort']['id']);
}
/**
* Tests views data for a URI field.
*
* @param $data
* The views data to check.
*/
protected function assertUriField($data) {
$this->assertEquals('field', $data['field']['id']);
$this->assertEquals('string', $data['field']['default_formatter']);
$this->assertEquals('string', $data['filter']['id']);
$this->assertEquals('string', $data['argument']['id']);
$this->assertEquals('standard', $data['sort']['id']);
}
/**
* Tests views data for a long text field.
*
* @param $data
* The views data for the table this field is in.
* @param $field_name
* The name of the field being checked.
*/
protected function assertLongTextField($data, $field_name) {
$value_field = $data[$field_name . '__value'];
$this->assertEquals('field', $value_field['field']['id']);
$this->assertEquals($field_name . '__format', $value_field['field']['format']);
$this->assertEquals('string', $value_field['filter']['id']);
$this->assertEquals('string', $value_field['argument']['id']);
$this->assertEquals('standard', $value_field['sort']['id']);
$this->assertStringField($data[$field_name . '__format']);
}
/**
* Tests views data for a UUID field.
*
* @param array $data
* The views data to check.
*/
protected function assertUuidField($data) {
// @todo Can we provide additional support for UUIDs in views?
$this->assertEquals('field', $data['field']['id']);
$this->assertFalse($data['field']['click sortable']);
$this->assertEquals('string', $data['filter']['id']);
$this->assertEquals('string', $data['argument']['id']);
$this->assertEquals('standard', $data['sort']['id']);
}
/**
* Tests views data for a numeric field.
*
* @param array $data
* The views data to check.
*/
protected function assertNumericField($data) {
$this->assertEquals('field', $data['field']['id']);
$this->assertEquals('numeric', $data['filter']['id']);
$this->assertEquals('numeric', $data['argument']['id']);
$this->assertEquals('standard', $data['sort']['id']);
}
/**
* Tests views data for a language field.
*
* @param array $data
* The views data to check.
*/
protected function assertLanguageField($data) {
$this->assertEquals('field', $data['field']['id']);
$this->assertEquals('language', $data['filter']['id']);
$this->assertEquals('language', $data['argument']['id']);
$this->assertEquals('standard', $data['sort']['id']);
}
/**
* Tests views data for a entity reference field.
*/
protected function assertEntityReferenceField($data) {
$this->assertEquals('field', $data['field']['id']);
$this->assertEquals('numeric', $data['filter']['id']);
$this->assertEquals('numeric', $data['argument']['id']);
$this->assertEquals('standard', $data['sort']['id']);
}
/**
* Tests views data for a bundle field.
*/
protected function assertBundleField($data) {
$this->assertEquals('field', $data['field']['id']);
$this->assertEquals('bundle', $data['filter']['id']);
$this->assertEquals('string', $data['argument']['id']);
$this->assertEquals('standard', $data['sort']['id']);
}
/**
* Returns entity info for the user entity.
*
* @return array
*/
protected static function userEntityInfo() {
return new ContentEntityType([
'id' => 'user',
'class' => 'Drupal\user\Entity\User',
'label' => 'User',
'base_table' => 'users',
'data_table' => 'users_field_data',
'entity_keys' => [
'id' => 'uid',
'uuid' => 'uuid',
],
]);
}
}
class TestEntityViewsData extends EntityViewsData {
public function setEntityType(EntityTypeInterface $entity_type) {
$this->entityType = $entity_type;
}
}
class TestEntityType extends EntityType {
/**
* Sets a specific entity key.
*
* @param string $key
* The name of the entity key.
* @param string $value
* The new value of the key.
*
* @return $this
*/
public function setKey($key, $value) {
$this->entity_keys[$key] = $value;
return $this;
}
}
}
namespace {
use Drupal\Component\Utility\SafeMarkup;
if (!function_exists('t')) {
function t($string, array $args = []) {
return SafeMarkup::format($string, $args);
}
}
}

View file

@ -0,0 +1,217 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\EventSubscriber\RouteSubscriberTest.
*/
namespace Drupal\Tests\views\Unit\EventSubscriber;
use Drupal\Core\Routing\RouteBuildEvent;
use Drupal\Tests\UnitTestCase;
use Drupal\views\EventSubscriber\RouteSubscriber;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* @coversDefaultClass \Drupal\views\EventSubscriber\RouteSubscriber
* @group views
*/
class RouteSubscriberTest extends UnitTestCase {
/**
* The mocked entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $entityManager;
/**
* The mocked view storage.
*
* @var \Drupal\views\ViewStorage|\PHPUnit_Framework_MockObject_MockObject
*/
protected $viewStorage;
/**
* The tested views route subscriber.
*
* @var \Drupal\views\EventSubscriber\RouteSubscriber|\Drupal\Tests\views\Unit\EventSubscriber\TestRouteSubscriber
*/
protected $routeSubscriber;
/**
* The mocked key value storage.
*
* @var \Drupal\Core\State\StateInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $state;
protected function setUp() {
$this->entityManager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface');
$this->viewStorage = $this->getMockBuilder('Drupal\Core\Config\Entity\ConfigEntityStorage')
->disableOriginalConstructor()
->getMock();
$this->entityManager->expects($this->any())
->method('getStorage')
->with('view')
->will($this->returnValue($this->viewStorage));
$this->state = $this->getMock('\Drupal\Core\State\StateInterface');
$this->routeSubscriber = new TestRouteSubscriber($this->entityManager, $this->state);
}
/**
* @covers ::routeRebuildFinished
*/
public function testRouteRebuildFinished() {
list($view, $executable, $display_1, $display_2) = $this->setupMocks();
$display_1->expects($this->once())
->method('collectRoutes')
->will($this->returnValue(array('test_id.page_1' => 'views.test_id.page_1')));
$display_2->expects($this->once())
->method('collectRoutes')
->will($this->returnValue(array('test_id.page_2' => 'views.test_id.page_2')));
$this->routeSubscriber->routes();
$this->state->expects($this->once())
->method('set')
->with('views.view_route_names', array('test_id.page_1' => 'views.test_id.page_1', 'test_id.page_2' => 'views.test_id.page_2'));
$this->routeSubscriber->routeRebuildFinished();
}
/**
* Tests the onAlterRoutes method.
*
* @see \Drupal\views\EventSubscriber\RouteSubscriber::onAlterRoutes()
*/
public function testOnAlterRoutes() {
$collection = new RouteCollection();
// The first route will be overridden later.
$collection->add('test_route', new Route('test_route', array('_controller' => 'Drupal\Tests\Core\Controller\TestController')));
$route_2 = new Route('test_route/example', array('_controller' => 'Drupal\Tests\Core\Controller\TestController'));
$collection->add('test_route_2', $route_2);
$route_event = new RouteBuildEvent($collection, 'views');
list($view, $executable, $display_1, $display_2) = $this->setupMocks();
// The page_1 display overrides an existing route, so the dynamicRoutes
// should only call the second display.
$display_1->expects($this->once())
->method('collectRoutes')
->willReturnCallback(function() use ($collection) {
$collection->add('views.test_id.page_1', new Route('test_route', ['_controller' => 'Drupal\views\Routing\ViewPageController']));
return ['test_id.page_1' => 'views.test_id.page_1'];
});
$display_1->expects($this->once())
->method('alterRoutes')
->willReturn(['test_id.page_1' => 'test_route']);
$display_2->expects($this->once())
->method('collectRoutes')
->willReturnCallback(function() use ($collection) {
$collection->add('views.test_id.page_2', new Route('test_route', ['_controller' => 'Drupal\views\Routing\ViewPageController']));
return ['test_id.page_2' => 'views.test_id.page_2'];
});
$display_2->expects($this->once())
->method('alterRoutes')
->willReturn([]);
// Ensure that even both the collectRoutes() and alterRoutes() methods
// are called on the displays, we ensure that the route first defined by
// views is dropped.
$this->routeSubscriber->routes();
$this->assertNull($this->routeSubscriber->onAlterRoutes($route_event));
$this->state->expects($this->once())
->method('set')
->with('views.view_route_names', array('test_id.page_1' => 'test_route', 'test_id.page_2' => 'views.test_id.page_2'));
$collection = $route_event->getRouteCollection();
$this->assertEquals(['test_route', 'test_route_2', 'views.test_id.page_2'], array_keys($collection->all()));
$this->routeSubscriber->routeRebuildFinished();
}
/**
* Sets up mocks of Views objects needed for testing.
*
* @return array
* An array of Views mocks, including the executable, the view entity, and
* two display plugins.
*/
protected function setupMocks() {
$executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$view = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->getMock();
$this->viewStorage->expects($this->any())
->method('load')
->will($this->returnValue($view));
$view->expects($this->any())
->method('getExecutable')
->will($this->returnValue($executable));
$view->expects($this->any())
->method('id')
->will($this->returnValue('test_id'));
$executable->storage = $view;
$executable->expects($this->any())
->method('setDisplay')
->will($this->returnValueMap(array(
array('page_1', TRUE),
array('page_2', TRUE),
array('page_3', FALSE),
)));
// Ensure that only the first two displays are actually called.
$display_1 = $this->getMock('Drupal\views\Plugin\views\display\DisplayRouterInterface');
$display_2 = $this->getMock('Drupal\views\Plugin\views\display\DisplayRouterInterface');
$display_collection = $this->getMockBuilder('Drupal\views\DisplayPluginCollection')
->disableOriginalConstructor()
->getMock();
$display_collection->expects($this->any())
->method('get')
->will($this->returnValueMap(array(
array('page_1', $display_1),
array('page_2', $display_2),
)));
$executable->displayHandlers = $display_collection;
$this->routeSubscriber->applicableViews = array();
$this->routeSubscriber->applicableViews[] = array('test_id', 'page_1');
$this->routeSubscriber->applicableViews[] = array('test_id', 'page_2');
$this->routeSubscriber->applicableViews[] = array('test_id', 'page_3');
return array($executable, $view, $display_1, $display_2);
}
}
/**
* Provides a test route subscriber.
*/
class TestRouteSubscriber extends RouteSubscriber {
/**
* The applicable views.
*
* @var array
*/
public $applicableViews;
/**
* {@inheritdoc}
*/
protected function getApplicableViews() {
return $this->applicableViews;
}
}

View file

@ -0,0 +1,192 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\Block\ViewsBlockTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\Block {
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\Block\ViewsBlock;
// @todo Remove this once the constant got converted.
if (!defined('BLOCK_LABEL_VISIBLE')) {
define('BLOCK_LABEL_VISIBLE', 'visible');
}
/**
* @coversDefaultClass \Drupal\views\Plugin\block\ViewsBlock
* @group views
*/
class ViewsBlockTest extends UnitTestCase {
/**
* The view executable.
*
* @var \Drupal\views\ViewExecutable|\PHPUnit_Framework_MockObject_MockObject
*/
protected $executable;
/**
* The view executable factory.
*
* @var \Drupal\views\ViewExecutableFactory|\PHPUnit_Framework_MockObject_MockObject
*/
protected $executableFactory;
/**
* The view entity.
*
* @var \Drupal\views\ViewEntityInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $view;
/**
* The view storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $storage;
/**
* The mocked user account.
*
* @var \Drupal\Core\Session\AccountInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $account;
/**
* The mocked display handler.
*
* @var \Drupal\views\Plugin\views\display\Block|\PHPUnit_Framework_MockObject_MockObject
*/
protected $displayHandler;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp(); // TODO: Change the autogenerated stub
$condition_plugin_manager = $this->getMock('Drupal\Core\Executable\ExecutableManagerInterface');
$condition_plugin_manager->expects($this->any())
->method('getDefinitions')
->will($this->returnValue(array()));
$container = new ContainerBuilder();
$container->set('plugin.manager.condition', $condition_plugin_manager);
\Drupal::setContainer($container);
$this->executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->setMethods(['buildRenderable', 'setDisplay', 'setItemsPerPage'])
->getMock();
$this->executable->expects($this->any())
->method('setDisplay')
->with('block_1')
->will($this->returnValue(TRUE));
$this->executable->expects($this->any())
->method('getShowAdminLinks')
->willReturn(FALSE);
$this->executable->display_handler = $this->getMockBuilder('Drupal\views\Plugin\views\display\Block')
->disableOriginalConstructor()
->setMethods(NULL)
->getMock();
$this->view = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->getMock();
$this->view->expects($this->any())
->method('id')
->willReturn('test_view');
$this->executable->storage = $this->view;
$this->executableFactory = $this->getMockBuilder('Drupal\views\ViewExecutableFactory')
->disableOriginalConstructor()
->getMock();
$this->executableFactory->expects($this->any())
->method('get')
->with($this->view)
->will($this->returnValue($this->executable));
$this->displayHandler = $this->getMockBuilder('Drupal\views\Plugin\views\display\Block')
->disableOriginalConstructor()
->getMock();
$this->displayHandler->expects($this->any())
->method('blockSettings')
->willReturn([]);
$this->displayHandler->expects($this->any())
->method('getPluginId')
->willReturn('block');
$this->executable->display_handler = $this->displayHandler;
$this->storage = $this->getMockBuilder('Drupal\Core\Config\Entity\ConfigEntityStorage')
->disableOriginalConstructor()
->getMock();
$this->storage->expects($this->any())
->method('load')
->with('test_view')
->will($this->returnValue($this->view));
$this->account = $this->getMock('Drupal\Core\Session\AccountInterface');
}
/**
* Tests the build method.
*
* @see \Drupal\views\Plugin\block\ViewsBlock::build()
*/
public function testBuild() {
$output = $this->randomMachineName(100);
$build = array('#markup' => $output, '#view_id' => 'test_view', '#view_display_plugin_class' => '\Drupal\views\Plugin\views\display\Block', '#view_display_show_admin_links' => FALSE, '#view_display_plugin_id' => 'block');
$this->executable->expects($this->once())
->method('buildRenderable')
->with('block_1', [])
->willReturn($build);
$block_id = 'views_block:test_view-block_1';
$config = array();
$definition = array();
$definition['provider'] = 'views';
$plugin = new ViewsBlock($config, $block_id, $definition, $this->executableFactory, $this->storage, $this->account);
$this->assertEquals($build, $plugin->build());
}
/**
* Tests the build method with a failed execution.
*
* @see \Drupal\views\Plugin\block\ViewsBlock::build()
*/
public function testBuildFailed() {
$output = FALSE;
$this->executable->expects($this->once())
->method('buildRenderable')
->with('block_1', [])
->willReturn($output);
$block_id = 'views_block:test_view-block_1';
$config = array();
$definition = array();
$definition['provider'] = 'views';
$plugin = new ViewsBlock($config, $block_id, $definition, $this->executableFactory, $this->storage, $this->account);
$this->assertEquals(array(), $plugin->build());
}
}
}
namespace {
// @todo replace views_add_contextual_links()
if (!function_exists('views_add_contextual_links')) {
function views_add_contextual_links() {
}
}
}

View file

@ -0,0 +1,386 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\Derivative\ViewsLocalTaskTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\Derivative;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\Derivative\ViewsLocalTask;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* @coversDefaultClass \Drupal\views\Plugin\Derivative\ViewsLocalTask
* @group views
*/
class ViewsLocalTaskTest extends UnitTestCase {
/**
* The mocked route provider.
*
* @var \Drupal\Core\Routing\RouteProviderInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $routeProvider;
/**
* The mocked key value storage.
*
* @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $state;
/**
* @var \Drupal\Core\Entity\EntityStorageInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $viewStorage;
protected $baseDefinition = array(
'class' => '\Drupal\views\Plugin\Menu\LocalTask\ViewsLocalTask',
'deriver' => '\Drupal\views\Plugin\Derivative\ViewsLocalTask'
);
/**
* The tested local task derivative class.
*
* @var \Drupal\views\Plugin\Derivative\ViewsLocalTask
*/
protected $localTaskDerivative;
protected function setUp() {
$this->routeProvider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface');
$this->state = $this->getMock('Drupal\Core\State\StateInterface');
$this->viewStorage = $this->getMock('Drupal\Core\Entity\EntityStorageInterface');
$this->localTaskDerivative = new TestViewsLocalTask($this->routeProvider, $this->state, $this->viewStorage);
}
/**
* Tests fetching the derivatives on no view with hook menu.
*
* @see \Drupal\views\Plugin\Derivative\ViewsLocalTask::getDerivativeDefinitions()
*/
public function testGetDerivativeDefinitionsWithoutHookMenuViews() {
$result = array();
$this->localTaskDerivative->setApplicableMenuViews($result);
$definitions = $this->localTaskDerivative->getDerivativeDefinitions($this->baseDefinition);
$this->assertEquals(array(), $definitions);
}
/**
* Tests fetching the derivatives on a view with without a local task.
*/
public function testGetDerivativeDefinitionsWithoutLocalTask() {
$executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$display_plugin = $this->getMockBuilder('Drupal\views\Plugin\views\display\PathPluginBase')
->setMethods(array('getOption'))
->disableOriginalConstructor()
->getMockForAbstractClass();
$display_plugin->expects($this->once())
->method('getOption')
->with('menu')
->will($this->returnValue(array('type' => 'normal')));
$executable->display_handler = $display_plugin;
$storage = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->getMock();
$storage->expects($this->any())
->method('id')
->will($this->returnValue('example_view'));
$storage->expects($this->any())
->method('getExecutable')
->willReturn($executable);
$this->viewStorage->expects($this->any())
->method('load')
->with('example_view')
->willReturn($storage);
$result = [['example_view', 'page_1']];
$this->localTaskDerivative->setApplicableMenuViews($result);
$definitions = $this->localTaskDerivative->getDerivativeDefinitions($this->baseDefinition);
$this->assertEquals(array(), $definitions);
}
/**
* Tests fetching the derivatives on a view with a default local task.
*/
public function testGetDerivativeDefinitionsWithLocalTask() {
$executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$storage = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->getMock();
$storage->expects($this->any())
->method('id')
->will($this->returnValue('example_view'));
$storage->expects($this->any())
->method('getExecutable')
->willReturn($executable);
$executable->storage = $storage;
$this->viewStorage->expects($this->any())
->method('load')
->with('example_view')
->willReturn($storage);
$display_plugin = $this->getMockBuilder('Drupal\views\Plugin\views\display\PathPluginBase')
->setMethods(array('getOption'))
->disableOriginalConstructor()
->getMockForAbstractClass();
$display_plugin->expects($this->once())
->method('getOption')
->with('menu')
->will($this->returnValue(array('type' => 'tab', 'weight' => 12, 'title' => 'Example title')));
$executable->display_handler = $display_plugin;
$result = [['example_view', 'page_1']];
$this->localTaskDerivative->setApplicableMenuViews($result);
// Mock the view route names state.
$view_route_names = array();
$view_route_names['example_view.page_1'] = 'view.example_view.page_1';
$this->state->expects($this->once())
->method('get')
->with('views.view_route_names')
->will($this->returnValue($view_route_names));
$definitions = $this->localTaskDerivative->getDerivativeDefinitions($this->baseDefinition);
$this->assertCount(1, $definitions);
$this->assertEquals('view.example_view.page_1', $definitions['view.example_view.page_1']['route_name']);
$this->assertEquals(12, $definitions['view.example_view.page_1']['weight']);
$this->assertEquals('Example title', $definitions['view.example_view.page_1']['title']);
$this->assertEquals($this->baseDefinition['class'], $definitions['view.example_view.page_1']['class']);
$this->assertTrue(empty($definitions['view.example_view.page_1']['base_route']));
}
/**
* Tests fetching the derivatives on a view which overrides an existing route.
*/
public function testGetDerivativeDefinitionsWithOverrideRoute() {
$executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$storage = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->getMock();
$storage->expects($this->any())
->method('id')
->will($this->returnValue('example_view'));
$storage->expects($this->any())
->method('getExecutable')
->willReturn($executable);
$executable->storage = $storage;
$this->viewStorage->expects($this->any())
->method('load')
->with('example_view')
->willReturn($storage);
$display_plugin = $this->getMockBuilder('Drupal\views\Plugin\views\display\PathPluginBase')
->setMethods(array('getOption'))
->disableOriginalConstructor()
->getMockForAbstractClass();
$display_plugin->expects($this->once())
->method('getOption')
->with('menu')
->will($this->returnValue(array('type' => 'tab', 'weight' => 12)));
$executable->display_handler = $display_plugin;
$result = [['example_view', 'page_1']];
$this->localTaskDerivative->setApplicableMenuViews($result);
// Mock the view route names state.
$view_route_names = array();
// Setup a view which overrides an existing route.
$view_route_names['example_view.page_1'] = 'example_overridden_route';
$this->state->expects($this->once())
->method('get')
->with('views.view_route_names')
->will($this->returnValue($view_route_names));
$definitions = $this->localTaskDerivative->getDerivativeDefinitions($this->baseDefinition);
$this->assertCount(0, $definitions);
}
/**
* Tests fetching the derivatives on a view with a default local task.
*/
public function testGetDerivativeDefinitionsWithDefaultLocalTask() {
$executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$storage = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->getMock();
$storage->expects($this->any())
->method('id')
->will($this->returnValue('example_view'));
$storage->expects($this->any())
->method('getExecutable')
->willReturn($executable);
$executable->storage = $storage;
$this->viewStorage->expects($this->any())
->method('load')
->with('example_view')
->willReturn($storage);
$display_plugin = $this->getMockBuilder('Drupal\views\Plugin\views\display\PathPluginBase')
->setMethods(array('getOption'))
->disableOriginalConstructor()
->getMockForAbstractClass();
$display_plugin->expects($this->exactly(2))
->method('getOption')
->with('menu')
->will($this->returnValue(array('type' => 'default tab', 'weight' => 12, 'title' => 'Example title')));
$executable->display_handler = $display_plugin;
$result = [['example_view', 'page_1']];
$this->localTaskDerivative->setApplicableMenuViews($result);
// Mock the view route names state.
$view_route_names = array();
$view_route_names['example_view.page_1'] = 'view.example_view.page_1';
$this->state->expects($this->exactly(2))
->method('get')
->with('views.view_route_names')
->will($this->returnValue($view_route_names));
$definitions = $this->localTaskDerivative->getDerivativeDefinitions($this->baseDefinition);
$this->assertCount(1, $definitions);
$plugin = $definitions['view.example_view.page_1'];
$this->assertEquals('view.example_view.page_1', $plugin['route_name']);
$this->assertEquals(12, $plugin['weight']);
$this->assertEquals('Example title', $plugin['title']);
$this->assertEquals($this->baseDefinition['class'], $plugin['class']);
$this->assertEquals('view.example_view.page_1', $plugin['base_route']);
// Setup the prefix of the derivative.
$definitions['views_view:view.example_view.page_1'] = $definitions['view.example_view.page_1'];
unset($definitions['view.example_view.page_1']);
$this->localTaskDerivative->alterLocalTasks($definitions);
$plugin = $definitions['views_view:view.example_view.page_1'];
$this->assertCount(1, $definitions);
$this->assertEquals('view.example_view.page_1', $plugin['route_name']);
$this->assertEquals(12, $plugin['weight']);
$this->assertEquals('Example title', $plugin['title']);
$this->assertEquals($this->baseDefinition['class'], $plugin['class']);
$this->assertEquals('view.example_view.page_1', $plugin['base_route']);
}
/**
* Tests fetching the derivatives on a view with a local task and a parent.
*
* The parent is defined by another module, not views.
*/
public function testGetDerivativeDefinitionsWithExistingLocalTask() {
$executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$storage = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->getMock();
$storage->expects($this->any())
->method('id')
->will($this->returnValue('example_view'));
$storage->expects($this->any())
->method('getExecutable')
->willReturn($executable);
$executable->storage = $storage;
$this->viewStorage->expects($this->any())
->method('load')
->with('example_view')
->willReturn($storage);
$display_plugin = $this->getMockBuilder('Drupal\views\Plugin\views\display\PathPluginBase')
->setMethods(array('getOption', 'getPath'))
->disableOriginalConstructor()
->getMockForAbstractClass();
$display_plugin->expects($this->exactly(2))
->method('getOption')
->with('menu')
->will($this->returnValue(array('type' => 'tab', 'weight' => 12, 'title' => 'Example title')));
$display_plugin->expects($this->once())
->method('getPath')
->will($this->returnValue('path/example'));
$executable->display_handler = $display_plugin;
$result = [['example_view', 'page_1']];
$this->localTaskDerivative->setApplicableMenuViews($result);
// Mock the view route names state.
$view_route_names = array();
$view_route_names['example_view.page_1'] = 'view.example_view.page_1';
$this->state->expects($this->exactly(2))
->method('get')
->with('views.view_route_names')
->will($this->returnValue($view_route_names));
// Mock the route provider.
$route_collection = new RouteCollection();
$route_collection->add('test_route', new Route('/path'));
$this->routeProvider->expects($this->any())
->method('getRoutesByPattern')
->with('/path')
->will($this->returnValue($route_collection));
// Setup the existing local task of the test_route.
$definitions['test_route_tab'] = $other_tab = array(
'route_name' => 'test_route',
'title' => 'Test route',
'base_route' => 'test_route',
);
$definitions += $this->localTaskDerivative->getDerivativeDefinitions($this->baseDefinition);
// Setup the prefix of the derivative.
$definitions['views_view:view.example_view.page_1'] = $definitions['view.example_view.page_1'];
unset($definitions['view.example_view.page_1']);
$this->localTaskDerivative->alterLocalTasks($definitions);
$plugin = $definitions['views_view:view.example_view.page_1'];
$this->assertCount(2, $definitions);
// Ensure the other local task was not changed.
$this->assertEquals($other_tab, $definitions['test_route_tab']);
$this->assertEquals('view.example_view.page_1', $plugin['route_name']);
$this->assertEquals(12, $plugin['weight']);
$this->assertEquals('Example title', $plugin['title']);
$this->assertEquals($this->baseDefinition['class'], $plugin['class']);
$this->assertEquals('test_route', $plugin['base_route']);
}
}
/**
* Replaces the applicable views call for easier testability.
*/
class TestViewsLocalTask extends ViewsLocalTask {
/**
* Sets applicable views result.
*/
public function setApplicableMenuViews($result) {
$this->result = $result;
}
/**
* {@inheritdoc}
*/
protected function getApplicableMenuViews() {
return $this->result;
}
}

View file

@ -0,0 +1,101 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\HandlerBaseTest.
*/
namespace Drupal\Tests\views\Unit\Plugin;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\HandlerBase;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\HandlerBase
* @group Views
*/
class HandlerBaseTest extends UnitTestCase {
use HandlerTestTrait;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->setupViewsData();
$this->setupExecutableAndView();
$this->setupDisplay();
}
/**
* @covers ::getEntityType
*/
public function testGetEntityTypeForFieldOnBaseTable() {
$handler = new TestHandler([], 'test_handler', []);
$handler->init($this->executable, $this->display);
$this->view->expects($this->any())
->method('get')
->with('base_table')
->willReturn('test_entity_type_table');
$this->viewsData->expects($this->any())
->method('get')
->with('test_entity_type_table')
->willReturn([
'table' => ['entity type' => 'test_entity_type']
]);
$handler->setViewsData($this->viewsData);
$this->assertEquals('test_entity_type', $handler->getEntityType());
}
/**
* @covers ::getEntityType
*/
public function testGetEntityTypeForFieldWithRelationship() {
$handler = new TestHandler([], 'test_handler', []);
$options = ['relationship' => 'test_relationship'];
$handler->init($this->executable, $this->display, $options);
$this->display->expects($this->atLeastOnce())
->method('getOption')
->with('relationships')
->willReturn(['test_relationship' => ['table' => 'test_entity_type_table', 'id' => 'test_relationship', 'field' => 'test_relationship']]);
$this->view->expects($this->any())
->method('get')
->with('base_table')
->willReturn('test_entity_type_table');
$this->viewsData->expects($this->any())
->method('get')
->willReturnMap([
['test_entity_type_table', [
'table' => ['entity type' => 'test_entity_type'],
'test_relationship' => [
'relationship' => [
'base' => 'test_other_entity_type_table',
'base field' => 'id',
],
],
]],
['test_other_entity_type_table', [
'table' => ['entity type' => 'test_other_entity_type'],
]],
]);
$handler->setViewsData($this->viewsData);
$this->assertEquals('test_other_entity_type', $handler->getEntityType());
}
}
/**
* Allow testing base handler implementation by extending the abstract class.
*/
class TestHandler extends HandlerBase {
}

View file

@ -0,0 +1,74 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\HandlerTestTrait.
*/
namespace Drupal\Tests\views\Unit\Plugin;
/**
* Test trait to mock dependencies of a handler.
*/
trait HandlerTestTrait {
/**
* The mocked view entity.
*
* @var \Drupal\views\Entity\View|\PHPUnit_Framework_MockObject_MockObject
*/
protected $view;
/**
* The mocked view executable.
*
* @var \Drupal\views\ViewExecutable|\PHPUnit_Framework_MockObject_MockObject
*/
protected $executable;
/**
* The mocked views data.
*
* @var \Drupal\views\ViewsData|\PHPUnit_Framework_MockObject_MockObject
*/
protected $viewsData;
/**
* The mocked display.
*
* @var \Drupal\views\Plugin\views\display\DisplayPluginBase|\PHPUnit_Framework_MockObject_MockObject
*/
protected $display;
/**
* Sets up a view executable and a view entity.
*/
protected function setupExecutableAndView() {
$this->view = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->getMock();
$this->executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$this->executable->storage = $this->view;
}
/**
* Sets up a mocked views data object.
*/
protected function setupViewsData() {
$this->viewsData = $this->getMockBuilder('Drupal\views\ViewsData')
->disableOriginalConstructor()
->getMock();
}
/**
* Sets up a mocked display object.
*/
protected function setupDisplay() {
$this->display = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
}
}

View file

@ -0,0 +1,327 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\area\EntityTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\area;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\area\Entity;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\area\Entity
* @group Entity
*/
class EntityTest extends UnitTestCase {
/**
* The tested entity area handler.
*
* @var \Drupal\views\Plugin\views\area\Entity
*/
protected $entityHandler;
/**
* The mocked entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $entityManager;
/**
* The mocked entity storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $entityStorage;
/**
* The mocked entity view builder.
*
* @var \Drupal\Core\Entity\EntityViewBuilderInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $entityViewBuilder;
/**
* The mocked view executable.
*
* @var \Drupal\views\ViewExecutable|\PHPUnit_Framework_MockObject_MockObject
*/
protected $executable;
/**
* The mocked display.
*
* @var \Drupal\views\Plugin\views\display\DisplayPluginBase|\PHPUnit_Framework_MockObject_MockObject
*/
protected $display;
/**
* The mocked style plugin.
*
* @var \Drupal\views\Plugin\views\style\StylePluginBase|\PHPUnit_Framework_MockObject_MockObject
*/
protected $stylePlugin;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->entityManager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface');
$this->entityStorage = $this->getMock('Drupal\Core\Entity\EntityStorageInterface');
$this->entityViewBuilder = $this->getMock('Drupal\Core\Entity\EntityViewBuilderInterface');
$this->executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$this->display = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$this->stylePlugin = $this->getMockBuilder('Drupal\views\Plugin\views\style\StylePluginBase')
->disableOriginalConstructor()
->getMock();
$this->executable->style_plugin = $this->stylePlugin;
$this->entityHandler = new Entity(array(), 'entity', array('entity_type' => 'entity_test'), $this->entityManager);
$this->display->expects($this->any())
->method('getPlugin')
->with('style')
->willReturn($this->stylePlugin);
$this->executable->expects($this->any())
->method('getStyle')
->willReturn($this->stylePlugin);
$token = $this->getMockBuilder('Drupal\Core\Utility\Token')
->disableOriginalConstructor()
->getMock();
$token->expects($this->any())
->method('replace')
->willReturnArgument(0);
$container = new ContainerBuilder();
$container->set('token', $token);
\Drupal::setContainer($container);
}
/**
* Ensures that the entity manager returns an entity storage.
*/
protected function setupEntityManager() {
$this->entityManager->expects($this->any())
->method('getStorage')
->with('entity_test')
->willReturn($this->entityStorage);
$this->entityManager->expects($this->any())
->method('getViewBuilder')
->with('entity_test')
->willReturn($this->entityViewBuilder);
}
/**
* Data provider for testing different types of tokens.
*
* @return array
*/
public function providerTestTokens() {
return [
['!1', 5],
['%2', 6],
['{{ test_render_token }}', 7],
['[test:global_token]', 8],
];
}
/**
* @covers ::render
* @covers ::defineOptions
* @covers ::init
*/
public function testRenderWithId() {
$this->setupEntityManager();
$options = [
'target' => 1,
'tokenize' => FALSE,
];
/** @var \Drupal\Core\Entity\EntityInterface $entity */
$entity = $this->getMock('Drupal\Core\Entity\EntityInterface');
$entity->expects($this->once())
->method('access')
->willReturn(TRUE);
$this->entityStorage->expects($this->never())
->method('loadByProperties');
$this->entityManager->expects($this->any())
->method('loadEntityByConfigTarget')
->willReturn($entity);
$this->entityViewBuilder->expects($this->once())
->method('view')
->with($entity, 'default')
->willReturn(['#markup' => 'hallo']);
$this->entityHandler->init($this->executable, $this->display, $options);
$result = $this->entityHandler->render();
$this->assertEquals(['#markup' => 'hallo'], $result);
}
/**
* @covers ::render
* @covers ::defineOptions
* @covers ::init
*
* @dataProvider providerTestTokens
*/
public function testRenderWithIdAndToken($token, $id) {
$this->setupEntityManager();
$options = [
'target' => $token,
'tokenize' => TRUE,
];
$entity = $this->getMock('Drupal\Core\Entity\EntityInterface');
$entity->expects($this->once())
->method('access')
->willReturn(TRUE);
$this->stylePlugin->expects($this->once())
->method('tokenizeValue')
->with($token, 0)
->willReturn($id);
$this->entityStorage->expects($this->never())
->method('loadByProperties');
$this->entityStorage->expects($this->once())
->method('load')
->with($id)
->willReturn($entity);
$this->entityViewBuilder->expects($this->once())
->method('view')
->with($entity, 'default')
->willReturn(['#markup' => 'hallo']);
$this->entityHandler->init($this->executable, $this->display, $options);
$result = $this->entityHandler->render();
$this->assertEquals(['#markup' => 'hallo'], $result);
}
/**
* @covers ::render
* @covers ::defineOptions
* @covers ::init
*/
public function testRenderWithUuid() {
$this->setupEntityManager();
$uuid = '1d52762e-b9d8-4177-908f-572d1a5845a4';
$options = [
'target' => $uuid,
'tokenize' => FALSE,
];
$entity = $this->getMock('Drupal\Core\Entity\EntityInterface');
$entity->expects($this->once())
->method('access')
->willReturn(TRUE);
$this->entityStorage->expects($this->never())
->method('load');
$this->entityManager->expects($this->once())
->method('loadEntityByConfigTarget')
->willReturn($entity);
$this->entityViewBuilder->expects($this->once())
->method('view')
->with($entity, 'default')
->willReturn(['#markup' => 'hallo']);
$this->entityHandler->init($this->executable, $this->display, $options);
$result = $this->entityHandler->render();
$this->assertEquals(['#markup' => 'hallo'], $result);
}
/**
* @covers ::calculateDependencies
*
* @dataProvider providerTestTokens
*/
public function testCalculateDependenciesWithPlaceholder($token, $id) {
$this->setupEntityManager();
$options = [
'target' => $token,
];
$this->entityHandler->init($this->executable, $this->display, $options);
$this->assertEquals([], $this->entityHandler->calculateDependencies());
}
/**
* @covers ::calculateDependencies
*/
public function testCalculateDependenciesWithUuid() {
$this->setupEntityManager();
$uuid = '1d52762e-b9d8-4177-908f-572d1a5845a4';
$entity = $this->getMock('Drupal\Core\Entity\EntityInterface');
$entity_type = $this->getMock('Drupal\Core\Entity\EntityTypeInterface');
$entity->expects($this->once())
->method('getConfigDependencyName')
->willReturn('entity_test:test-bundle:1d52762e-b9d8-4177-908f-572d1a5845a4');
$this->entityStorage->expects($this->never())
->method('load');
$this->entityManager->expects($this->once())
->method('loadEntityByConfigTarget')
->willReturn($entity);
$entity_type->expects($this->once())
->method('getConfigDependencyKey')
->willReturn('content');
$this->entityManager->expects($this->once())
->method('getDefinition')
->willReturn($entity_type);
$options = [
'target' => $uuid,
];
$this->entityHandler->init($this->executable, $this->display, $options);
$this->assertEquals(['content' => ['entity_test:test-bundle:1d52762e-b9d8-4177-908f-572d1a5845a4']], $this->entityHandler->calculateDependencies());
}
/**
* @covers ::calculateDependencies
*/
public function testCalculateDependenciesWithEntityId() {
$this->setupEntityManager();
$entity = $this->getMock('Drupal\Core\Entity\EntityInterface');
$entity_type = $this->getMock('Drupal\Core\Entity\EntityTypeInterface');
$entity->expects($this->once())
->method('getConfigDependencyName')
->willReturn('entity_test:test-bundle:1d52762e-b9d8-4177-908f-572d1a5845a4');
$this->entityManager->expects($this->once())
->method('loadEntityByConfigTarget')
->willReturn($entity);
$this->entityStorage->expects($this->never())
->method('loadByProperties');
$entity_type->expects($this->once())
->method('getConfigDependencyKey')
->willReturn('content');
$this->entityManager->expects($this->once())
->method('getDefinition')
->willReturn($entity_type);
$options = [
'target' => 1,
];
$this->entityHandler->init($this->executable, $this->display, $options);
$this->assertEquals(['content' => ['entity_test:test-bundle:1d52762e-b9d8-4177-908f-572d1a5845a4']], $this->entityHandler->calculateDependencies());
}
}

View file

@ -0,0 +1,62 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\area\MessagesTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\area;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\area\Messages;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\area\Messages
* @group views
*/
class MessagesTest extends UnitTestCase {
/**
* The view executable object.
*
* @var \Drupal\views\ViewExecutable
*/
protected $view;
/**
* The message handler.
*
* @var \Drupal\views\Plugin\views\area\Messages
*/
protected $messagesHandler;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->messagesHandler = new Messages(array(), 'result', array());
}
/**
* Tests the render method.
*
* @covers ::defineOptions
* @covers ::render
*/
public function testRender() {
// The handler is configured to show with empty views by default, so should
// appear.
$this->assertSame(array('#type' => 'status_messages'), $this->messagesHandler->render());
// Turn empty off, and make sure it isn't rendered.
$this->messagesHandler->options['empty'] = FALSE;
// $empty parameter passed to render will still be FALSE, so should still
// appear.
$this->assertSame(array('#type' => 'status_messages'), $this->messagesHandler->render());
// Should now be empty as both the empty option and parameter are empty.
$this->assertSame(array(), $this->messagesHandler->render(TRUE));
}
}

View file

@ -0,0 +1,141 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\area\ResultTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\area;
use Drupal\Tests\UnitTestCase;
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\area\Result;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\area\Result
* @group views
*/
class ResultTest extends UnitTestCase {
/**
* The view executable object.
*
* @var \Drupal\views\ViewExecutable
*/
protected $view;
/**
* The Result handler.
*
* @var \Drupal\views\Plugin\views\area\Result
*/
protected $resultHandler;
protected function setUp() {
parent::setUp();
$storage = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->setMethods(array('label'))
->getMock();
$storage->expects($this->any())
->method('label')
->will($this->returnValue('ResultTest'));
$user = $this->getMock('Drupal\Core\Session\AccountInterface');
$views_data = $this->getMockBuilder('Drupal\views\ViewsData')
->disableOriginalConstructor()
->getMock();
$route_provider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface');
$this->view = new ViewExecutable($storage, $user, $views_data, $route_provider);
$this->resultHandler = new Result(array(), 'result', array());
$this->resultHandler->view = $this->view;
}
/**
* Tests the query method.
*/
public function testQuery() {
$this->assertNull($this->view->get_total_rows);
// @total should set get_total_rows.
$this->resultHandler->options['content'] = '@total';
$this->resultHandler->query();
$this->assertTrue($this->view->get_total_rows);
// A different token should not.
$this->view->get_total_rows = NULL;
$this->resultHandler->options['content'] = '@current_page';
$this->resultHandler->query();
$this->assertNull($this->view->get_total_rows);
}
/**
* Tests the rendered output of the Result area handler.
*
* @param string $content
* The content to use when rendering the handler.
* @param string $expected
* The expected content string.
* @param int $items_per_page
* The items per page of the configuration.
*
* @dataProvider providerTestResultArea
*/
public function testResultArea($content, $expected, $items_per_page = 0) {
$this->setupViewPager($items_per_page);
$this->resultHandler->options['content'] = $content;
$this->assertEquals(array('#markup' => $expected), $this->resultHandler->render());
}
/**
* Data provider for testResultArea.
*
* @return array
*/
public function providerTestResultArea() {
return array(
array('@label', 'ResultTest'),
array('@start', '1'),
array('@start', '1', 1),
array('@end', '100'),
array('@end', '1', 1),
array('@total', '100'),
array('@total', '100', 1),
array('@per_page', '0'),
array('@per_page', '1', 1),
array('@current_page', '1'),
array('@current_page', '1', 1),
array('@current_record_count', '100'),
array('@current_record_count', '1', 1),
array('@page_count', '1'),
array('@page_count', '100', 1),
array('@start | @end | @total', '1 | 100 | 100'),
array('@start | @end | @total', '1 | 1 | 100', 1),
);
}
/**
* Sets up a mock pager on the view executable object.
*
* @param int $items_per_page
* The value to return from getItemsPerPage().
*/
protected function setupViewPager($items_per_page = 0) {
$pager = $this->getMockBuilder('Drupal\views\Plugin\views\pager\PagerPluginBase')
->disableOriginalConstructor()
->setMethods(array('getItemsPerPage', 'getCurrentPage'))
->getMock();
$pager->expects($this->once())
->method('getItemsPerPage')
->will($this->returnValue($items_per_page));
$pager->expects($this->once())
->method('getCurrentPage')
->will($this->returnValue(0));
$this->view->pager = $pager;
$this->view->style_plugin = new \stdClass();
$this->view->total_rows = 100;
$this->view->result = array(1,2,3,4,5);
}
}

View file

@ -0,0 +1,74 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\area\ViewTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\area;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\area\View as ViewAreaPlugin;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\area\View
* @group views
*/
class ViewTest extends UnitTestCase {
/**
* The mocked entity storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $entityStorage;
/**
* The view handler.
*
* @var \Drupal\views\Plugin\views\area\View
*/
protected $viewHandler;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->entityStorage = $this->getMock('Drupal\Core\Entity\EntityStorageInterface');
$this->viewHandler = new ViewAreaPlugin(array(), 'view', array(), $this->entityStorage);
$this->viewHandler->view = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
}
/**
* @covers ::calculateDependencies
*/
public function testCalculateDependencies() {
/* @var $view_this \Drupal\views\Entity\View */
/* @var $view_other \Drupal\views\Entity\View */
$view_this = $this->getMock('Drupal\views\ViewEntityInterface');
$view_this->expects($this->any())->method('getConfigDependencyKey')->willReturn('config');
$view_this->expects($this->any())->method('getConfigDependencyName')->willReturn('view.this');
$view_this->expects($this->any())->method('id')->willReturn('this');
$view_other = $this->getMock('Drupal\views\ViewEntityInterface');
$view_other->expects($this->any())->method('getConfigDependencyKey')->willReturn('config');
$view_other->expects($this->any())->method('getConfigDependencyName')->willReturn('view.other');
$this->entityStorage->expects($this->any())
->method('load')
->willReturnMap([
['this', $view_this],
['other', $view_other]
]);
$this->viewHandler->view->storage = $view_this;
$this->viewHandler->options['view_to_insert'] = 'other:default';
$this->assertArrayEquals(array('config' => array('view.other')), $this->viewHandler->calculateDependencies());
$this->viewHandler->options['view_to_insert'] = 'this:default';
$this->assertArrayEquals(array(), $this->viewHandler->calculateDependencies());
}
}

View file

@ -0,0 +1,88 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\argument_default\QueryParameterTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\argument_default;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\argument_default\QueryParameter;
use Symfony\Component\HttpFoundation\Request;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\argument_default\QueryParameter
* @group views
*/
class QueryParameterTest extends UnitTestCase {
/**
* Test the getArgument() method.
*
* @covers ::getArgument
* @dataProvider providerGetArgument
*/
public function testGetArgument($options, Request $request, $expected) {
$view = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->setMethods(NULL)
->getMock();
$view->setRequest($request);
$display_plugin = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$raw = new QueryParameter(array(), 'query_parameter', array());
$raw->init($view, $display_plugin, $options);
$this->assertEquals($expected, $raw->getArgument());
}
/**
* Provides data for testGetArgument().
*
* @return array
* An array of test data, with the following entries:
* - first entry: the options for the plugin.
* - second entry: the request object to test with.
* - third entry: the expected default argument value.
*/
public function providerGetArgument() {
$data = array();
$single[] = array(
'query_param' => 'test',
);
$single[] = new Request(array('test' => 'data'));
$single[] = 'data';
$data[] = $single;
$single[] = array(
'query_param' => 'test',
'multiple' => 'AND'
);
$single[] = new Request(array('test' => array('data1', 'data2')));
$single[] = 'data1+data2';
$data[] = $single;
$single[] = array(
'query_param' => 'test',
'multiple' => 'OR'
);
$single[] = new Request(array('test' => array('data1', 'data2')));
$single[] = 'data1,data2';
$data[] = $single;
$single[] = array(
'query_param' => 'test',
'fallback' => 'blub',
);
$single[] = new Request(array());
$single[] = 'blub';
$data[] = $single;
return $data;
}
}

View file

@ -0,0 +1,87 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\argument_default\RawTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\argument_default;
use Drupal\Core\Path\CurrentPathStack;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\argument_default\Raw;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\argument_default\Raw
* @group views
*/
class RawTest extends UnitTestCase {
/**
* Test the getArgument() method.
*
* @see \Drupal\views\Plugin\views\argument_default\Raw::getArgument()
*/
public function testGetArgument() {
$view = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$display_plugin = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$current_path = new CurrentPathStack(new RequestStack());
$request = new Request();
$current_path->setPath('/test/example', $request);
$view->expects($this->any())
->method('getRequest')
->will($this->returnValue($request));
$alias_manager = $this->getMock('Drupal\Core\Path\AliasManagerInterface');
$alias_manager->expects($this->never())
->method('getAliasByPath');
// Don't use aliases.
$raw = new Raw(array(), 'raw', array(), $alias_manager, $current_path);
$options = array(
'use_alias' => FALSE,
'index' => 0,
);
$raw->init($view, $display_plugin, $options);
$this->assertEquals('test', $raw->getArgument());
$raw = new Raw(array(), 'raw', array(), $alias_manager, $current_path);
$options = array(
'use_alias' => FALSE,
'index' => 1,
);
$raw->init($view, $display_plugin, $options);
$this->assertEquals('example', $raw->getArgument());
// Setup an alias manager with a path alias.
$alias_manager = $this->getMock('Drupal\Core\Path\AliasManagerInterface');
$alias_manager->expects($this->any())
->method('getAliasByPath')
->with($this->equalTo('test/example'))
->will($this->returnValue('other/example'));
$raw = new Raw(array(), 'raw', array(), $alias_manager, $current_path);
$options = array(
'use_alias' => TRUE,
'index' => 0,
);
$raw->init($view, $display_plugin, $options);
$this->assertEquals('other', $raw->getArgument());
$raw = new Raw(array(), 'raw', array(), $alias_manager, $current_path);
$options = array(
'use_alias' => TRUE,
'index' => 1,
);
$raw->init($view, $display_plugin, $options);
$this->assertEquals('example', $raw->getArgument());
}
}

View file

@ -0,0 +1,253 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\argument_validator\EntityTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\argument_validator;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\argument_validator\Entity;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\argument_validator\Entity
* @group views
*/
class EntityTest extends UnitTestCase {
/**
* The view executable.
*
* @var \Drupal\views\ViewExecutable
*/
protected $executable;
/**
* The view display.
*
* @var \Drupal\views\Plugin\views\display\DisplayPluginBase
*/
protected $display;
/**
* The entity manager.
*
* @var \PHPUnit_Framework_MockObject_MockObject|\Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* The tested argument validator.
*
* @var \Drupal\views\Plugin\views\argument_validator\Entity
*/
protected $argumentValidator;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->entityManager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface');
$mock_entity = $this->getMockForAbstractClass('Drupal\Core\Entity\Entity', array(), '', FALSE, TRUE, TRUE, array('bundle', 'access'));
$mock_entity->expects($this->any())
->method('bundle')
->will($this->returnValue('test_bundle'));
$mock_entity->expects($this->any())
->method('access')
->will($this->returnValueMap(array(
array('test_op', NULL, FALSE, TRUE),
array('test_op_2', NULL, FALSE, FALSE),
array('test_op_3', NULL, FALSE, TRUE),
)));
$mock_entity_bundle_2 = $this->getMockForAbstractClass('Drupal\Core\Entity\Entity', array(), '', FALSE, TRUE, TRUE, array('bundle', 'access'));
$mock_entity_bundle_2->expects($this->any())
->method('bundle')
->will($this->returnValue('test_bundle_2'));
$mock_entity_bundle_2->expects($this->any())
->method('access')
->will($this->returnValueMap(array(
array('test_op', NULL, FALSE, FALSE),
array('test_op_2', NULL, FALSE, FALSE),
array('test_op_3', NULL, FALSE, TRUE),
)));
$storage = $this->getMock('Drupal\Core\Entity\EntityStorageInterface');
// Setup values for IDs passed as strings or numbers.
$value_map = array(
array(array(), array()),
array(array(1), array(1 => $mock_entity)),
array(array('1'), array(1 => $mock_entity)),
array(array(1, 2), array(1 => $mock_entity, 2 => $mock_entity_bundle_2)),
array(array('1', '2'), array(1 => $mock_entity, 2 => $mock_entity_bundle_2)),
array(array(2), array(2 => $mock_entity_bundle_2)),
array(array('2'), array(2 => $mock_entity_bundle_2)),
);
$storage->expects($this->any())
->method('loadMultiple')
->will($this->returnValueMap($value_map));
$this->entityManager->expects($this->any())
->method('getStorage')
->with('entity_test')
->will($this->returnValue($storage));
$this->executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$this->display = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$definition = array(
'entity_type' => 'entity_test',
);
$this->argumentValidator = new Entity(array(), 'entity_test', $definition, $this->entityManager);
}
/**
* Tests the validate argument method with no access and bundles.
*
* @see \Drupal\views\Plugin\views\argument_validator\Entity::validateArgument()
*/
public function testValidateArgumentNoAccess() {
$options = array();
$options['access'] = FALSE;
$options['bundles'] = array();
$this->argumentValidator->init($this->executable, $this->display, $options);
$this->assertFalse($this->argumentValidator->validateArgument(3));
$this->assertFalse($this->argumentValidator->validateArgument(''));
$this->assertTrue($this->argumentValidator->validateArgument(1));
$this->assertTrue($this->argumentValidator->validateArgument(2));
$this->assertFalse($this->argumentValidator->validateArgument('1,2'));
}
/**
* Tests the validate argument method with access and no bundles.
*
* @see \Drupal\views\Plugin\views\argument_validator\Entity::validateArgument()
*/
public function testValidateArgumentAccess() {
$options = array();
$options['access'] = TRUE;
$options['bundles'] = array();
$options['operation'] = 'test_op';
$this->argumentValidator->init($this->executable, $this->display, $options);
$this->assertFalse($this->argumentValidator->validateArgument(3));
$this->assertFalse($this->argumentValidator->validateArgument(''));
$this->assertTrue($this->argumentValidator->validateArgument(1));
$options = array();
$options['access'] = TRUE;
$options['bundles'] = array();
$options['operation'] = 'test_op_2';
$this->argumentValidator->init($this->executable, $this->display, $options);
$this->assertFalse($this->argumentValidator->validateArgument(3));
$this->assertFalse($this->argumentValidator->validateArgument(''));
$this->assertFalse($this->argumentValidator->validateArgument(1));
$this->assertFalse($this->argumentValidator->validateArgument(2));
}
/**
* Tests the validate argument method with bundle checking.
*/
public function testValidateArgumentBundle() {
$options = array();
$options['access'] = FALSE;
$options['bundles'] = array('test_bundle' => 1);
$this->argumentValidator->init($this->executable, $this->display, $options);
$this->assertTrue($this->argumentValidator->validateArgument(1));
$this->assertFalse($this->argumentValidator->validateArgument(2));
}
/**
* @covers ::calculateDependencies
*/
public function testCalculateDependencies() {
// Create an entity manager, storage, entity type, and entity to mock the
// loading of entities providing bundles.
$entityManager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface');
$storage = $this->getMock('Drupal\Core\Entity\EntityStorageInterface');
$entity_type = $this->getMock('Drupal\Core\Entity\EntityTypeInterface');
$mock_entity = $this->getMock('Drupal\Core\Entity\EntityInterface');
$mock_entity->expects($this->any())
->method('getConfigDependencyKey')
->willReturn('config');
$mock_entity->expects($this->any())
->method('getConfigDependencyName')
->willReturn('test_bundle');
$storage->expects($this->any())
->method('loadMultiple')
->with(['test_bundle'])
->willReturn(['test_bundle' => $mock_entity]);
$entity_type->expects($this->any())
->method('getBundleEntityType')
->willReturn('entity_test_bundle');
$entityManager->expects($this->any())
->method('getDefinition')
->with('entity_test')
->willReturn($entity_type);
$entityManager->expects($this->any())
->method('hasHandler')
->with('entity_test_bundle', 'storage')
->willReturn(TRUE);
$entityManager->expects($this->any())
->method('getStorage')
->with('entity_test_bundle')
->willReturn($storage);
// Set up the argument validator.
$argumentValidator = new Entity(array(), 'entity_test', ['entity_type' => 'entity_test'], $entityManager);
$options = array();
$options['access'] = FALSE;
$options['bundles'] = array('test_bundle' => 1);
$argumentValidator->init($this->executable, $this->display, $options);
$this->assertEquals(['config'=>['test_bundle']], $argumentValidator->calculateDependencies());
}
/**
* Tests the validate argument method with multiple argument splitting.
*/
public function testValidateArgumentMultiple() {
$options = array();
$options['access'] = TRUE;
$options['bundles'] = array();
$options['operation'] = 'test_op';
$options['multiple'] = TRUE;
$this->argumentValidator->init($this->executable, $this->display, $options);
$this->assertTrue($this->argumentValidator->validateArgument('1'));
$this->assertFalse($this->argumentValidator->validateArgument('2'));
$this->assertFalse($this->argumentValidator->validateArgument('1,2'));
$this->assertFalse($this->argumentValidator->validateArgument('1+2'));
$options = array();
$options['access'] = TRUE;
$options['bundles'] = array();
$options['operation'] = 'test_op_3';
$options['multiple'] = TRUE;
$this->argumentValidator->init($this->executable, $this->display, $options);
$this->assertTrue($this->argumentValidator->validateArgument('1,2'));
$this->assertTrue($this->argumentValidator->validateArgument('1+2'));
}
}

View file

@ -0,0 +1,44 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\display\PageTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\display;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\display\Page;
use Symfony\Component\Routing\Route;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\display\Page
* @group views
*/
class PageTest extends UnitTestCase {
/**
* @covers ::buildBasicRenderable
*/
public function testBuildBasicRenderable() {
$route = new Route('/test-view');
$route->setDefault('view_id', 'test_view');
$route->setOption('_view_display_plugin_id', 'page');
$route->setOption('_view_display_show_admin_links', TRUE);
$result = Page::buildBasicRenderable('test_view', 'page_1', [], $route);
$this->assertEquals('test_view', $result['#view_id']);
$this->assertEquals('page', $result['#view_display_plugin_id']);
$this->assertEquals(TRUE, $result['#view_display_show_admin_links']);
}
/**
* @covers ::buildBasicRenderable
* @expectedException \BadFunctionCallException
*/
public function testBuildBasicRenderableWithMissingRoute() {
Page::buildBasicRenderable('test_view', 'page_1', []);
}
}

View file

@ -0,0 +1,445 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\display\PathPluginBaseTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\display;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\display\PathPluginBase
* @group views
*/
class PathPluginBaseTest extends UnitTestCase {
/**
* The route provider that should be used.
*
* @var \Drupal\Core\Routing\RouteProviderInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $routeProvider;
/**
* The tested path plugin base.
*
* @var \Drupal\views\Plugin\views\display\PathPluginBase|\PHPUnit_Framework_MockObject_MockObject
*/
protected $pathPlugin;
/**
* The mocked views access plugin manager.
*
* @var \Drupal\views\Plugin\ViewsPluginManager|\PHPUnit_Framework_MockObject_MockObject
*/
protected $accessPluginManager;
/**
* The mocked key value storage.
*
* @var \Drupal\Core\State\StateInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $state;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->routeProvider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface');
$this->state = $this->getMock('\Drupal\Core\State\StateInterface');
$this->pathPlugin = $this->getMockBuilder('Drupal\views\Plugin\views\display\PathPluginBase')
->setConstructorArgs(array(array(), 'path_base', array(), $this->routeProvider, $this->state))
->setMethods(NULL)
->getMock();
$this->setupContainer();
}
/**
* Setup access plugin manager and config factory in the Drupal class.
*/
public function setupContainer() {
$this->accessPluginManager = $this->getMockBuilder('\Drupal\views\Plugin\ViewsPluginManager')
->disableOriginalConstructor()
->getMock();
$container = new ContainerBuilder();
$container->set('plugin.manager.views.access', $this->accessPluginManager);
$config = array(
'views.settings' => array(
'skip_cache' => TRUE,
'display_extenders' => array(),
),
);
$container->set('config.factory', $this->getConfigFactoryStub($config));
\Drupal::setContainer($container);
}
/**
* Tests the collectRoutes method.
*
* @see \Drupal\views\Plugin\views\display\PathPluginBase::collectRoutes()
*/
public function testCollectRoutes() {
list($view) = $this->setupViewExecutableAccessPlugin();
$display = array();
$display['display_plugin'] = 'page';
$display['id'] = 'page_1';
$display['display_options'] = array(
'path' => 'test_route',
);
$this->pathPlugin->initDisplay($view, $display);
$collection = new RouteCollection();
$result = $this->pathPlugin->collectRoutes($collection);
$this->assertEquals(array('test_id.page_1' => 'view.test_id.page_1'), $result);
$route = $collection->get('view.test_id.page_1');
$this->assertTrue($route instanceof Route);
$this->assertEquals('test_id', $route->getDefault('view_id'));
$this->assertEquals('page_1', $route->getDefault('display_id'));
$this->assertSame(FALSE, $route->getOption('returns_response'));
}
/**
* Tests the collectRoutes method with a display returning a response.
*
* @see \Drupal\views\Plugin\views\display\PathPluginBase::collectRoutes()
*/
public function testCollectRoutesWithDisplayReturnResponse() {
list($view) = $this->setupViewExecutableAccessPlugin();
$display = array();
$display['display_plugin'] = 'page';
$display['id'] = 'page_1';
$display['display_options'] = array(
'path' => 'test_route',
);
$this->pathPlugin = $this->getMockBuilder('Drupal\views\Plugin\views\display\PathPluginBase')
->setConstructorArgs(array(array(), 'path_base', array('returns_response' => TRUE), $this->routeProvider, $this->state))
->setMethods(NULL)
->getMock();
$this->pathPlugin->initDisplay($view, $display);
$collection = new RouteCollection();
$this->pathPlugin->collectRoutes($collection);
$route = $collection->get('view.test_id.page_1');
$this->assertSame(TRUE, $route->getOption('returns_response'));
}
/**
* Tests the collectRoutes method with arguments.
*
* @see \Drupal\views\Plugin\views\display\PathPluginBase::collectRoutes()
*/
public function testCollectRoutesWithArguments() {
list($view) = $this->setupViewExecutableAccessPlugin();
$display = array();
$display['display_plugin'] = 'page';
$display['id'] = 'page_1';
$display['display_options'] = array(
'path' => 'test_route/%/example',
);
$this->pathPlugin->initDisplay($view, $display);
$collection = new RouteCollection();
$result = $this->pathPlugin->collectRoutes($collection);
$this->assertEquals(array('test_id.page_1' => 'view.test_id.page_1'), $result);
$route = $collection->get('view.test_id.page_1');
$this->assertTrue($route instanceof Route);
$this->assertEquals('test_id', $route->getDefault('view_id'));
$this->assertEquals('page_1', $route->getDefault('display_id'));
$this->assertEquals(array('arg_0' => 'arg_0'), $route->getOption('_view_argument_map'));
}
/**
* Tests the collectRoutes method with arguments not specified in the path.
*
* @see \Drupal\views\Plugin\views\display\PathPluginBase::collectRoutes()
*/
public function testCollectRoutesWithArgumentsNotSpecifiedInPath() {
list($view) = $this->setupViewExecutableAccessPlugin();
$display = array();
$display['display_plugin'] = 'page';
$display['id'] = 'page_1';
$display['display_options'] = array(
'path' => 'test_with_arguments',
);
$display['display_options']['arguments'] = array(
'test_id' => array(),
);
$this->pathPlugin->initDisplay($view, $display);
$collection = new RouteCollection();
$result = $this->pathPlugin->collectRoutes($collection);
$this->assertEquals(array('test_id.page_1' => 'view.test_id.page_1'), $result);
$route = $collection->get('view.test_id.page_1');
$this->assertTrue($route instanceof Route);
$this->assertEquals('test_id', $route->getDefault('view_id'));
$this->assertEquals('page_1', $route->getDefault('display_id'));
$this->assertEquals(array('arg_0' => 'arg_0'), $route->getOption('_view_argument_map'));
}
/**
* Tests the collect routes method with an alternative route name in the UI.
*/
public function testCollectRoutesWithSpecialRouteName() {
list($view) = $this->setupViewExecutableAccessPlugin();
$display = array();
$display['display_plugin'] = 'page';
$display['id'] = 'page_1';
$display['display_options'] = array(
'path' => 'test_route',
'route_name' => 'test_route',
);
$this->pathPlugin->initDisplay($view, $display);
$collection = new RouteCollection();
$result = $this->pathPlugin->collectRoutes($collection);
$this->assertEquals(array('test_id.page_1' => 'test_route'), $result);
$route = $collection->get('test_route');
$this->assertTrue($route instanceof Route);
$this->assertEquals('test_id', $route->getDefault('view_id'));
$this->assertEquals('page_1', $route->getDefault('display_id'));
}
/**
* Tests the alter route method.
*/
public function testAlterRoute() {
$collection = new RouteCollection();
$collection->add('test_route', new Route('test_route', array('_controller' => 'Drupal\Tests\Core\Controller\TestController::content')));
$route_2 = new Route('test_route/example', array('_controller' => 'Drupal\Tests\Core\Controller\TestController::content'));
$collection->add('test_route_2', $route_2);
list($view) = $this->setupViewExecutableAccessPlugin();
$display = array();
$display['display_plugin'] = 'page';
$display['id'] = 'page_1';
$display['display_options'] = array(
'path' => 'test_route',
);
$this->pathPlugin->initDisplay($view, $display);
$view_route_names = $this->pathPlugin->alterRoutes($collection);
$this->assertEquals(array('test_id.page_1' => 'test_route'), $view_route_names);
// Ensure that the test_route is overridden.
$route = $collection->get('test_route');
$this->assertTrue($route instanceof Route);
$this->assertEquals('test_id', $route->getDefault('view_id'));
$this->assertEquals('page_1', $route->getDefault('display_id'));
// Ensure that the test_route_2 is not overridden.
$route = $collection->get('test_route_2');
$this->assertTrue($route instanceof Route);
$this->assertFalse($route->hasDefault('view_id'));
$this->assertFalse($route->hasDefault('display_id'));
$this->assertSame($collection->get('test_route_2'), $route_2);
}
/**
* Tests the collectRoutes method with a path containing named parameters.
*
* @see \Drupal\views\Plugin\views\display\PathPluginBase::collectRoutes()
*/
public function testCollectRoutesWithNamedParameters() {
/** @var \Drupal\views\ViewExecutable|\PHPUnit_Framework_MockObject_MockObject $view */
list($view) = $this->setupViewExecutableAccessPlugin();
$view->argument = array();
$view->argument['nid'] = $this->getMockBuilder('Drupal\views\Plugin\views\argument\ArgumentPluginBase')
->disableOriginalConstructor()
->getMock();
$display = array();
$display['display_plugin'] = 'page';
$display['id'] = 'page_1';
$display['display_options'] = array(
'path' => 'test_route/%node/example',
);
$this->pathPlugin->initDisplay($view, $display);
$collection = new RouteCollection();
$result = $this->pathPlugin->collectRoutes($collection);
$this->assertEquals(array('test_id.page_1' => 'view.test_id.page_1'), $result);
$route = $collection->get('view.test_id.page_1');
$this->assertTrue($route instanceof Route);
$this->assertEquals('/test_route/{node}/example', $route->getPath());
$this->assertEquals('test_id', $route->getDefault('view_id'));
$this->assertEquals('page_1', $route->getDefault('display_id'));
$this->assertEquals(array('arg_0' => 'node'), $route->getOption('_view_argument_map'));
}
/**
* Tests altering routes with parameters in the overridden route.
*/
public function testAlterRoutesWithParameters() {
$collection = new RouteCollection();
$collection->add('test_route', new Route('test_route/{parameter}', array('_controller' => 'Drupal\Tests\Core\Controller\TestController::content')));
list($view) = $this->setupViewExecutableAccessPlugin();
// Manually set up an argument handler.
$argument = $this->getMockBuilder('Drupal\views\Plugin\views\argument\ArgumentPluginBase')
->disableOriginalConstructor()
->getMock();
$view->argument['test_id'] = $argument;
$display = array();
$display['display_plugin'] = 'page';
$display['id'] = 'page_1';
$display['display_options'] = array(
'path' => 'test_route/%',
);
$this->pathPlugin->initDisplay($view, $display);
$view_route_names = $this->pathPlugin->alterRoutes($collection);
$this->assertEquals(array('test_id.page_1' => 'test_route'), $view_route_names);
// Ensure that the test_route is overridden.
$route = $collection->get('test_route');
$this->assertInstanceOf('\Symfony\Component\Routing\Route', $route);
$this->assertEquals('test_id', $route->getDefault('view_id'));
$this->assertEquals('page_1', $route->getDefault('display_id'));
// Ensure that the path did not changed and placeholders are respected.
$this->assertEquals('/test_route/{parameter}', $route->getPath());
$this->assertEquals(array('arg_0' => 'parameter'), $route->getOption('_view_argument_map'));
}
/**
* Tests altering routes with parameters and upcasting information
*/
public function testAlterRoutesWithParametersAndUpcasting() {
$collection = new RouteCollection();
$collection->add('test_route', new Route('test_route/{parameter}', ['_controller' => 'Drupal\Tests\Core\Controller\TestController::content'], [], ['parameters' => ['taxonomy_term' => 'entity:entity_test']]));
list($view) = $this->setupViewExecutableAccessPlugin();
// Manually set up an argument handler.
$argument = $this->getMockBuilder('Drupal\views\Plugin\views\argument\ArgumentPluginBase')
->disableOriginalConstructor()
->getMock();
$view->argument['test_id'] = $argument;
$display = array();
$display['display_plugin'] = 'page';
$display['id'] = 'page_1';
$display['display_options'] = [
'path' => 'test_route/%',
];
$this->pathPlugin->initDisplay($view, $display);
$view_route_names = $this->pathPlugin->alterRoutes($collection);
$this->assertEquals(['test_id.page_1' => 'test_route'], $view_route_names);
// Ensure that the test_route is overridden.
$route = $collection->get('test_route');
$this->assertInstanceOf('\Symfony\Component\Routing\Route', $route);
$this->assertEquals('test_id', $route->getDefault('view_id'));
$this->assertEquals('page_1', $route->getDefault('display_id'));
$this->assertEquals(['taxonomy_term' => 'entity:entity_test'], $route->getOption('parameters'));
// Ensure that the path did not changed and placeholders are respected kk.
$this->assertEquals('/test_route/{parameter}', $route->getPath());
$this->assertEquals(['arg_0' => 'parameter'], $route->getOption('_view_argument_map'));
}
/**
* Tests altering routes with optional parameters in the overridden route.
*/
public function testAlterRoutesWithOptionalParameters() {
$collection = new RouteCollection();
$collection->add('test_route', new Route('test_route/{parameter}', array('_controller' => 'Drupal\Tests\Core\Controller\TestController::content')));
list($view) = $this->setupViewExecutableAccessPlugin();
$display = array();
$display['display_plugin'] = 'page';
$display['id'] = 'page_1';
$display['display_options'] = array(
'path' => 'test_route/%',
);
$display['display_options']['arguments'] = array(
'test_id' => array(),
'test_id2' => array(),
);
$this->pathPlugin->initDisplay($view, $display);
$view_route_names = $this->pathPlugin->alterRoutes($collection);
$this->assertEquals(array('test_id.page_1' => 'test_route'), $view_route_names);
// Ensure that the test_route is overridden.
$route = $collection->get('test_route');
$this->assertInstanceOf('\Symfony\Component\Routing\Route', $route);
$this->assertEquals('test_id', $route->getDefault('view_id'));
$this->assertEquals('page_1', $route->getDefault('display_id'));
// Ensure that the path did not changed and placeholders are respected.
$this->assertEquals('/test_route/{parameter}/{arg_1}', $route->getPath());
$this->assertEquals(array('arg_0' => 'parameter'), $route->getOption('_view_argument_map'));
}
/**
* Tests the getRouteName method.
*/
public function testGetRouteName() {
list($view) = $this->setupViewExecutableAccessPlugin();
$display = array();
$display['display_plugin'] = 'page';
$display['id'] = 'page_1';
$display['display_options'] = array(
'path' => 'test_route',
);
$this->pathPlugin->initDisplay($view, $display);
$route_name = $this->pathPlugin->getRouteName();
// Ensure that the expected routename is returned.
$this->assertEquals('view.test_id.page_1', $route_name);
}
/**
* Returns some mocked view entity, view executable, and access plugin.
*/
protected function setupViewExecutableAccessPlugin() {
$view_entity = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->getMock();
$view_entity->expects($this->any())
->method('id')
->will($this->returnValue('test_id'));
$view = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$view->storage = $view_entity;
// Skip views options caching.
$view->editing = TRUE;
$access_plugin = $this->getMockBuilder('Drupal\views\Plugin\views\access\AccessPluginBase')
->disableOriginalConstructor()
->getMockForAbstractClass();
$this->accessPluginManager->expects($this->any())
->method('createInstance')
->will($this->returnValue($access_plugin));
return array($view, $view_entity, $access_plugin);
}
}

View file

@ -0,0 +1,262 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\field\CounterTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\field;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Entity\View;
use Drupal\views\Plugin\views\field\Counter;
use Drupal\views\ResultRow;
use Drupal\views\Tests\ViewTestData;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\field\Counter
* @group views
*/
class CounterTest extends UnitTestCase {
/**
* The pager plugin instance.
*
* @var \Drupal\views\Plugin\views\pager\PagerPluginBase
*/
protected $pager;
/**
* The view executable.
*
* @var \Drupal\views\ViewExecutable
*/
protected $view;
/**
* The display plugin instance.
*
* @var \Drupal\views\Plugin\views\display\DisplayPluginBase
*/
protected $display;
/**
* Stores the test data.
*
* @var array
*/
protected $testData = array();
/**
* The handler definition of the counter field.
*
* @return array
*/
protected $definition;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Setup basic stuff like the view and the display.
$config = array();
$config['display']['default'] = array(
'id' => 'default',
'display_plugin' => 'default',
'display_title' => 'Default',
);
$storage = new View($config, 'view');
$user = $this->getMock('Drupal\Core\Session\AccountInterface');
$views_data = $this->getMockBuilder('Drupal\views\ViewsData')
->disableOriginalConstructor()
->getMock();
$route_provider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface');
$this->view = $this->getMock('Drupal\views\ViewExecutable', NULL, array($storage, $user, $views_data, $route_provider));
$this->display = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$this->pager = $this->getMockBuilder('Drupal\views\Plugin\views\pager\Full')
->disableOriginalConstructor()
->setMethods(NULL)
->getMock();
$this->view->display_handler = $this->display;
$this->view->pager = $this->pager;
foreach (ViewTestData::dataSet() as $index => $set) {
$this->testData[] = new ResultRow($set + ['index' => $index]);
}
$this->definition = array('title' => 'counter field', 'plugin_type' => 'field');
}
/**
* Provides some row index to test.
*
* @return array
* Returns an array of row index to test.
*/
public function providerRowIndexes() {
return array(
array(0),
array(1),
array(2),
);
}
/**
* Tests a simple counter field.
*
* @dataProvider providerRowIndexes
*/
public function testSimpleCounter($i) {
$counter_handler = new Counter(array(), 'counter', $this->definition);
$options = array();
$counter_handler->init($this->view, $this->display, $options);
$this->view->row_index = $i;
$expected = $i + 1;
$counter = $counter_handler->getValue($this->testData[$i]);
$this->assertEquals($expected, $counter, SafeMarkup::format('The expected number (@expected) patches with the rendered number (@counter) failed', array(
'@expected' => $expected,
'@counter' => $counter
)));
$counter = $this->renderCounter($counter_handler, $this->testData[$i]);
$this->assertEquals($expected, $counter, SafeMarkup::format('The expected number (@expected) patches with the rendered number (@counter) failed', array(
'@expected' => $expected,
'@counter' => $counter
)));
}
/**
* Tests a counter with a random start.
*
* @param int $i
* The row index to test.
*
* @dataProvider providerRowIndexes
*/
public function testCounterRandomStart($i) {
// Setup a counter field with a random start.
$rand_start = rand(5, 10);
$counter_handler = new Counter(array(), 'counter', $this->definition);
$options = array(
'counter_start' => $rand_start,
);
$counter_handler->init($this->view, $this->display, $options);
$this->view->row_index = $i;
$expected = $rand_start + $i;
$counter = $counter_handler->getValue($this->testData[$i]);
$this->assertEquals($expected, $counter, SafeMarkup::format('The expected number (@expected) patches with the rendered number (@counter) failed', array(
'@expected' => $expected,
'@counter' => $counter
)));
$counter = $this->renderCounter($counter_handler, $this->testData[$i]);
$this->assertEquals($expected, $counter, SafeMarkup::format('The expected number (@expected) patches with the rendered number (@counter) failed', array(
'@expected' => $expected,
'@counter' => $counter
)));
}
/**
* Tests a counter field with a random pager offset.
*
* @param int $i
* The row index to test.
*
* @dataProvider providerRowIndexes
*/
public function testCounterRandomPagerOffset($i) {
// Setup a counter field with a pager with a random offset.
$offset = 3;
$this->pager->setOffset($offset);
$rand_start = rand(5, 10);
$counter_handler = new Counter(array(), 'counter', $this->definition);
$options = array(
'counter_start' => $rand_start,
);
$counter_handler->init($this->view, $this->display, $options);
$this->view->row_index = $i;
$expected = $offset + $rand_start + $i;
$counter = $counter_handler->getValue($this->testData[$i]);
$this->assertEquals($expected, $counter, SafeMarkup::format('The expected number (@expected) patches with the rendered number (@counter) failed', array(
'@expected' => $expected,
'@counter' => $counter
)));
$counter = $this->renderCounter($counter_handler, $this->testData[$i]);
$this->assertEquals($expected, $counter, SafeMarkup::format('The expected number (@expected) patches with the rendered number (@counter) failed', array(
'@expected' => $expected,
'@counter' => $counter
)));
}
/**
* Tests a counter field on the second page.
*
* @param int $i
* The row index to test.
*
* @dataProvider providerRowIndexes
*/
public function testCounterSecondPage($i) {
$offset = 3;
// Setup a pager on the second page.
$this->pager->setOffset($offset);
$items_per_page = 5;
$this->pager->setItemsPerPage($items_per_page);
$current_page = 1;
$this->pager->setCurrentPage($current_page);
$rand_start = rand(5, 10);
$counter_handler = new Counter(array(), 'counter', $this->definition);
$options = array(
'counter_start' => $rand_start,
);
$counter_handler->init($this->view, $this->display, $options);
$this->view->row_index = $i;
$expected = $items_per_page + $offset + $rand_start + $i;
$counter = $counter_handler->getValue($this->testData[$i]);
$this->assertEquals($expected, $counter, SafeMarkup::format('The expected number (@expected) patches with the rendered number (@counter) failed', array(
'@expected' => $expected,
'@counter' => $counter
)));
$counter = $this->renderCounter($counter_handler, $this->testData[$i]);
$this->assertEquals($expected, $counter, SafeMarkup::format('The expected number (@expected) patches with the rendered number (@counter) failed', array(
'@expected' => $expected,
'@counter' => $counter
)));
}
/**
* Renders the counter field handler.
*
* @param \Drupal\views\Plugin\views\field\Counter $handler
* The counter handler.
* @param \Drupal\views\ResultRow $row
* A result row.
*
* @return string
* The counter rendered markup.
*/
protected function renderCounter(Counter $handler, ResultRow $row) {
$markup = $handler->render($row);
$handler->postRender($row, $markup);
return $handler->last_render;
}
}

View file

@ -0,0 +1,515 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\field\FieldPluginBaseTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\field;
use Drupal\Core\Language\Language;
use Drupal\Core\Url;
use Drupal\Core\Utility\LinkGenerator;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Drupal\Core\Utility\UnroutedUrlAssembler;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Route;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\field\FieldPluginBase
* @group views
*/
class FieldPluginBaseTest extends UnitTestCase {
/**
* The configuration of the plugin under test.
*
* @var array
*/
protected $configuration = [];
/**
* The ID plugin of the plugin under test.
*
* @var string
*/
protected $pluginId = 'field_test';
/**
* The definition of the plugin under test.
*
* @var array
*/
protected $pluginDefinition = [];
/**
* Default configuration for URL output.
*
* @var array
*/
protected $defaultUrlOptions = [
'absolute' => FALSE,
'alias' => FALSE,
'entity' => NULL,
'entity_type' => NULL,
'language' => NULL,
'query' => [],
'set_active_class' => FALSE,
];
/**
* The mocked link generator.
*
* @var \Drupal\Core\Utility\LinkGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $linkGenerator;
/**
* The mocked view executable.
*
* @var \Drupal\views\ViewExecutable|\PHPUnit_Framework_MockObject_MockObject
*/
protected $executable;
/**
* The mocked display plugin instance.
*
* @var \Drupal\views\Plugin\views\display\DisplayPluginBase|\PHPUnit_Framework_MockObject_MockObject
*/
protected $display;
/**
* The mocked url generator.
*
* @var \Drupal\Core\Routing\UrlGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $urlGenerator;
/**
* The mocked path validator.
*
* @var \Drupal\Core\Path\PathValidatorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $pathValidator;
/**
* The unrouted url assembler service.
*
* @var \Drupal\Core\Utility\UnroutedUrlAssemblerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $unroutedUrlAssembler;
/**
* The request stack.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* The mocked path processor.
*
* @var \Drupal\Core\PathProcessor\OutboundPathProcessorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $pathProcessor;
/**
* The mocked path renderer.
*
* @var \Drupal\Core\Render\RendererInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $renderer;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$this->display = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$route_provider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface');
$route_provider->expects($this->any())
->method('getRouteByName')
->with('test_route')
->willReturn(new Route('/test-path'));
$this->urlGenerator = $this->getMock('Drupal\Core\Routing\UrlGeneratorInterface');
$this->pathValidator = $this->getMock('Drupal\Core\Path\PathValidatorInterface');
$this->requestStack = new RequestStack();
$this->requestStack->push(new Request());
$this->unroutedUrlAssembler = $this->getMock('Drupal\Core\Utility\UnroutedUrlAssemblerInterface');
$this->linkGenerator = $this->getMock('Drupal\Core\Utility\LinkGeneratorInterface');
$this->renderer = $this->getMock('Drupal\Core\Render\RendererInterface');
$container_builder = new ContainerBuilder();
$container_builder->set('url_generator', $this->urlGenerator);
$container_builder->set('path.validator', $this->pathValidator);
$container_builder->set('unrouted_url_assembler', $this->unroutedUrlAssembler);
$container_builder->set('request_stack', $this->requestStack);
$container_builder->set('renderer', $this->renderer);
\Drupal::setContainer($container_builder);
}
/**
* Sets up the unrouted url assembler and the link generator.
*/
protected function setUpUrlIntegrationServices() {
$config = $this->getMockBuilder('Drupal\Core\Config\ImmutableConfig')
->disableOriginalConstructor()
->getMock();
$config_factory = $this->getMock('\Drupal\Core\Config\ConfigFactoryInterface');
$config_factory->expects($this->any())
->method('get')
->willReturn($config);
$this->pathProcessor = $this->getMock('Drupal\Core\PathProcessor\OutboundPathProcessorInterface');
$this->unroutedUrlAssembler = new UnroutedUrlAssembler($this->requestStack, $config_factory, $this->pathProcessor);
\Drupal::getContainer()->set('unrouted_url_assembler', $this->unroutedUrlAssembler);
$this->linkGenerator = new LinkGenerator($this->urlGenerator, $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface'));
}
/**
* Sets up a display with empty arguments and fields.
*/
protected function setupDisplayWithEmptyArgumentsAndFields() {
$this->display->expects($this->any())
->method('getHandlers')
->willReturnMap([
['argument', []],
['field', []],
]);
}
/**
* Test rendering as a link without a path.
*
* @covers ::renderAsLink
*/
public function testRenderAsLinkWithoutPath() {
$alter = [
'make_link' => TRUE,
];
$this->setUpUrlIntegrationServices();
$field = $this->setupTestField(['alter' => $alter]);
$field->field_alias = 'key';
$row = new ResultRow(['key' => 'value']);
$expected_result = 'value';
$result = $field->advancedRender($row);
$this->assertEquals($expected_result, $result);
}
/**
* Test rendering of a link with a path and options.
*
* @dataProvider providerTestRenderAsLinkWithPathAndOptions
* @covers ::renderAsLink
*/
public function testRenderAsLinkWithPathAndOptions($path, $alter, $link_html, $final_html = NULL) {
$alter += [
'make_link' => TRUE,
'path' => $path,
];
$final_html = isset($final_html) ? $final_html : $link_html;
$this->setUpUrlIntegrationServices();
$this->setupDisplayWithEmptyArgumentsAndFields();
$field = $this->setupTestField(['alter' => $alter]);
$field->field_alias = 'key';
$row = new ResultRow(['key' => 'value']);
$result = $field->advancedRender($row);
$this->assertEquals($final_html, $result);
}
/**
* Data provider for ::testRenderAsLinkWithPathAndOptions().
*
* @return array
* Test data.
*/
public function providerTestRenderAsLinkWithPathAndOptions() {
$data = [];
// Simple path with default options.
$data[] = ['test-path', [], [], '<a href="/test-path">value</a>'];
// Add a fragment.
$data[] = ['test-path', ['fragment' => 'test'], '<a href="/test-path#test">value</a>'];
// Rel attributes.
$data[] = ['test-path', ['rel' => 'up'], '<a href="/test-path" rel="up">value</a>'];
// Target attributes.
$data[] = ['test-path', ['target' => '_blank'], '<a href="/test-path" target="_blank">value</a>'];
// Link attributes.
$data[] = ['test-path', ['link_attributes' => ['foo' => 'bar']], '<a href="/test-path" foo="bar">value</a>'];
// Manual specified query.
$data[] = ['test-path', ['query' => ['foo' => 'bar']], '<a href="/test-path?foo=bar">value</a>'];
// Query specified as part of the path.
$data[] = ['test-path?foo=bar', [], '<a href="/test-path?foo=bar">value</a>'];
// Query specified as option and path.
// @todo Do we expect that options override all existing ones?
$data[] = ['test-path?foo=bar', ['query' => ['key' => 'value']], '<a href="/test-path?key=value">value</a>'];
// Alias flag.
$data[] = ['test-path', ['alias' => TRUE], '<a href="/test-path">value</a>'];
// Note: In contrast to the testRenderAsLinkWithUrlAndOptions test we don't
// test the language, because the path processor for the language won't be
// executed for paths which aren't routed.
// Entity flag.
$entity = $this->getMock('Drupal\Core\Entity\EntityInterface');
$data[] = ['test-path', ['entity' => $entity], '<a href="/test-path">value</a>'];
// entity_type flag.
$entity_type_id = 'node';
$data[] = ['test-path', ['entity_type' => $entity_type_id], '<a href="/test-path">value</a>'];
// prefix
$data[] = ['test-path', ['prefix' => 'test_prefix'], '<a href="/test-path">value</a>', 'test_prefix<a href="/test-path">value</a>'];
// suffix.
$data[] = ['test-path', ['suffix' => 'test_suffix'], '<a href="/test-path">value</a>', '<a href="/test-path">value</a>test_suffix'];
// External URL.
$data[] = ['https://www.drupal.org', [], [], '<a href="https://www.drupal.org">value</a>'];
return $data;
}
/**
* Tests link rendering with a URL and options.
*
* @dataProvider providerTestRenderAsLinkWithUrlAndOptions
* @covers ::renderAsLink
*/
public function testRenderAsLinkWithUrlAndOptions(Url $url, $alter, Url $expected_url, $url_path, Url $expected_link_url, $link_html, $final_html = NULL) {
$alter += [
'make_link' => TRUE,
'url' => $url,
];
$final_html = isset($final_html) ? $final_html : $link_html;
$this->setUpUrlIntegrationServices();
$this->setupDisplayWithEmptyArgumentsAndFields();
$field = $this->setupTestField(['alter' => $alter]);
$field->field_alias = 'key';
$row = new ResultRow(['key' => 'value']);
$expected_url->setOptions($expected_url->getOptions() + $this->defaultUrlOptions);
$expected_link_url->setUrlGenerator($this->urlGenerator);
$expected_url_options = $expected_url->getOptions();
unset($expected_url_options['attributes']);
$this->urlGenerator->expects($this->once())
->method('generateFromRoute')
->with($expected_url->getRouteName(), $expected_url->getRouteParameters(), $expected_url_options)
->willReturn($url_path);
$result = $field->advancedRender($row);
$this->assertEquals($final_html, $result);
}
/**
* Data provider for ::testRenderAsLinkWithUrlAndOptions().
*
* @return array
* Array of test data.
*/
public function providerTestRenderAsLinkWithUrlAndOptions() {
$data = [];
// Simple path with default options.
$url = Url::fromRoute('test_route');
$data[]= [$url, [], clone $url, '/test-path', clone $url, '<a href="/test-path">value</a>'];
// Simple url with parameters.
$url_parameters = Url::fromRoute('test_route', ['key' => 'value']);
$data[]= [$url_parameters, [], clone $url_parameters, '/test-path/value', clone $url_parameters, '<a href="/test-path/value">value</a>'];
// Add a fragment.
$url = Url::fromRoute('test_route');
$url_with_fragment = Url::fromRoute('test_route');
$options = ['fragment' => 'test'] + $this->defaultUrlOptions;
$url_with_fragment->setOptions($options);
$data[]= [$url, ['fragment' => 'test'], $url_with_fragment, '/test-path#test', clone $url_with_fragment, '<a href="/test-path#test">value</a>'];
// Rel attributes.
$url = Url::fromRoute('test_route');
$url_with_rel = Url::fromRoute('test_route');
$options = ['attributes' => ['rel' => 'up']] + $this->defaultUrlOptions;
$url_with_rel->setOptions($options);
$data[]= [$url, ['rel' => 'up'], clone $url, '/test-path', $url_with_rel, '<a href="/test-path" rel="up">value</a>'];
// Target attributes.
$url = Url::fromRoute('test_route');
$url_with_target = Url::fromRoute('test_route');
$options = ['attributes' => ['target' => '_blank']] + $this->defaultUrlOptions;
$url_with_target->setOptions($options);
$data[]= [$url, ['target' => '_blank'], $url_with_target, '/test-path', clone $url_with_target, '<a href="/test-path" target="_blank">value</a>'];
// Link attributes.
$url = Url::fromRoute('test_route');
$url_with_link_attributes = Url::fromRoute('test_route');
$options = ['attributes' => ['foo' => 'bar']] + $this->defaultUrlOptions;
$url_with_link_attributes->setOptions($options);
$data[]= [$url, ['link_attributes' => ['foo' => 'bar']], clone $url, '/test-path', $url_with_link_attributes, '<a href="/test-path" foo="bar">value</a>'];
// Manual specified query.
$url = Url::fromRoute('test_route');
$url_with_query = Url::fromRoute('test_route');
$options = ['query' => ['foo' => 'bar']] + $this->defaultUrlOptions;
$url_with_query->setOptions($options);
$data[]= [$url, ['query' => ['foo' => 'bar']], clone $url_with_query, '/test-path?foo=bar', $url_with_query, '<a href="/test-path?foo=bar">value</a>'];
// Query specified as part of the path.
$url = Url::fromRoute('test_route')->setOption('query', ['foo' => 'bar']);
$url_with_query = clone $url;
$url_with_query->setOptions(['query' => ['foo' => 'bar']] + $url_with_query->getOptions());
$data[] = [$url, [], $url_with_query, '/test-path?foo=bar', clone $url, '<a href="/test-path?foo=bar">value</a>'];
// Query specified as option and path.
$url = Url::fromRoute('test_route')->setOption('query', ['foo' => 'bar']);
$url_with_query = Url::fromRoute('test_route');
$options = ['query' => ['key' => 'value']] + $this->defaultUrlOptions;
$url_with_query->setOptions($options);
$data[] = [$url, ['query' => ['key' => 'value']], $url_with_query, '/test-path?key=value', clone $url_with_query, '<a href="/test-path?key=value">value</a>'];
// Alias flag.
$url = Url::fromRoute('test_route');
$url_without_alias = Url::fromRoute('test_route');
$options = ['alias' => TRUE] + $this->defaultUrlOptions;
$url_without_alias->setOptions($options);
$data[] = [$url, ['alias' => TRUE], $url_without_alias, '/test-path', clone $url_without_alias, '<a href="/test-path">value</a>'];
// Language flag.
$language = new Language(['id' => 'fr']);
$url = Url::fromRoute('test_route');
$url_with_language = Url::fromRoute('test_route');
$options = ['language' => $language] + $this->defaultUrlOptions;
$url_with_language->setOptions($options);
$data[] = [$url, ['language' => $language], $url_with_language, '/fr/test-path', clone $url_with_language, '<a href="/fr/test-path" hreflang="fr">value</a>'];
// Entity flag.
$entity = $this->getMock('Drupal\Core\Entity\EntityInterface');
$url = Url::fromRoute('test_route');
$url_with_entity = Url::fromRoute('test_route');
$options = ['entity' => $entity] + $this->defaultUrlOptions;
$url_with_entity->setOptions($options);
$data[] = [$url, ['entity' => $entity], $url_with_entity, '/test-path', clone $url_with_entity, '<a href="/test-path">value</a>'];
// Test entity_type flag.
$entity_type_id = 'node';
$url = Url::fromRoute('test_route');
$url_with_entity_type = Url::fromRoute('test_route');
$options = ['entity_type' => $entity_type_id] + $this->defaultUrlOptions;
$url_with_entity_type->setOptions($options);
$data[] = [$url, ['entity_type' => $entity_type_id], $url_with_entity_type, '/test-path', clone $url_with_entity_type, '<a href="/test-path">value</a>'];
// Test prefix.
$url = Url::fromRoute('test_route');
$data[] = [$url, ['prefix' => 'test_prefix'], clone $url, '/test-path', clone $url, '<a href="/test-path">value</a>', 'test_prefix<a href="/test-path">value</a>'];
// Test suffix.
$url = Url::fromRoute('test_route');
$data[] = [$url, ['suffix' => 'test_suffix'], clone $url, '/test-path', clone $url, '<a href="/test-path">value</a>', '<a href="/test-path">value</a>test_suffix'];
return $data;
}
/**
* Test rendering of a link with a path and options.
*
* @dataProvider providerTestRenderAsLinkWithPathAndTokens
* @covers ::renderAsLink
*/
public function testRenderAsLinkWithPathAndTokens($path, $tokens, $link_html) {
$alter = [
'make_link' => TRUE,
'path' => $path,
];
$this->setUpUrlIntegrationServices();
$this->setupDisplayWithEmptyArgumentsAndFields();
$this->executable->build_info['substitutions'] = $tokens;
$field = $this->setupTestField(['alter' => $alter]);
$field->field_alias = 'key';
$row = new ResultRow(['key' => 'value']);
$build =[
'#type' => 'inline_template',
'#template' => 'base:test-path/' . explode('/', $path)[1],
'#context' => ['foo' => 123],
];
$this->renderer->expects($this->once())
->method('render')
->with($build, FALSE)
->willReturn('base:test-path/123');
$result = $field->advancedRender($row);
$this->assertEquals($link_html, $result);
}
/**
* Data provider for ::testRenderAsLinkWithPathAndTokens().
*
* @return array
* Test data.
*/
public function providerTestRenderAsLinkWithPathAndTokens() {
$tokens = ['{{ foo }}' => 123];
$link_html = '<a href="/test-path/123">value</a>';
$data = [];
$data[] = ['test-path/{{foo}}', $tokens, $link_html];
$data[] = ['test-path/{{ foo}}', $tokens, $link_html];
$data[] = ['test-path/{{ foo}}', $tokens, $link_html];
$data[] = ['test-path/{{foo }}', $tokens, $link_html];
$data[] = ['test-path/{{foo }}', $tokens, $link_html];
$data[] = ['test-path/{{ foo }}', $tokens, $link_html];
$data[] = ['test-path/{{ foo }}', $tokens, $link_html];
$data[] = ['test-path/{{ foo }}', $tokens, $link_html];
$data[] = ['test-path/{{ foo }}', $tokens, $link_html];
return $data;
}
/**
* Sets up a test field.
*
* @return \Drupal\Tests\views\Unit\Plugin\field\FieldPluginBaseTestField|\PHPUnit_Framework_MockObject_MockObject
* The test field.
*/
protected function setupTestField(array $options = []) {
/** @var \Drupal\Tests\views\Unit\Plugin\field\FieldPluginBaseTestField $field */
$field = $this->getMock('Drupal\Tests\views\Unit\Plugin\field\FieldPluginBaseTestField', ['l'], [$this->configuration, $this->pluginId, $this->pluginDefinition]);
$field->init($this->executable, $this->display, $options);
$field->setLinkGenerator($this->linkGenerator);
return $field;
}
}
class FieldPluginBaseTestField extends FieldPluginBase {
public function setLinkGenerator(LinkGeneratorInterface $link_generator) {
$this->linkGenerator = $link_generator;
}
}

View file

@ -0,0 +1,733 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\field\FieldTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\field;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Tests\UnitTestCase;
use Drupal\Tests\views\Unit\Plugin\HandlerTestTrait;
use Drupal\views\Plugin\views\field\Field;
use Drupal\views\ResultRow;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\field\Field
* @group views
*/
class FieldTest extends UnitTestCase {
use HandlerTestTrait;
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $entityManager;
/**
* The mocked formatter plugin manager.
*
* @var \Drupal\Core\Field\FormatterPluginManager|\PHPUnit_Framework_MockObject_MockObject
*/
protected $formatterPluginManager;
/**
* The mocked language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $languageManager;
/**
* The mocked field type plugin manager.
*
* @var \Drupal\Core\Field\FieldTypePluginManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $fieldTypePluginManager;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $renderer;
/**
* The container.
*
* @var \Drupal\Core\DependencyInjection\Container
*/
protected $container;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->entityManager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface');
$this->formatterPluginManager = $this->getMockBuilder('Drupal\Core\Field\FormatterPluginManager')
->disableOriginalConstructor()
->getMock();
$this->fieldTypePluginManager = $this->getMock('Drupal\Core\Field\FieldTypePluginManagerInterface');
$this->fieldTypePluginManager->expects($this->any())
->method('getDefaultStorageSettings')
->willReturn([]);
$this->fieldTypePluginManager->expects($this->any())
->method('getDefaultFieldSettings')
->willReturn([]);
$this->languageManager = $this->getMock('Drupal\Core\Language\LanguageManagerInterface');
$this->renderer = $this->getMock('Drupal\Core\Render\RendererInterface');
$this->setupExecutableAndView();
$this->setupViewsData();
$this->display = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$this->container = new ContainerBuilder();
$this->container->set('plugin.manager.field.field_type', $this->fieldTypePluginManager);
\Drupal::setContainer($this->container);
}
/**
* @covers ::__construct
*/
public function testConstruct() {
$definition = [
'entity_type' => 'test_entity',
// Just provide 'entity field' as definition. This is how EntityViewsData
// provides it.
'entity field' => 'title',
];
$handler = new Field([], 'field', $definition, $this->entityManager, $this->formatterPluginManager, $this->fieldTypePluginManager, $this->languageManager, $this->renderer);
$this->assertEquals('title', $handler->definition['field_name']);
}
/**
* @covers ::defineOptions
*/
public function testDefineOptionsWithNoOptions() {
$definition = [
'entity_type' => 'test_entity',
'field_name' => 'title'
];
$handler = new Field([], 'field', $definition, $this->entityManager, $this->formatterPluginManager, $this->fieldTypePluginManager, $this->languageManager, $this->renderer);
// Setup the entity manager to allow fetching the storage definitions.
$title_storage = $this->getBaseFieldStorage();
$this->entityManager->expects($this->atLeastOnce())
->method('getFieldStorageDefinitions')
->with('test_entity')
->willReturn([
'title' => $title_storage,
]);
$options = [];
$handler->init($this->executable, $this->display, $options);
$this->assertEquals('value', $handler->options['group_column']);
$this->assertEquals(0, $handler->options['delta_limit']);
}
/**
* @covers ::defineOptions
*/
public function testDefineOptionsWithDefaultFormatterOnFieldDefinition() {
$definition = [
'entity_type' => 'test_entity',
'field_name' => 'title',
'default_formatter' => 'test_example',
'default_formatter_settings' => ['link_to_entity' => TRUE]
];
$handler = new Field([], 'field', $definition, $this->entityManager, $this->formatterPluginManager, $this->fieldTypePluginManager, $this->languageManager, $this->renderer);
// Setup the entity manager to allow fetching the storage definitions.
$title_storage = $this->getBaseFieldStorage();
$this->entityManager->expects($this->atLeastOnce())
->method('getFieldStorageDefinitions')
->with('test_entity')
->willReturn([
'title' => $title_storage,
]);
$options = [];
$handler->init($this->executable, $this->display, $options);
$this->assertEquals('test_example', $handler->options['type']);
}
/**
* @covers ::defineOptions
*/
public function testDefineOptionsWithDefaultFormatterOnFieldType() {
$definition = [
'entity_type' => 'test_entity',
'field_name' => 'title',
'default_formatter_settings' => ['link_to_entity' => TRUE]
];
$handler = new Field([], 'field', $definition, $this->entityManager, $this->formatterPluginManager, $this->fieldTypePluginManager, $this->languageManager, $this->renderer);
// Setup the entity manager to allow fetching the storage definitions.
$title_storage = $this->getBaseFieldStorage();
$this->entityManager->expects($this->atLeastOnce())
->method('getFieldStorageDefinitions')
->with('test_entity')
->willReturn([
'title' => $title_storage,
]);
$options = [];
$handler->init($this->executable, $this->display, $options);
$this->assertEquals(['link_to_entity' => TRUE], $handler->options['settings']);
}
/**
* @covers ::calculateDependencies
*/
public function testCalculateDependenciesWithBaseField() {
$definition = [
'entity_type' => 'test_entity',
'field_name' => 'title'
];
$handler = new Field([], 'field', $definition, $this->entityManager, $this->formatterPluginManager, $this->fieldTypePluginManager, $this->languageManager, $this->renderer);
$title_storage = $this->getBaseFieldStorage();
$this->entityManager->expects($this->atLeastOnce())
->method('getFieldStorageDefinitions')
->with('test_entity')
->willReturn([
'title' => $title_storage,
]);
$dependencies = $handler->calculateDependencies();
$this->assertEmpty($dependencies);
}
/**
* @covers ::calculateDependencies
*/
public function testCalculateDependenciesWithConfiguredField() {
$definition = [
'entity_type' => 'test_entity',
'field_name' => 'body'
];
$handler = new Field([], 'field', $definition, $this->entityManager, $this->formatterPluginManager, $this->fieldTypePluginManager, $this->languageManager, $this->renderer);
$body_storage = $this->getConfigFieldStorage();
$this->entityManager->expects($this->atLeastOnce())
->method('getFieldStorageDefinitions')
->with('test_entity')
->willReturn([
'body' => $body_storage,
]);
$body_storage->expects($this->atLeastOnce())
->method('getConfigDependencyName')
->willReturn('field.field_storage_config.body');
$dependencies = $handler->calculateDependencies();
$this->assertEquals(['config' => ['field.field_storage_config.body']], $dependencies);
}
/**
* @covers ::access
*/
public function testAccess() {
$definition = [
'entity_type' => 'test_entity',
'field_name' => 'title',
];
$handler = new Field([], 'field', $definition, $this->entityManager, $this->formatterPluginManager, $this->fieldTypePluginManager, $this->languageManager, $this->renderer);
$handler->view = $this->executable;
$handler->setViewsData($this->viewsData);
$this->view->expects($this->atLeastOnce())
->method('get')
->with('base_table')
->willReturn('test_entity_table');
$this->viewsData->expects($this->atLeastOnce())
->method('get')
->with('test_entity_table')
->willReturn([
'table' => ['entity type' => 'test_entity']
]);
$access_control_handler = $this->getMock('Drupal\Core\Entity\EntityAccessControlHandlerInterface');
$this->entityManager->expects($this->atLeastOnce())
->method('getAccessControlHandler')
->with('test_entity')
->willReturn($access_control_handler);
$title_storage = $this->getBaseFieldStorage();
$this->entityManager->expects($this->atLeastOnce())
->method('getFieldStorageDefinitions')
->with('test_entity')
->willReturn([
'title' => $title_storage,
]);
$account = $this->getMock('Drupal\Core\Session\AccountInterface');
$access_control_handler->expects($this->atLeastOnce())
->method('fieldAccess')
->with('view', $this->anything(), $account, NULL, $this->anything())
->willReturn(TRUE);
$this->assertTrue($handler->access($account));
}
/**
* @dataProvider providerSortOrders
*
* @param string $order
* The sort order.
*/
public function testClickSortWithOutConfiguredColumn($order) {
$definition = [
'entity_type' => 'test_entity',
'field_name' => 'title',
];
$handler = new Field([], 'field', $definition, $this->entityManager, $this->formatterPluginManager, $this->fieldTypePluginManager, $this->languageManager, $this->renderer);
$handler->view = $this->executable;
$this->entityManager->expects($this->never())
->method('getFieldStorageDefinitions');
$handler->clickSort($order);
}
/**
* @dataProvider providerSortOrders
*
* @param string $order
* The sort order.
*
* @covers ::clickSort
*/
public function testClickSortWithBaseField($order) {
$definition = [
'entity_type' => 'test_entity',
'field_name' => 'title',
];
$handler = new Field([], 'field', $definition, $this->entityManager, $this->formatterPluginManager, $this->fieldTypePluginManager, $this->languageManager, $this->renderer);
$handler->view = $this->executable;
$field_storage = $this->getBaseFieldStorage();
$this->entityManager->expects($this->atLeastOnce())
->method('getFieldStorageDefinitions')
->with('test_entity')
->willReturn([
'title' => $field_storage,
]);
$table_mapping = $this->getMock('Drupal\Core\Entity\Sql\TableMappingInterface');
$table_mapping
->expects($this->atLeastOnce())
->method('getFieldColumnName')
->with($field_storage, 'value')
->willReturn('title');
$entity_storage = $this->getMock('Drupal\Core\Entity\Sql\SqlEntityStorageInterface');
$entity_storage->expects($this->atLeastOnce())
->method('getTableMapping')
->willReturn($table_mapping);
$this->entityManager->expects($this->atLeastOnce())
->method('getStorage')
->with('test_entity')
->willReturn($entity_storage);
// Setup a click sort configuration.
$options = [
'click_sort_column' => 'value',
'table' => 'test_entity',
];
$handler->init($this->executable, $this->display, $options);
$handler->query = $this->getMockBuilder('Drupal\views\Plugin\views\query\Sql')
->disableOriginalConstructor()
->getMock();
$handler->query->expects($this->atLeastOnce())
->method('ensureTable')
->with('test_entity', NULL)
->willReturn('test_entity');
$handler->query->expects($this->atLeastOnce())
->method('addOrderBy')
->with(NULL, NULL, $order, 'test_entity.title', []);
$handler->clickSort($order);
}
/**
* @dataProvider providerSortOrders
*
* @param string $order
* The sort order.
*
* @covers ::clickSort
*/
public function testClickSortWithConfiguredField($order) {
$definition = [
'entity_type' => 'test_entity',
'field_name' => 'body',
];
$handler = new Field([], 'field', $definition, $this->entityManager, $this->formatterPluginManager, $this->fieldTypePluginManager, $this->languageManager, $this->renderer);
$handler->view = $this->executable;
$field_storage = $this->getConfigFieldStorage();
$this->entityManager->expects($this->atLeastOnce())
->method('getFieldStorageDefinitions')
->with('test_entity')
->willReturn([
'body' => $field_storage,
]);
$table_mapping = $this->getMock('Drupal\Core\Entity\Sql\TableMappingInterface');
$table_mapping
->expects($this->atLeastOnce())
->method('getFieldColumnName')
->with($field_storage, 'value')
->willReturn('body_value');
$entity_storage = $this->getMock('Drupal\Core\Entity\Sql\SqlEntityStorageInterface');
$entity_storage->expects($this->atLeastOnce())
->method('getTableMapping')
->willReturn($table_mapping);
$this->entityManager->expects($this->atLeastOnce())
->method('getStorage')
->with('test_entity')
->willReturn($entity_storage);
// Setup a click sort configuration.
$options = [
'click_sort_column' => 'value',
'table' => 'test_entity__body',
];
$handler->init($this->executable, $this->display, $options);
$handler->query = $this->getMockBuilder('Drupal\views\Plugin\views\query\Sql')
->disableOriginalConstructor()
->getMock();
$handler->query->expects($this->atLeastOnce())
->method('ensureTable')
->with('test_entity__body', NULL)
->willReturn('test_entity__body_alias');
$handler->query->expects($this->atLeastOnce())
->method('addOrderBy')
->with(NULL, NULL, $order, 'test_entity__body_alias.body_value', []);
$handler->clickSort($order);
}
/**
* @covers ::query
*/
public function testQueryWithGroupByForBaseField() {
$definition = [
'entity_type' => 'test_entity',
'field_name' => 'title',
];
$handler = new Field([], 'field', $definition, $this->entityManager, $this->formatterPluginManager, $this->fieldTypePluginManager, $this->languageManager, $this->renderer);
$handler->view = $this->executable;
$handler->view->field = [$handler];
$this->setupLanguageRenderer($handler, $definition);
$field_storage = $this->getBaseFieldStorage();
$this->entityManager->expects($this->any())
->method('getFieldStorageDefinitions')
->with('test_entity')
->willReturn([
'title' => $field_storage,
]);
$table_mapping = $this->getMock('Drupal\Core\Entity\Sql\TableMappingInterface');
$table_mapping
->expects($this->any())
->method('getFieldColumnName')
->with($field_storage, 'value')
->willReturn('title');
$entity_storage = $this->getMock('Drupal\Core\Entity\Sql\SqlEntityStorageInterface');
$entity_storage->expects($this->any())
->method('getTableMapping')
->willReturn($table_mapping);
$this->entityManager->expects($this->any())
->method('getStorage')
->with('test_entity')
->willReturn($entity_storage);
$options = [
'group_column' => 'value',
'group_columns' => [],
'table' => 'test_entity_table',
];
$handler->init($this->executable, $this->display, $options);
$query = $this->getMockBuilder('Drupal\views\Plugin\views\query\Sql')
->disableOriginalConstructor()
->getMock();
$query->expects($this->once())
->method('ensureTable')
->with('test_entity_table', NULL)
->willReturn('test_entity_table');
// Ensure that we add the title field to the query, if we group by some
// other field in the view.
$query->expects($this->once())
->method('addField')
->with('test_entity_table', 'title');
$this->executable->query = $query;
$handler->query(TRUE);
}
/**
* @covers ::query
*/
public function testQueryWithGroupByForConfigField() {
$definition = [
'entity_type' => 'test_entity',
'field_name' => 'body',
];
$handler = new Field([], 'field', $definition, $this->entityManager, $this->formatterPluginManager, $this->fieldTypePluginManager, $this->languageManager, $this->renderer);
$handler->view = $this->executable;
$handler->view->field = [$handler];
$this->setupLanguageRenderer($handler, $definition);
$field_storage = $this->getConfigFieldStorage();
$this->entityManager->expects($this->any())
->method('getFieldStorageDefinitions')
->with('test_entity')
->willReturn([
'body' => $field_storage,
]);
$table_mapping = $this->getMock('Drupal\Core\Entity\Sql\TableMappingInterface');
$table_mapping
->expects($this->any())
->method('getFieldColumnName')
->with($field_storage, 'value')
->willReturn('body_value');
$entity_storage = $this->getMock('Drupal\Core\Entity\Sql\SqlEntityStorageInterface');
$entity_storage->expects($this->any())
->method('getTableMapping')
->willReturn($table_mapping);
$this->entityManager->expects($this->any())
->method('getStorage')
->with('test_entity')
->willReturn($entity_storage);
$options = [
'group_column' => 'value',
'group_columns' => [],
'table' => 'test_entity__body',
];
$handler->init($this->executable, $this->display, $options);
$query = $this->getMockBuilder('Drupal\views\Plugin\views\query\Sql')
->disableOriginalConstructor()
->getMock();
$query->expects($this->once())
->method('ensureTable')
->with('test_entity__body', NULL)
->willReturn('test_entity__body');
// Ensure that we add the title field to the query, if we group by some
// other field in the view.
$query->expects($this->once())
->method('addField')
->with('test_entity__body', 'body_value');
$this->executable->query = $query;
$handler->query(TRUE);
}
/**
* @covers ::prepareItemsByDelta
*
* @dataProvider providerTestPrepareItemsByDelta
*/
public function testPrepareItemsByDelta(array $options, array $expected_values) {
$definition = [
'entity_type' => 'test_entity',
'field_name' => 'integer',
];
$handler = new FieldTestField([], 'field', $definition, $this->entityManager, $this->formatterPluginManager, $this->fieldTypePluginManager, $this->languageManager, $this->renderer);
$handler->view = $this->executable;
$handler->view->field = [$handler];
$this->setupLanguageRenderer($handler, $definition);
$field_storage = $this->getConfigFieldStorage();
$field_storage->expects($this->any())
->method('getCardinality')
->willReturn(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
$this->entityManager->expects($this->any())
->method('getFieldStorageDefinitions')
->with('test_entity')
->willReturn([
'integer' => $field_storage,
]);
$table_mapping = $this->getMock('Drupal\Core\Entity\Sql\TableMappingInterface');
$table_mapping
->expects($this->any())
->method('getFieldColumnName')
->with($field_storage, 'value')
->willReturn('integer_value');
$entity_storage = $this->getMock('Drupal\Core\Entity\Sql\SqlEntityStorageInterface');
$entity_storage->expects($this->any())
->method('getTableMapping')
->willReturn($table_mapping);
$this->entityManager->expects($this->any())
->method('getStorage')
->with('test_entity')
->willReturn($entity_storage);
$options = [
'group_column' => 'value',
'group_columns' => [],
'table' => 'test_entity__integer',
] + $options;
$handler->init($this->executable, $this->display, $options);
$this->executable->row_index = 0;
$this->executable->result = [0 => new ResultRow([])];
$items = [3, 1, 4, 1, 5, 9];
$this->assertEquals($expected_values, $handler->executePrepareItemsByDelta($items));
}
/**
* Provides test data for testPrepareItemsByDelta().
*/
public function providerTestPrepareItemsByDelta() {
$data = [];
// Let's display all values.
$data[] = [[], [3, 1, 4, 1, 5, 9]];
// Test just reversed deltas.
$data[] = [['delta_reversed' => TRUE], [9, 5, 1, 4, 1, 3]];
// Test combinations of delta limit, offset and first_last.
$data[] = [['group_rows' => TRUE, 'delta_limit' => 3], [3, 1, 4]];
$data[] = [['group_rows' => TRUE, 'delta_limit' => 3, 'delta_offset' => 2], [4, 1, 5]];
$data[] = [['group_rows' => TRUE, 'delta_reversed' => TRUE, 'delta_limit' => 3, 'delta_offset' => 2], [1, 4, 1]];
$data[] = [['group_rows' => TRUE, 'delta_first_last' => TRUE], [3, 9]];
$data[] = [['group_rows' => TRUE, 'delta_limit' => 1, 'delta_first_last' => TRUE], [3]];
$data[] = [['group_rows' => TRUE, 'delta_offset' => 1, 'delta_first_last' => TRUE], [1, 9]];
return $data;
}
/**
* Returns a mocked base field storage object.
*
* @return \Drupal\Core\Field\FieldStorageDefinitionInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected function getBaseFieldStorage() {
$title_storage = $this->getMock('Drupal\Core\Field\FieldStorageDefinitionInterface');
$title_storage->expects($this->any())
->method('getColumns')
->willReturn(['value' => ['type' => 'varchar']]);
$title_storage->expects($this->any())
->method('getSettings')
->willReturn([]);
$title_storage->expects($this->any())
->method('getConstraints')
->willReturn([]);
return $title_storage;
}
/**
* Returns a mocked configurable field storage object.
*
* @return \Drupal\field\FieldStorageConfigInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected function getConfigFieldStorage() {
$title_storage = $this->getMock('Drupal\field\FieldStorageConfigInterface');
$title_storage->expects($this->any())
->method('getColumns')
->willReturn(['value' => ['type' => 'varchar']]);
$title_storage->expects($this->any())
->method('getSettings')
->willReturn([]);
$title_storage->expects($this->any())
->method('getConstraints')
->willReturn([]);
return $title_storage;
}
/**
* Provides sort orders for clickSort() test methods.
*
* @return array
*/
public function providerSortOrders() {
return [
['asc'],
['desc'],
['ASC'],
['DESC'],
];
}
/**
* Setup the mock data needed to make language renderers work.
*
* @param \Drupal\views\Plugin\views\field\Field $handler
* The field handler.
* @param $definition
* An array with entity type definition data.
*/
protected function setupLanguageRenderer(Field $handler, $definition) {
$display_handler = $this->getMockBuilder('\Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$display_handler->expects($this->any())
->method('getOption')
->with($this->equalTo('rendering_language'))
->willReturn('en');
$handler->view->display_handler = $display_handler;
$data['table']['entity type'] = $definition['entity_type'];
$views_data = $this->getMockBuilder('\Drupal\views\ViewsData')
->disableOriginalConstructor()
->getMock();
$views_data->expects($this->any())
->method('get')
->willReturn($data);
$this->container->set('views.views_data', $views_data);
$entity_type = $this->getMock('\Drupal\Core\Entity\EntityTypeInterface');
$entity_type->expects($this->any())
->method('id')
->willReturn($definition['entity_type']);
$this->entityManager->expects($this->any())
->method('getDefinition')
->willReturn($entity_type);
}
}
class FieldTestField extends Field {
public function executePrepareItemsByDelta(array $all_values) {
return $this->prepareItemsByDelta($all_values);
}
}

View file

@ -0,0 +1,255 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\pager\PagerPluginBaseTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\pager;
use Drupal\Tests\UnitTestCase;
use Drupal\Core\Database\StatementInterface;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\pager\PagerPluginBase
* @group views
*/
class PagerPluginBaseTest extends UnitTestCase {
/**
* The mock pager plugin instance.
*
* @var \Drupal\views\Plugin\views\pager\PagerPluginBase|\PHPUnit_Framework_MockObject_MockObject
*/
protected $pager;
protected function setUp() {
$this->pager = $this->getMockBuilder('Drupal\views\Plugin\views\pager\PagerPluginBase')
->disableOriginalConstructor()
->getMockForAbstractClass();
$view = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$display = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$options = array(
'items_per_page' => 5,
'offset' => 1,
);
$this->pager->init($view, $display, $options);
$this->pager->current_page = 1;
}
/**
* Tests the getItemsPerPage() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::getItemsPerPage()
*/
public function testGetItemsPerPage() {
$this->assertEquals(5, $this->pager->getItemsPerPage());
}
/**
* Tests the setItemsPerPage() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::setItemsPerPage()
*/
public function testSetItemsPerPage() {
$this->pager->setItemsPerPage(6);
$this->assertEquals(6, $this->pager->getItemsPerPage());
}
/**
* Tests the getOffset() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::getOffset()
*/
public function testGetOffset() {
$this->assertEquals(1, $this->pager->getOffset());
}
/**
* Tests the setOffset() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::setOffset()
*/
public function testSetOffset() {
$this->pager->setOffset(2);
$this->assertEquals(2, $this->pager->getOffset());
}
/**
* Tests the getCurrentPage() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::getCurrentPage()
*/
public function testGetCurrentPage() {
$this->assertEquals(1, $this->pager->getCurrentPage());
}
/**
* Tests the setCurrentPage() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::setCurrentPage()
*/
public function testSetCurrentPage() {
$this->pager->setCurrentPage(2);
$this->assertEquals(2, $this->pager->getCurrentPage());
// A non numeric number or number below 0 should return 0.
$this->pager->setCurrentPage('two');
$this->assertEquals(0, $this->pager->getCurrentPage());
$this->pager->setCurrentPage(-2);
$this->assertEquals(0, $this->pager->getCurrentPage());
}
/**
* Tests the getTotalItems() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::getTotalItems()
*/
public function testGetTotalItems() {
// Should return 0 by default.
$this->assertEquals(0, $this->pager->getTotalItems());
$this->pager->total_items = 10;
$this->assertEquals(10, $this->pager->getTotalItems());
}
/**
* Tests the getPagerId() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::getPagerId()
*/
public function testGetPagerId() {
// Should return 0 if 'id' is not set.
$this->assertEquals(0, $this->pager->getPagerId());
$this->pager->options['id'] = 1;
$this->assertEquals(1, $this->pager->getPagerId());
}
/**
* Tests the usePager() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::usePager()
*/
public function testUsePager() {
$this->assertTrue($this->pager->usePager());
}
/**
* Tests the useCountQuery() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::useCountQuery()
*/
public function testUseCountQuery() {
$this->assertTrue($this->pager->useCountQuery());
}
/**
* Tests the usesExposed() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::usedExposed()
*/
public function testUsesExposed() {
$this->assertFalse($this->pager->usesExposed());
}
/**
* Tests the hasMoreRecords() method.
*
* @dataProvider providerTestHasMoreRecords
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::hasMoreRecords()
*/
public function testHasMoreRecords($items_per_page, $total_items, $current_page, $has_more_records) {
$this->pager->setItemsPerPage($items_per_page);
$this->pager->total_items = $total_items;
$this->pager->setCurrentPage($current_page);
$this->assertEquals($has_more_records, $this->pager->hasMoreRecords());
}
/**
* Provides test data for the hasMoreRecord method test.
*
* @see self::testHasMoreRecords
*/
public function providerTestHasMoreRecords() {
return array(
// No items per page, so there can't be more available records.
array(0, 0, 0, FALSE),
array(0, 10, 0, FALSE),
// The amount of total items equals the items per page, so there is no
// next page available.
array(5, 5, 0, FALSE),
// There is one more item, and we are at the first page.
array(5, 6, 0, TRUE),
// Now we are on the second page, which has just a single one left.
array(5, 6, 1, FALSE),
// Increase the total items, so we have some available on the third page.
array(5, 12, 1, TRUE)
);
}
/**
* Tests the executeCountQuery method without a set offset.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::executeCountQuery()
*/
public function testExecuteCountQueryWithoutOffset() {
$statement = $this->getMock('\Drupal\Tests\views\Unit\Plugin\pager\TestStatementInterface');
$statement->expects($this->once())
->method('fetchField')
->will($this->returnValue(3));
$query = $this->getMockBuilder('\Drupal\Core\Database\Query\Select')
->disableOriginalConstructor()
->getMock();
$query->expects($this->once())
->method('execute')
->will($this->returnValue($statement));
$this->pager->setOffset(0);
$this->assertEquals(3, $this->pager->executeCountQuery($query));
}
/**
* Tests the executeCountQuery method with a set offset.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::executeCountQuery()
*/
public function testExecuteCountQueryWithOffset() {
$statement = $this->getMock('\Drupal\Tests\views\Unit\Plugin\pager\TestStatementInterface');
$statement->expects($this->once())
->method('fetchField')
->will($this->returnValue(3));
$query = $this->getMockBuilder('\Drupal\Core\Database\Query\Select')
->disableOriginalConstructor()
->getMock();
$query->expects($this->once())
->method('execute')
->will($this->returnValue($statement));
$this->pager->setOffset(2);
$this->assertEquals(1, $this->pager->executeCountQuery($query));
}
}
// As StatementInterface extends \Traversable, which though always needs
// an additional interface. The Statement class itself can't be mocked because
// of its __wakeup function.
interface TestStatementInterface extends StatementInterface, \Iterator {}

View file

@ -0,0 +1,106 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\query\SqlTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\query;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\query\Sql;
use Drupal\views\ResultRow;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\query\Sql
*
* @group views
*/
class SqlTest extends UnitTestCase {
/**
* @covers ::getCacheTags
* @covers ::getAllEntities
*/
public function testGetCacheTags() {
$view = $this->prophesize('Drupal\views\ViewExecutable')->reveal();
$query = new Sql([], 'sql', []);
$query->view = $view;
$result = [];
$view->result = $result;
// Add a row with an entity.
$row = new ResultRow();
$prophecy = $this->prophesize('Drupal\Core\Entity\EntityInterface');
$prophecy->getCacheTags()->willReturn(['entity_test:123']);
$entity = $prophecy->reveal();
$row->_entity = $entity;
$result[] = $row;
$view->result = $result;
// Add a row with an entity and a relationship entity.
$row = new ResultRow();
$prophecy = $this->prophesize('Drupal\Core\Entity\EntityInterface');
$prophecy->getCacheTags()->willReturn(['entity_test:124']);
$entity = $prophecy->reveal();
$row->_entity = $entity;
$prophecy = $this->prophesize('Drupal\Core\Entity\EntityInterface');
$prophecy->getCacheTags()->willReturn(['entity_test:125']);
$entity = $prophecy->reveal();
$row->_relationship_entities[] = $entity;
$prophecy = $this->prophesize('Drupal\Core\Entity\EntityInterface');
$prophecy->getCacheTags()->willReturn(['entity_test:126']);
$entity = $prophecy->reveal();
$row->_relationship_entities[] = $entity;
$result[] = $row;
$view->result = $result;
$this->assertEquals(['entity_test:123', 'entity_test:124', 'entity_test:125', 'entity_test:126'], $query->getCacheTags());
}
/**
* @covers ::getCacheTags
* @covers ::getAllEntities
*/
public function testGetCacheMaxAge() {
$view = $this->prophesize('Drupal\views\ViewExecutable')->reveal();
$query = new Sql([], 'sql', []);
$query->view = $view;
$view->result = [];
// Add a row with an entity.
$row = new ResultRow();
$prophecy = $this->prophesize('Drupal\Core\Entity\EntityInterface');
$prophecy->getCacheMaxAge()->willReturn(10);
$entity = $prophecy->reveal();
$row->_entity = $entity;
$view->result[] = $row;
// Add a row with an entity and a relationship entity.
$row = new ResultRow();
$prophecy = $this->prophesize('Drupal\Core\Entity\EntityInterface');
$prophecy->getCacheMaxAge()->willReturn(20);
$entity = $prophecy->reveal();
$row->_entity = $entity;
$prophecy = $this->prophesize('Drupal\Core\Entity\EntityInterface');
$prophecy->getCacheMaxAge()->willReturn(30);
$entity = $prophecy->reveal();
$row->_relationship_entities[] = $entity;
$prophecy = $this->prophesize('Drupal\Core\Entity\EntityInterface');
$prophecy->getCacheMaxAge()->willReturn(40);
$entity = $prophecy->reveal();
$row->_relationship_entities[] = $entity;
$this->assertEquals(10, $query->getCacheMaxAge());
}
}

View file

@ -0,0 +1,95 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\views\display\BlockTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\views\display;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\display\Block
* @group block
*/
class BlockTest extends UnitTestCase {
/**
* The view executable.
*
* @var \Drupal\views\ViewExecutable|\PHPUnit_Framework_MockObject_MockObject
*/
protected $executable;
/**
* The views block plugin.
*
* @var \Drupal\views\Plugin\Block\ViewsBlock|\PHPUnit_Framework_MockObject_MockObject
*/
protected $blockPlugin;
/**
* The tested block display plugin.
*
* @var \Drupal\views\Plugin\views\display\Block|\PHPUnit_Framework_MockObject_MockObject
*/
protected $blockDisplay;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->setMethods(array('executeDisplay', 'setDisplay', 'setItemsPerPage'))
->getMock();
$this->executable->expects($this->any())
->method('setDisplay')
->with('block_1')
->will($this->returnValue(TRUE));
$this->blockDisplay = $this->executable->display_handler = $this->getMockBuilder('Drupal\views\Plugin\views\display\Block')
->disableOriginalConstructor()
->setMethods(NULL)
->getMock();
$this->blockDisplay->view = $this->executable;
$this->blockPlugin = $this->getMockBuilder('Drupal\views\Plugin\Block\ViewsBlock')
->disableOriginalConstructor()
->getMock();
}
/**
* Tests the build method with no overriding.
*/
public function testBuildNoOverride() {
$this->executable->expects($this->never())
->method('setItemsPerPage');
$this->blockPlugin->expects($this->once())
->method('getConfiguration')
->will($this->returnValue(array('items_per_page' => 'none')));
$this->blockDisplay->preBlockBuild($this->blockPlugin);
}
/**
* Tests the build method with overriding items per page.
*/
public function testBuildOverride() {
$this->executable->expects($this->once())
->method('setItemsPerPage')
->with(5);
$this->blockPlugin->expects($this->once())
->method('getConfiguration')
->will($this->returnValue(array('items_per_page' => 5)));
$this->blockDisplay->preBlockBuild($this->blockPlugin);
}
}

View file

@ -0,0 +1,165 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\views\field\EntityOperationsUnitTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\views\field {
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\field\EntityOperations;
use Drupal\views\ResultRow;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\field\EntityOperations
* @group Views
*/
class EntityOperationsUnitTest extends UnitTestCase {
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $entityManager;
/**
* The plugin under test.
*
* @var \Drupal\views\Plugin\views\field\EntityOperations
*/
protected $plugin;
/**
* {@inheritdoc}
*
* @covers ::__construct
*/
public function setUp() {
$this->entityManager = $this->getMock('\Drupal\Core\Entity\EntityManagerInterface');
$configuration = array();
$plugin_id = $this->randomMachineName();
$plugin_definition = array(
'title' => $this->randomMachineName(),
);
$this->plugin = new EntityOperations($configuration, $plugin_id, $plugin_definition, $this->entityManager);
$redirect_service = $this->getMock('Drupal\Core\Routing\RedirectDestinationInterface');
$redirect_service->expects($this->any())
->method('getAsArray')
->willReturn(['destination' => 'foobar']);
$this->plugin->setRedirectDestination($redirect_service);
$view = $this->getMockBuilder('\Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$display = $this->getMockBuilder('\Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMockForAbstractClass();
$view->display_handler = $display;
$this->plugin->init($view, $display);
}
/**
* @covers ::usesGroupBy
*/
public function testUsesGroupBy() {
$this->assertFalse($this->plugin->usesGroupBy());
}
/**
* @covers ::defineOptions
*/
public function testDefineOptions() {
$options = $this->plugin->defineOptions();
$this->assertInternalType('array', $options);
$this->assertArrayHasKey('destination', $options);
}
/**
* @covers ::render
*/
public function testRenderWithDestination() {
$entity_type_id = $this->randomMachineName();
$entity = $this->getMockBuilder('\Drupal\user\Entity\Role')
->disableOriginalConstructor()
->getMock();
$entity->expects($this->any())
->method('getEntityTypeId')
->will($this->returnValue($entity_type_id));
$operations = array(
'foo' => array(
'title' => $this->randomMachineName(),
),
);
$list_builder = $this->getMock('\Drupal\Core\Entity\EntityListBuilderInterface');
$list_builder->expects($this->once())
->method('getOperations')
->with($entity)
->will($this->returnValue($operations));
$this->entityManager->expects($this->once())
->method('getListBuilder')
->with($entity_type_id)
->will($this->returnValue($list_builder));
$this->plugin->options['destination'] = TRUE;
$result = new ResultRow();
$result->_entity = $entity;
$expected_build = array(
'#type' => 'operations',
'#links' => $operations
);
$expected_build['#links']['foo']['query'] = ['destination' => 'foobar'];
$build = $this->plugin->render($result);
$this->assertSame($expected_build, $build);
}
/**
* @covers ::render
*/
public function testRenderWithoutDestination() {
$entity_type_id = $this->randomMachineName();
$entity = $this->getMockBuilder('\Drupal\user\Entity\Role')
->disableOriginalConstructor()
->getMock();
$entity->expects($this->any())
->method('getEntityTypeId')
->will($this->returnValue($entity_type_id));
$operations = array(
'foo' => array(
'title' => $this->randomMachineName(),
),
);
$list_builder = $this->getMock('\Drupal\Core\Entity\EntityListBuilderInterface');
$list_builder->expects($this->once())
->method('getOperations')
->with($entity)
->will($this->returnValue($operations));
$this->entityManager->expects($this->once())
->method('getListBuilder')
->with($entity_type_id)
->will($this->returnValue($list_builder));
$this->plugin->options['destination'] = FALSE;
$result = new ResultRow();
$result->_entity = $entity;
$expected_build = array(
'#type' => 'operations',
'#links' => $operations
);
$build = $this->plugin->render($result);
$this->assertSame($expected_build, $build);
}
}
}

View file

@ -0,0 +1,320 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\PluginBaseTest.
*/
namespace Drupal\Tests\views\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Tests\TestHelperPlugin;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\PluginBase
* @group views
*/
class PluginBaseTest extends UnitTestCase {
/**
* The test helper plugin to use for the tests.
*
* @var \Drupal\views\Tests\TestHelperPlugin
*/
protected $testHelperPlugin;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->testHelperPlugin = new TestHelperPlugin(array(), 'default', array());
}
/**
* Tests the unpackOptions method.
*
* @param array $storage
* The storage array to unpack option into.
* @param array $options
* The array of options to unpack.
* @param array $definition
* The definition array, defining default options.
* @param array $expected
* The expected array after unpacking
* @param bool $all
* Whether to unpack all options.
*
* @dataProvider providerTestUnpackOptions
* @covers ::unpackOptions
*/
public function testUnpackOptions($storage, $options, $definition, $expected, $all = FALSE) {
$this->testHelperPlugin->unpackOptions($storage, $options, $definition, $all);
$this->assertEquals($storage, $expected);
}
/**
* Tests the setOptionDefault method.
*
* @param array $storage
* The storage array to unpack option into.
* @param array $definition
* The definition array, defining default options.
* @param array $expected
* The expected array after unpacking
*
* @dataProvider providerTestSetOptionDefault
* @covers ::setOptionDefaults
*/
public function testSetOptionDefault($storage, $definition, $expected) {
$this->testHelperPlugin->testSetOptionDefaults($storage, $definition);
$this->assertEquals($storage, $expected);
}
/**
* Data provider for testUnpackOptions().
*
* @return array
*/
public function providerTestUnpackOptions() {
$test_parameters = array();
// Set a storage but no value, so the storage value should be kept.
$test_parameters[] = array(
'storage' => array(
'key' => 'value',
),
'options' => array(
),
'definition' => array(
'key' => array('default' => 'value2'),
),
'expected' => array(
'key' => 'value',
),
);
// Set a storage and a option value, so the option value should be kept.
$test_parameters[] = array(
'storage' => array(
'key' => 'value',
),
'options' => array(
'key' => 'value2',
),
'definition' => array(
'key' => array('default' => 'value3'),
),
'expected' => array(
'key' => 'value2',
),
''
);
// Set no storage but an options value, so the options value should be kept.
$test_parameters[] = array(
'storage' => array(),
'options' => array(
'key' => 'value',
),
'definition' => array(
'key' => array('default' => 'value2'),
),
'expected' => array(
'key' => 'value',
),
);
// Set additional options, which aren't part of the definition, so they
// should be ignored if all is set.
$test_parameters[] = array(
'storage' => array(),
'options' => array(
'key' => 'value',
'key2' => 'value2',
),
'definition' => array(
'key' => array('default' => 'value2'),
),
'expected' => array(
'key' => 'value',
),
);
$test_parameters[] = array(
'storage' => array(),
'options' => array(
'key' => 'value',
'key2' => 'value2',
),
'definition' => array(
'key' => array('default' => 'value2'),
),
'expected' => array(
'key' => 'value',
'key2' => 'value2',
),
'all' => TRUE,
);
// Provide multiple options with their corresponding definition.
$test_parameters[] = array(
'storage' => array(),
'options' => array(
'key' => 'value',
'key2' => 'value2',
),
'definition' => array(
'key' => array('default' => 'value2'),
'key2' => array('default' => 'value3'),
),
'expected' => array(
'key' => 'value',
'key2' => 'value2',
),
);
// Set a complex definition structure with a zero and a one level structure.
$test_parameters[] = array(
'storage' => array(),
'options' => array(
'key0' => 'value',
'key1' => array('key1:1' => 'value1', 'key1:2' => 'value2'),
),
'definition' => array(
'key0' => array('default' => 'value0'),
'key1' => array('contains' => array(
'key1:1' => array('default' => 'value1:1'),
)),
),
'expected' => array(
'key0' => 'value',
'key1' => array('key1:1' => 'value1'),
),
);
// Setup a two level structure.
$test_parameters[] = array(
'storage' => array(),
'options' => array(
'key2' => array(
'key2:1' => array(
'key2:1:1' => 'value0',
'key2:1:2' => array(
'key2:1:2:1' => 'value1',
),
),
),
),
'definition' => array(
'key2' => array('contains' => array(
'key2:1' => array('contains' => array(
'key2:1:1' => array('default' => 'value2:1:2:1'),
'key2:1:2' => array('contains' => array(
'key2:1:2:1' => array('default' => 'value2:1:2:1'),
)),
)),
)),
),
'expected' => array(
'key2' => array(
'key2:1' => array(
'key2:1:1' => 'value0',
'key2:1:2' => array(
'key2:1:2:1' => 'value1',
),
),
),
),
);
return $test_parameters;
}
/**
* Data provider for testSetOptionDefault().
*
* @return array
*/
public function providerTestSetOptionDefault() {
$test_parameters = array();
// No definition should change anything on the storage.
$test_parameters[] = array(
'storage' => array(),
'definition' => array(),
'expected' => array(),
);
// Set a single definition, which should be picked up.
$test_parameters[] = array(
'storage' => array(),
'definition' => array(
'key' => array('default' => 'value'),
),
'expected' => array(
'key' => 'value',
),
);
// Set multiple keys, all should be picked up.
$test_parameters[] = array(
'storage' => array(),
'definition' => array(
'key' => array('default' => 'value'),
'key2' => array('default' => 'value2'),
'key3' => array('default' => 'value3'),
),
'expected' => array(
'key' => 'value',
'key2' => 'value2',
'key3' => 'value3',
),
);
// Setup a definition with multiple levels.
$test_parameters[] = array(
'storage' => array(),
'definition' => array(
'key' => array('default' => 'value'),
'key2' => array('contains' => array(
'key2:1' => array('default' => 'value2:1'),
'key2:2' => array('default' => 'value2:2'),
)),
),
'expected' => array(
'key' => 'value',
'key2' => array(
'key2:1' => 'value2:1',
'key2:2' => 'value2:2',
),
),
);
return $test_parameters;
}
/**
* @dataProvider providerTestFilterByDefinedOptions
* @covers ::filterByDefinedOptions
*/
public function testFilterByDefinedOptions($storage, $options, $expected_storage) {
$this->testHelperPlugin->setDefinedOptions($options);
$this->testHelperPlugin->filterByDefinedOptions($storage);
$this->assertEquals($expected_storage, $storage);
}
public function providerTestFilterByDefinedOptions() {
$data = [];
// A simple defined option.
$values_1 = ['key1' => 'value1'];
$options_1 = ['key1' => ['default' => '']];
$data[] = [$values_1, $options_1, $values_1];
// Multiple defined options .
$values_2 = ['key1' => 'value1', 'key2' => 'value2'];
$options_2 = ['key1' => ['default' => ''], 'key2' => ['default' => '']];
$data[] = [$values_2, $options_2, $values_2];
// Multiple options, just one defined.
$data[] = [$values_2, $options_1, $values_1];
// Nested options, all properly defined.
$data[] = [['sub1' => $values_2, 'sub2' => $values_2], ['sub1' => ['contains' => $options_2], 'sub2' => ['contains' => $options_2]], ['sub1' => $values_2, 'sub2' => $values_2]];
// Nested options, not all properly defined.
$data[] = [['sub1' => $values_2, 'sub2' => $values_2], ['sub1' => ['contains' => $options_2], 'sub2' => ['contains' => $options_1]], ['sub1' => $values_2, 'sub2' => $values_1]];
return $data;
}
}

View file

@ -0,0 +1,49 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\PluginTypeListTest.
*/
namespace Drupal\Tests\views\Unit;
use Drupal\views\ViewExecutable;
use Drupal\Tests\UnitTestCase;
/**
* Tests that list of plugin is correct.
*
* @group views
*/
class PluginTypeListTest extends UnitTestCase {
/**
* Tests the plugins list is correct.
*/
public function testPluginList() {
$plugin_list = array(
'access',
'area',
'argument',
'argument_default',
'argument_validator',
'cache',
'display_extender',
'display',
'exposed_form',
'field',
'filter',
'join',
'pager',
'query',
'relationship',
'row',
'sort',
'style',
'wizard',
);
$diff = array_diff($plugin_list, ViewExecutable::getPluginTypes());
$this->assertTrue(empty($diff), 'The plugin list is correct');
}
}

View file

@ -0,0 +1,217 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Routing\ViewPageControllerTest.
*/
namespace Drupal\Tests\views\Unit\Routing;
use Drupal\Core\Routing\RouteMatch;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Routing\ViewPageController;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\Routing\Route;
/**
* @coversDefaultClass \Drupal\views\Routing\ViewPageController
* @group views
*/
class ViewPageControllerTest extends UnitTestCase {
/**
* The page controller of views.
*
* @var \Drupal\views\Routing\ViewPageController
*/
public $pageController;
/**
* The mocked view storage.
*
* @var \Drupal\views\ViewStorage|\PHPUnit_Framework_MockObject_MockObject
*/
protected $storage;
/**
* The mocked view executable factory.
*
* @var \Drupal\views\ViewExecutableFactory|\PHPUnit_Framework_MockObject_MockObject
*/
protected $executableFactory;
/**
* A render array expected for every page controller render array result.
*
* @var array
*/
protected $defaultRenderArray = [
'#cache_properties' => ['#view_id', '#view_display_show_admin_links', '#view_display_plugin_id'],
'#view_id' => 'test_page_view',
'#view_display_plugin_id' => NULL,
'#view_display_show_admin_links' => NULL,
];
protected function setUp() {
$this->storage = $this->getMockBuilder('Drupal\Core\Config\Entity\ConfigEntityStorage')
->disableOriginalConstructor()
->getMock();
$this->executableFactory = $this->getMockBuilder('Drupal\views\ViewExecutableFactory')
->disableOriginalConstructor()
->getMock();
$this->pageController = new ViewPageController($this->storage, $this->executableFactory);
}
/**
* Tests the page controller.
*/
public function testPageController() {
$this->storage->expects($this->never())
->method('load');
$build = [
'#type' => 'view',
'#name' => 'test_page_view',
'#display_id' => 'default',
'#embed' => FALSE,
'#arguments' => [],
'#cache' => [
'keys' => ['view', 'test_page_view', 'display', 'default'],
],
] + $this->defaultRenderArray;
$request = new Request();
$request->attributes->set('view_id', 'test_page_view');
$request->attributes->set('display_id', 'default');
$options = [
'_view_display_plugin_class' => '\Drupal\views\Plugin\views\display\Page',
];
$request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/test', ['view_id' => 'test_page_view', 'display_id' => 'default'], [], $options));
$route_match = RouteMatch::createFromRequest($request);
$output = $this->pageController->handle($route_match->getParameter('view_id'), $route_match->getParameter('display_id'), $route_match);
$this->assertInternalType('array', $output);
$this->assertEquals($build, $output);
}
/**
* Tests the page controller with arguments on a non overridden page view.
*/
public function testHandleWithArgumentsWithoutOverridden() {
$this->storage->expects($this->never())
->method('load');
$request = new Request();
$request->attributes->set('view_id', 'test_page_view');
$request->attributes->set('display_id', 'page_1');
// Add the argument to the request.
$request->attributes->set('arg_0', 'test-argument');
$options = [
'_view_argument_map' => ['arg_0' => 'arg_0'],
'_view_display_plugin_class' => '\Drupal\views\Plugin\views\display\Page',
];
$request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/test/{arg_0}', ['view_id' => 'test_page_view', 'display_id' => 'default'], [], $options));
$route_match = RouteMatch::createFromRequest($request);
$result = $this->pageController->handle($route_match->getParameter('view_id'), $route_match->getParameter('display_id'), $route_match);
$build = [
'#type' => 'view',
'#name' => 'test_page_view',
'#display_id' => 'page_1',
'#embed' => FALSE,
'#arguments' => ['test-argument'],
'#cache' => [
'keys' => ['view', 'test_page_view', 'display', 'page_1', 'args', 'test-argument'],
],
] + $this->defaultRenderArray;
$this->assertEquals($build, $result);
}
/**
* Tests the page controller with arguments of a overridden page view.
*
* Note: This test does not care about upcasting for now.
*/
public function testHandleWithArgumentsOnOverriddenRoute() {
$this->storage->expects($this->never())
->method('load');
$request = new Request();
$request->attributes->set('view_id', 'test_page_view');
$request->attributes->set('display_id', 'page_1');
// Add the argument to the request.
$request->attributes->set('parameter', 'test-argument');
$options = [
'_view_argument_map' => [
'arg_0' => 'parameter',
],
'_view_display_plugin_class' => '\Drupal\views\Plugin\views\display\Page',
];
$request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/test/{parameter}', ['view_id' => 'test_page_view', 'display_id' => 'default'], [], $options));
$route_match = RouteMatch::createFromRequest($request);
$result = $this->pageController->handle($route_match->getParameter('view_id'), $route_match->getParameter('display_id'), $route_match);
$build = [
'#type' => 'view',
'#name' => 'test_page_view',
'#display_id' => 'page_1',
'#embed' => FALSE,
'#arguments' => ['test-argument'],
'#cache' => [
'keys' => ['view', 'test_page_view', 'display', 'page_1', 'args', 'test-argument'],
],
] + $this->defaultRenderArray;
$this->assertEquals($build, $result);
}
/**
* Tests the page controller with arguments of a overridden page view.
*
* This test care about upcasted values and ensures that the raw variables
* are pulled in.
*/
public function testHandleWithArgumentsOnOverriddenRouteWithUpcasting() {
$this->storage->expects($this->never())
->method('load');
$request = new Request();
$request->attributes->set('view_id', 'test_page_view');
$request->attributes->set('display_id', 'page_1');
// Add the argument to the request.
$request->attributes->set('test_entity', $this->getMock('Drupal\Core\Entity\EntityInterface'));
$raw_variables = new ParameterBag(array('test_entity' => 'example_id'));
$request->attributes->set('_raw_variables', $raw_variables);
$options = [
'_view_argument_map' => [
'arg_0' => 'test_entity',
],
'_view_display_plugin_class' => '\Drupal\views\Plugin\views\display\Page',
];
$request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/test/{test_entity}', ['view_id' => 'test_page_view', 'display_id' => 'default'], [], $options));
$route_match = RouteMatch::createFromRequest($request);
$result = $this->pageController->handle($route_match->getParameter('view_id'), $route_match->getParameter('display_id'), $route_match);
$build = [
'#type' => 'view',
'#name' => 'test_page_view',
'#display_id' => 'page_1',
'#embed' => FALSE,
'#arguments' => ['example_id'],
'#cache' => [
'keys' => ['view', 'test_page_view', 'display', 'page_1', 'args', 'example_id'],
],
] + $this->defaultRenderArray;
$this->assertEquals($build, $result);
}
}

View file

@ -0,0 +1,106 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\ViewExecutableFactoryTest.
*/
namespace Drupal\Tests\views\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\views\ViewExecutableFactory;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* @coversDefaultClass \Drupal\views\ViewExecutableFactory
* @group views
*/
class ViewExecutableFactoryTest extends UnitTestCase {
/**
* The mock user object.
*
* @var \Drupal\Core\Session\AccountInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $user;
/**
* The mock request stack object.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* The mock view entity.
*
* @var \Drupal\Core\Config\Entity\ConfigEntityInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $view;
/**
* The ViewExecutableFactory class under test.
*
* @var \Drupal\views\ViewExecutableFactory
*/
protected $viewExecutableFactory;
/**
* The mocked views data.
*
* @var \Drupal\views\ViewsData|\PHPUnit_Framework_MockObject_MockObject
*/
protected $viewsData;
/**
* The mocked route provider.
*
* @var \Drupal\Core\Routing\RouteProviderInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $routeProvider;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->user = $this->getMock('Drupal\Core\Session\AccountInterface');
$this->requestStack = new RequestStack();
$this->view = $this->getMock('Drupal\views\ViewEntityInterface');
$this->viewsData = $this->getMockBuilder('Drupal\views\ViewsData')
->disableOriginalConstructor()
->getMock();
$this->routeProvider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface');
$this->viewExecutableFactory = new ViewExecutableFactory($this->user, $this->requestStack, $this->viewsData, $this->routeProvider);
}
/**
* Tests the get method.
*
* @covers ::get
*/
public function testGet() {
$request_1 = new Request();
$request_2 = new Request();
$this->requestStack->push($request_1);
$executable = $this->viewExecutableFactory->get($this->view);
$this->assertInstanceOf('Drupal\views\ViewExecutable', $executable);
$this->assertSame($executable->getRequest(), $request_1);
$this->assertSame($executable->getUser(), $this->user);
// Call get() again to ensure a new executable is created with the other
// request object.
$this->requestStack->push($request_2);
$executable = $this->viewExecutableFactory->get($this->view);
$this->assertInstanceOf('Drupal\views\ViewExecutable', $executable);
$this->assertSame($executable->getRequest(), $request_2);
$this->assertSame($executable->getUser(), $this->user);
}
}

View file

@ -0,0 +1,472 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\ViewExecutableTest.
*/
namespace Drupal\Tests\views\Unit;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Url;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Entity\View;
use Drupal\views\ViewExecutable;
use Symfony\Component\Routing\Route;
/**
* @coversDefaultClass \Drupal\views\ViewExecutable
* @group views
*/
class ViewExecutableTest extends UnitTestCase {
/**
* A mocked display collection.
*
* @var \Drupal\views\DisplayPluginCollection|\PHPUnit_Framework_MockObject_MockObject
*/
protected $displayHandlers;
/**
* The mocked view executable.
*
* @var \Drupal\views\ViewExecutableFactory|\PHPUnit_Framework_MockObject_MockObject
*/
protected $viewExecutableFactory;
/**
* The tested view executable.
*
* @var \Drupal\views\ViewExecutable
*/
protected $executable;
/**
* The mocked view entity.
*
* @var \Drupal\views\ViewEntityInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $view;
/**
* The mocked user.
*
* @var \Drupal\Core\Session\AccountInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $user;
/**
* The mocked views data.
*
* @var \Drupal\views\ViewsData|\PHPUnit_Framework_MockObject_MockObject
*/
protected $viewsData;
/**
* The mocked display handler.
*
* @var \Drupal\views\Plugin\views\display\DisplayPluginInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $displayHandler;
/**
* The mocked route provider.
*
* @var \Drupal\Core\Routing\RouteProviderInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $routeProvider;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->view = $this->getMock('Drupal\views\ViewEntityInterface');
$this->user = $this->getMock('Drupal\Core\Session\AccountInterface');
$this->viewsData = $this->getMockBuilder('Drupal\views\ViewsData')
->disableOriginalConstructor()
->getMock();
$this->displayHandler = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayRouterInterface')
->disableOriginalConstructor()
->getMock();
$this->routeProvider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface');
$this->displayHandlers = $this->getMockBuilder('Drupal\views\DisplayPluginCollection')
->disableOriginalConstructor()
->getMock();
$this->executable = new ViewExecutable($this->view, $this->user, $this->viewsData, $this->routeProvider);
$this->executable->display_handler = $this->displayHandler;
$this->executable->displayHandlers = $this->displayHandlers;
$this->viewExecutableFactory = $this->getMockBuilder('Drupal\views\ViewExecutableFactory')
->disableOriginalConstructor()
->getMock();
$translation = $this->getStringTranslationStub();
$container = new ContainerBuilder();
$container->set('string_translation', $translation);
$container->set('views.executable', $this->viewExecutableFactory);
\Drupal::setContainer($container);
}
/**
* @covers ::getUrl
*/
public function testGetUrlWithOverriddenUrl() {
$url = Url::fromRoute('example');
$this->executable->override_url = $url;
$this->assertSame($url, $this->executable->getUrl());
}
/**
* @covers ::getUrl
*/
public function testGetUrlWithPathNoPlaceholders() {
$this->displayHandler->expects($this->any())
->method('getRoutedDisplay')
->willReturn($this->displayHandler);
$this->displayHandlers->expects($this->any())
->method('get')
->willReturn($this->displayHandler);
$this->displayHandler->expects($this->any())
->method('getUrlInfo')
->willReturn(Url::fromRoute('views.test.page_1'));
$this->displayHandler->expects($this->any())
->method('getPath')
->willReturn('test-path');
$this->assertEquals(Url::fromRoute('views.test.page_1'), $this->executable->getUrl());
}
/**
* @expectedException \InvalidArgumentException
*
* @covers ::getUrl
*/
public function testGetUrlWithoutRouterDisplay() {
$this->displayHandler = $this->getMock('Drupal\views\Plugin\views\display\DisplayPluginInterface');
$this->displayHandlers->expects($this->any())
->method('get')
->willReturn($this->displayHandler);
$this->executable->display_handler = $this->displayHandler;
$this->executable->getUrl();
}
/**
* @covers ::getUrl
*/
public function testGetUrlWithPlaceholdersAndArgs() {
$this->displayHandler->expects($this->any())
->method('getRoutedDisplay')
->willReturn($this->displayHandler);
$this->displayHandlers->expects($this->any())
->method('get')
->willReturn($this->displayHandler);
$this->displayHandler->expects($this->any())
->method('getUrlInfo')
->willReturn(Url::fromRoute('views.test.page_1'));
$this->displayHandler->expects($this->any())
->method('getPath')
->willReturn('test-path/%');
$route = new Route('/test-path/{arg_0}');
$this->routeProvider->expects($this->any())
->method('getRouteByName')
->with('views.test.page_1')
->willReturn($route);
$this->assertEquals(Url::fromRoute('views.test.page_1', ['arg_0' => 'test']), $this->executable->getUrl(['test']));
}
/**
* @covers ::getUrl
*/
public function testGetUrlWithPlaceholdersAndWithoutArgs() {
$this->displayHandler->expects($this->any())
->method('getRoutedDisplay')
->willReturn($this->displayHandler);
$this->displayHandlers->expects($this->any())
->method('get')
->willReturn($this->displayHandler);
$this->displayHandler->expects($this->any())
->method('getUrlInfo')
->willReturn(Url::fromRoute('views.test.page_1'));
$this->displayHandler->expects($this->any())
->method('getPath')
->willReturn('test-path/%/%');
$route = new Route('/test-path/{arg_0}/{arg_1}');
$this->routeProvider->expects($this->any())
->method('getRouteByName')
->with('views.test.page_1')
->willReturn($route);
$this->assertEquals(Url::fromRoute('views.test.page_1', ['arg_0' => '*', 'arg_1' => '*']), $this->executable->getUrl());
}
/**
* @covers ::getUrl
*/
public function testGetUrlWithPlaceholdersAndWithoutArgsAndExceptionValue() {
$this->displayHandler->expects($this->any())
->method('getRoutedDisplay')
->willReturn($this->displayHandler);
$this->displayHandlers->expects($this->any())
->method('get')
->willReturn($this->displayHandler);
$this->displayHandler->expects($this->any())
->method('getUrlInfo')
->willReturn(Url::fromRoute('views.test.page_1'));
$this->displayHandler->expects($this->any())
->method('getPath')
->willReturn('test-path/%/%');
$route = new Route('/test-path/{arg_0}/{arg_1}');
$this->routeProvider->expects($this->any())
->method('getRouteByName')
->with('views.test.page_1')
->willReturn($route);
$argument_handler = $this->getMockBuilder('Drupal\views\Plugin\views\argument\ArgumentPluginBase')
->disableOriginalConstructor()
->getMock();
$argument_handler->options['exception']['value'] = 'exception_0';
$this->executable->argument['key_1'] = $argument_handler;
$argument_handler = $this->getMockBuilder('Drupal\views\Plugin\views\argument\ArgumentPluginBase')
->disableOriginalConstructor()
->getMock();
$argument_handler->options['exception']['value'] = 'exception_1';
$this->executable->argument['key_2'] = $argument_handler;
$this->assertEquals(Url::fromRoute('views.test.page_1', ['arg_0' => 'exception_0', 'arg_1' => 'exception_1']), $this->executable->getUrl());
}
/**
* @covers ::buildThemeFunctions
*/
public function testBuildThemeFunctions() {
/** @var \Drupal\views\ViewExecutable|\PHPUnit_Framework_MockObject_MockObject $view */
/** @var \Drupal\views\Plugin\views\display\DisplayPluginBase|\PHPUnit_Framework_MockObject_MockObject $display */
list($view, $display) = $this->setupBaseViewAndDisplay();
unset($view->display_handler);
$expected = [
'test_hook__test_view',
'test_hook'
];
$this->assertEquals($expected, $view->buildThemeFunctions('test_hook'));
$view->display_handler = $display;
$expected = [
'test_hook__test_view__default',
'test_hook__default',
'test_hook__one',
'test_hook__two',
'test_hook__and_three',
'test_hook__test_view',
'test_hook'
];
$this->assertEquals($expected, $view->buildThemeFunctions('test_hook'));
//Change the name of the display plugin and make sure that is in the array.
$view->display_handler->display['display_plugin'] = 'default2';
$expected = [
'test_hook__test_view__default',
'test_hook__default',
'test_hook__one',
'test_hook__two',
'test_hook__and_three',
'test_hook__test_view__default2',
'test_hook__default2',
'test_hook__test_view',
'test_hook'
];
$this->assertEquals($expected, $view->buildThemeFunctions('test_hook'));
}
/**
* @covers ::generateHandlerId
*/
public function testGenerateHandlerId() {
// Test the generateHandlerId() method.
$test_ids = ['test' => 'test', 'test_1' => 'test_1'];
$this->assertEquals(ViewExecutable::generateHandlerId('new', $test_ids), 'new');
$this->assertEquals(ViewExecutable::generateHandlerId('test', $test_ids), 'test_2');
}
/**
* @covers ::addHandler
*/
public function testAddHandler() {
/** @var \Drupal\views\ViewExecutable|\PHPUnit_Framework_MockObject_MockObject $view */
/** @var \Drupal\views\Plugin\views\display\DisplayPluginBase|\PHPUnit_Framework_MockObject_MockObject $display */
list($view, $display) = $this->setupBaseViewAndDisplay();
$views_data = [];
$views_data['test_field'] = [
'field' => ['id' => 'standard'],
'filter' => ['id' => 'standard'],
'argument' => ['id' => 'standard'],
'sort' => ['id' => 'standard'],
];
$this->viewsData->expects($this->atLeastOnce())
->method('get')
->with('test_entity')
->willReturn($views_data);
foreach (['field', 'filter', 'argument', 'sort'] as $handler_type) {
$display->expects($this->atLeastOnce())
->method('setOption')
->with($this->callback(function($argument) {
return $argument;
}), ['test_field' => [
'id' => 'test_field',
'table' => 'test_entity',
'field' => 'test_field',
'plugin_id' => 'standard',
]]);
}
foreach (['field', 'filter', 'argument', 'sort'] as $handler_type) {
$view->addHandler('default', $handler_type, 'test_entity', 'test_field');
}
}
/**
* @covers ::addHandler
*/
public function testAddHandlerWithEntityField() {
/** @var \Drupal\views\ViewExecutable|\PHPUnit_Framework_MockObject_MockObject $view */
/** @var \Drupal\views\Plugin\views\display\DisplayPluginBase|\PHPUnit_Framework_MockObject_MockObject $display */
list($view, $display) = $this->setupBaseViewAndDisplay();
$views_data = [];
$views_data['table']['entity type'] = 'test_entity_type';
$views_data['test_field'] = [
'entity field' => 'test_field',
'field' => ['id' => 'standard'],
'filter' => ['id' => 'standard'],
'argument' => ['id' => 'standard'],
'sort' => ['id' => 'standard'],
];
$this->viewsData->expects($this->atLeastOnce())
->method('get')
->with('test_entity')
->willReturn($views_data);
foreach (['field', 'filter', 'argument', 'sort'] as $handler_type) {
$display->expects($this->atLeastOnce())
->method('setOption')
->with($this->callback(function($argument) {
return $argument;
}), ['test_field' => [
'id' => 'test_field',
'table' => 'test_entity',
'field' => 'test_field',
'entity_type' => 'test_entity_type',
'entity_field' => 'test_field',
'plugin_id' => 'standard',
]]);
}
foreach (['field', 'filter', 'argument', 'sort'] as $handler_type) {
$view->addHandler('default', $handler_type, 'test_entity', 'test_field');
}
}
/**
* @covers ::attachDisplays
*/
public function testAttachDisplays() {
/** @var \Drupal\views\ViewExecutable|\PHPUnit_Framework_MockObject_MockObject $view */
/** @var \Drupal\views\Plugin\views\display\DisplayPluginBase|\PHPUnit_Framework_MockObject_MockObject $display */
list($view, $display) = $this->setupBaseViewAndDisplay();
$display->expects($this->atLeastOnce())
->method('acceptAttachments')
->willReturn(TRUE);
$display->expects($this->atLeastOnce())
->method('getAttachedDisplays')
->willReturn(['page_1']);
$cloned_view = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$this->viewExecutableFactory->expects($this->atLeastOnce())
->method('get')
->willReturn($cloned_view);
$page_display = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$page_display->expects($this->atLeastOnce())
->method('isEnabled')
->willReturn(TRUE);
$display_collection = $this->getMockBuilder('Drupal\views\DisplayPluginCollection')
->disableOriginalConstructor()
->getMock();
$display_collection->expects($this->atLeastOnce())
->method('get')
->with('page_1')
->willReturn($page_display);
$view->displayHandlers = $display_collection;
// Setup the expectations.
$page_display->expects($this->once())
->method('attachTo')
->with($cloned_view, 'default', $view->element);
$view->attachDisplays();
}
/**
* Setups a view executable and default display.
*
* @return array
* Returns the view executable and default display.
*/
protected function setupBaseViewAndDisplay() {
$config = array(
'id' => 'test_view',
'tag' => 'OnE, TWO, and three',
'display' => [
'default' => [
'id' => 'default',
'display_plugin' => 'default',
'display_title' => 'Default',
],
],
);
$storage = new View($config, 'view');
$view = new ViewExecutable($storage, $this->user, $this->viewsData, $this->routeProvider);
$display = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$display->display = $config['display']['default'];
$view->current_display = 'default';
$view->display_handler = $display;
$view->displayHandlers = $this->displayHandlers;
$view->displayHandlers->expects($this->any())
->method('get')
->with('default')
->willReturn($display);
$view->displayHandlers->expects($this->any())
->method('has')
->with('default')
->willReturn(TRUE);
return array($view, $display);
}
}

View file

@ -0,0 +1,124 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\ViewsDataHelperTest.
*/
namespace Drupal\Tests\views\Unit;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Tests\UnitTestCase;
use Drupal\views\ViewsDataHelper;
use Drupal\views\Tests\ViewTestData;
/**
* @coversDefaultClass \Drupal\views\ViewsDataHelper
* @group views
*/
class ViewsDataHelperTest extends UnitTestCase {
/**
* Returns the views data definition.
*
* @return array
*/
protected function viewsData() {
$data = ViewTestData::viewsData();
// Tweak the views data to have a base for testing
// \Drupal\views\ViewsDataHelper::fetchFields().
unset($data['views_test_data']['id']['field']);
unset($data['views_test_data']['name']['argument']);
unset($data['views_test_data']['age']['filter']);
unset($data['views_test_data']['job']['sort']);
$data['views_test_data']['created']['area']['id'] = 'text';
$data['views_test_data']['age']['area']['id'] = 'text';
$data['views_test_data']['age']['area']['sub_type'] = 'header';
$data['views_test_data']['job']['area']['id'] = 'text';
$data['views_test_data']['job']['area']['sub_type'] = array('header', 'footer');
return $data;
}
/**
* Tests fetchFields.
*/
public function testFetchFields() {
$views_data = $this->getMockBuilder('Drupal\views\ViewsData')
->disableOriginalConstructor()
->getMock();
$views_data->expects($this->once())
->method('get')
->will($this->returnValue($this->viewsData()));
$data_helper = new ViewsDataHelper($views_data);
$expected = array(
'field' => array(
'age',
'created',
'job',
'name',
'status',
),
'argument' => array(
'age',
'created',
'id',
'job',
),
'filter' => array(
'created',
'id',
'job',
'name',
'status',
),
'sort' => array(
'age',
'created',
'id',
'name',
'status',
),
'area' => array(
'age',
'created',
'job',
),
'header' => array(
'age',
'created',
'job',
),
'footer' => array(
'age',
'created',
'job',
),
);
$handler_types = array('field', 'argument', 'filter', 'sort', 'area');
foreach ($handler_types as $handler_type) {
$fields = $data_helper->fetchFields('views_test_data', $handler_type);
$expected_keys = $expected[$handler_type];
array_walk($expected_keys, function(&$item) {
$item = "views_test_data.$item";
});
$this->assertEquals($expected_keys, array_keys($fields), SafeMarkup::format('Handlers of type @handler_type are not listed as expected.', array('@handler_type' => $handler_type)));
}
// Check for subtype filtering, so header and footer.
foreach (array('header', 'footer') as $sub_type) {
$fields = $data_helper->fetchFields('views_test_data', 'area', FALSE, $sub_type);
$expected_keys = $expected[$sub_type];
array_walk($expected_keys, function(&$item) {
$item = "views_test_data.$item";
});
$this->assertEquals($expected_keys, array_keys($fields), SafeMarkup::format('Sub_type @sub_type is not filtered as expected.', array('@sub_type' => $sub_type)));
}
}
}

View file

@ -0,0 +1,646 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\ViewsDataTest.
*/
namespace Drupal\Tests\views\Unit;
use Drupal\Core\Language\Language;
use Drupal\Tests\UnitTestCase;
use Drupal\views\ViewsData;
use Drupal\views\Tests\ViewTestData;
/**
* @coversDefaultClass \Drupal\views\ViewsData
* @group views
*/
class ViewsDataTest extends UnitTestCase {
/**
* The mocked cache backend.
*
* @var \Drupal\Core\Cache\CacheBackendInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $cacheBackend;
/**
* The mocked cache tags invalidator.
*
* @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $cacheTagsInvalidator;
/**
* The mocked module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $moduleHandler;
/**
* The mocked config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $configFactory;
/**
* The mocked language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $languageManager;
/**
* The tested views data class.
*
* @var \Drupal\views\ViewsData
*/
protected $viewsData;
/**
* {@inheritdoc}
*/
protected function setUp() {
$this->cacheTagsInvalidator = $this->getMock('Drupal\Core\Cache\CacheTagsInvalidatorInterface');
$this->cacheBackend = $this->getMock('Drupal\Core\Cache\CacheBackendInterface');
$this->getContainerWithCacheTagsInvalidator($this->cacheTagsInvalidator);
$configs = array();
$configs['views.settings']['skip_cache'] = FALSE;
$this->configFactory = $this->getConfigFactoryStub($configs);
$this->moduleHandler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');
$this->languageManager = $this->getMock('Drupal\Core\Language\LanguageManagerInterface');
$this->languageManager->expects($this->any())
->method('getCurrentLanguage')
->will($this->returnValue(new Language(array('id' => 'en'))));
$this->viewsData = new ViewsData($this->cacheBackend, $this->configFactory, $this->moduleHandler, $this->languageManager);
}
/**
* Returns the views data definition.
*/
protected function viewsData() {
$data = ViewTestData::viewsData();
// Tweak the views data to have a base for testing.
unset($data['views_test_data']['id']['field']);
unset($data['views_test_data']['name']['argument']);
unset($data['views_test_data']['age']['filter']);
unset($data['views_test_data']['job']['sort']);
$data['views_test_data']['created']['area']['id'] = 'text';
$data['views_test_data']['age']['area']['id'] = 'text';
$data['views_test_data']['age']['area']['sub_type'] = 'header';
$data['views_test_data']['job']['area']['id'] = 'text';
$data['views_test_data']['job']['area']['sub_type'] = array('header', 'footer');
// Duplicate the example views test data for different weight, different title,
// and matching data.
$data['views_test_data_2'] = $data['views_test_data'];
$data['views_test_data_2']['table']['base']['weight'] = 50;
$data['views_test_data_3'] = $data['views_test_data'];
$data['views_test_data_3']['table']['base']['weight'] = -50;
$data['views_test_data_4'] = $data['views_test_data'];
$data['views_test_data_4']['table']['base']['title'] = 'A different title';
$data['views_test_data_5'] = $data['views_test_data'];
$data['views_test_data_5']['table']['base']['title'] = 'Z different title';
$data['views_test_data_6'] = $data['views_test_data'];
return $data;
}
/**
* Returns the views data definition with the provider key.
*
* @return array
*
* @see static::viewsData()
*/
protected function viewsDataWithProvider() {
$views_data = static::viewsData();
foreach (array_keys($views_data) as $table) {
$views_data[$table]['table']['provider'] = 'views_test_data';
}
return $views_data;
}
/**
* Mocks the basic module handler used for the test.
*
* @return \Drupal\Core\Extension\ModuleHandlerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected function setupMockedModuleHandler() {
$views_data = $this->viewsData();
$this->moduleHandler->expects($this->at(0))
->method('getImplementations')
->with('views_data')
->willReturn(array('views_test_data'));
$this->moduleHandler->expects($this->at(1))
->method('invoke')
->with('views_test_data', 'views_data')
->willReturn($views_data);
}
/**
* Tests the fetchBaseTables() method.
*/
public function testFetchBaseTables() {
$this->setupMockedModuleHandler();
$data = $this->viewsData->get();
$base_tables = $this->viewsData->fetchBaseTables();
// Ensure that 'provider' is set for each base table.
foreach (array_keys($base_tables) as $base_table) {
$this->assertEquals('views_test_data', $data[$base_table]['table']['provider']);
}
// Test the number of tables returned and their order.
$this->assertCount(6, $base_tables, 'The correct amount of base tables were returned.');
$base_tables_keys = array_keys($base_tables);
for ($i = 1; $i < count($base_tables); ++$i) {
$prev = $base_tables[$base_tables_keys[$i - 1]];
$current = $base_tables[$base_tables_keys[$i]];
$this->assertTrue($prev['weight'] <= $current['weight'] && $prev['title'] <= $prev['title'], 'The tables are sorted as expected.');
}
// Test the values returned for each base table.
$defaults = array(
'title' => '',
'help' => '',
'weight' => 0,
);
foreach ($base_tables as $base_table => $info) {
// Merge in default values as in fetchBaseTables().
$expected = $data[$base_table]['table']['base'] += $defaults;
foreach ($defaults as $key => $default) {
$this->assertSame($info[$key], $expected[$key]);
}
}
}
/**
* Tests fetching all the views data without a static cache.
*/
public function testGetOnFirstCall() {
// Ensure that the hooks are just invoked once.
$this->setupMockedModuleHandler();
$this->moduleHandler->expects($this->at(2))
->method('alter')
->with('views_data', $this->viewsDataWithProvider());
$this->cacheBackend->expects($this->once())
->method('get')
->with("views_data:en")
->will($this->returnValue(FALSE));
$expected_views_data = $this->viewsDataWithProvider();
$views_data = $this->viewsData->get();
$this->assertSame($expected_views_data, $views_data);
}
/**
* Tests the cache of the full and single table data.
*/
public function testFullAndTableGetCache() {
$expected_views_data = $this->viewsDataWithProvider();
$table_name = 'views_test_data';
$table_name_2 = 'views_test_data_2';
$random_table_name = $this->randomMachineName();
// Views data should be invoked twice due to the clear call.
$this->moduleHandler->expects($this->at(0))
->method('getImplementations')
->with('views_data')
->willReturn(array('views_test_data'));
$this->moduleHandler->expects($this->at(1))
->method('invoke')
->with('views_test_data', 'views_data')
->willReturn($this->viewsData());
$this->moduleHandler->expects($this->at(2))
->method('alter')
->with('views_data', $expected_views_data);
$this->moduleHandler->expects($this->at(3))
->method('getImplementations')
->with('views_data')
->willReturn(array('views_test_data'));
$this->moduleHandler->expects($this->at(4))
->method('invoke')
->with('views_test_data', 'views_data')
->willReturn($this->viewsData());
$this->moduleHandler->expects($this->at(5))
->method('alter')
->with('views_data', $expected_views_data);
// The cache should only be called once (before the clear() call) as get
// will get all table data in the first get().
$this->cacheBackend->expects($this->at(0))
->method('get')
->with("views_data:en")
->will($this->returnValue(FALSE));
$this->cacheBackend->expects($this->at(1))
->method('set')
->with("views_data:en", $expected_views_data);
$this->cacheBackend->expects($this->at(2))
->method('get')
->with("views_data:$random_table_name:en")
->will($this->returnValue(FALSE));
$this->cacheBackend->expects($this->at(3))
->method('set')
->with("views_data:$random_table_name:en", array());
$this->cacheTagsInvalidator->expects($this->once())
->method('invalidateTags')
->with(['views_data']);
$this->cacheBackend->expects($this->at(4))
->method('get')
->with("views_data:en")
->will($this->returnValue(FALSE));
$this->cacheBackend->expects($this->at(5))
->method('set')
->with("views_data:en", $expected_views_data);
$this->cacheBackend->expects($this->at(6))
->method('get')
->with("views_data:$random_table_name:en")
->will($this->returnValue(FALSE));
$this->cacheBackend->expects($this->at(7))
->method('set')
->with("views_data:$random_table_name:en", array());
$views_data = $this->viewsData->get();
$this->assertSame($expected_views_data, $views_data);
// Request a specific table should be static cached.
$views_data = $this->viewsData->get($table_name);
$this->assertSame($expected_views_data[$table_name], $views_data);
// Another table being requested should also come from the static cache.
$views_data = $this->viewsData->get($table_name_2);
$this->assertSame($expected_views_data[$table_name_2], $views_data);
$views_data = $this->viewsData->get($random_table_name);
$this->assertSame(array(), $views_data);
$this->viewsData->clear();
// Get the views data again.
$this->viewsData->get();
$this->viewsData->get($table_name);
$this->viewsData->get($table_name_2);
$this->viewsData->get($random_table_name);
}
/**
* Tests the caching of the full views data.
*/
public function testFullGetCache() {
$expected_views_data = $this->viewsDataWithProvider();
// Views data should be invoked once.
$this->setupMockedModuleHandler();
$this->moduleHandler->expects($this->once())
->method('alter')
->with('views_data', $expected_views_data);
$this->cacheBackend->expects($this->once())
->method('get')
->with("views_data:en")
->will($this->returnValue(FALSE));
$views_data = $this->viewsData->get();
$this->assertSame($expected_views_data, $views_data);
$views_data = $this->viewsData->get();
$this->assertSame($expected_views_data, $views_data);
}
/**
* Tests the caching of the views data for a specific table.
*/
public function testSingleTableGetCache() {
$table_name = 'views_test_data';
$expected_views_data = $this->viewsDataWithProvider();
// Views data should be invoked once.
$this->setupMockedModuleHandler();
$this->moduleHandler->expects($this->once())
->method('alter')
->with('views_data', $this->viewsDataWithProvider());
$this->cacheBackend->expects($this->at(0))
->method('get')
->with("views_data:$table_name:en")
->will($this->returnValue(FALSE));
$this->cacheBackend->expects($this->at(1))
->method('get')
->with("views_data:en")
->will($this->returnValue(FALSE));
$views_data = $this->viewsData->get($table_name);
$this->assertSame($expected_views_data[$table_name], $views_data, 'Make sure fetching views data by table works as expected.');
$views_data = $this->viewsData->get($table_name);
$this->assertSame($expected_views_data[$table_name], $views_data, 'Make sure fetching cached views data by table works as expected.');
// Test that this data is present if all views data is returned.
$views_data = $this->viewsData->get();
$this->assertArrayHasKey($table_name, $views_data, 'Make sure the views_test_data info appears in the total views data.');
$this->assertSame($expected_views_data[$table_name], $views_data[$table_name], 'Make sure the views_test_data has the expected values.');
}
/**
* Tests building the views data with a non existing table.
*/
public function testNonExistingTableGetCache() {
$random_table_name = $this->randomMachineName();
// Views data should be invoked once.
$this->setupMockedModuleHandler();
$this->moduleHandler->expects($this->once())
->method('alter')
->with('views_data', $this->viewsDataWithProvider());
$this->cacheBackend->expects($this->at(0))
->method('get')
->with("views_data:$random_table_name:en")
->will($this->returnValue(FALSE));
$this->cacheBackend->expects($this->at(1))
->method('get')
->with("views_data:en")
->will($this->returnValue(FALSE));
// All views data should be requested on the first try.
$views_data = $this->viewsData->get($random_table_name);
$this->assertSame(array(), $views_data, 'Make sure fetching views data for an invalid table returns an empty array.');
// Test no data is rebuilt when requesting an invalid table again.
$views_data = $this->viewsData->get($random_table_name);
$this->assertSame(array(), $views_data, 'Make sure fetching views data for an invalid table returns an empty array.');
}
/**
* Tests the cache backend behavior with requesting the same table multiple
*/
public function testCacheCallsWithSameTableMultipleTimes() {
$expected_views_data = $this->viewsDataWithProvider();
$this->setupMockedModuleHandler();
$this->cacheBackend->expects($this->at(0))
->method('get')
->with('views_data:views_test_data:en');
$this->cacheBackend->expects($this->at(1))
->method('get')
->with('views_data:en');
$this->cacheBackend->expects($this->at(2))
->method('set')
->with('views_data:en', $expected_views_data);
$this->cacheBackend->expects($this->at(3))
->method('set')
->with('views_data:views_test_data:en', $expected_views_data['views_test_data']);
// Request the same table 5 times. The caches are empty at this point, so
// what will happen is that it will first check for a cache entry for the
// given table, get a cache miss, then try the cache entry for all tables,
// which does not exist yet either. As a result, it rebuilds the information
// and writes a cache entry for all tables and the requested table.
$table_name = 'views_test_data';
for ($i = 0; $i < 5; $i++) {
$views_data = $this->viewsData->get($table_name);
$this->assertSame($expected_views_data['views_test_data'], $views_data);
}
}
/**
* Tests the cache calls for a single table and warm cache for:
* - all tables
* - views_test_data
*/
public function testCacheCallsWithSameTableMultipleTimesAndWarmCache() {
$expected_views_data = $this->viewsDataWithProvider();
$this->moduleHandler->expects($this->never())
->method('getImplementations');
// Setup a warm cache backend for a single table.
$this->cacheBackend->expects($this->once())
->method('get')
->with('views_data:views_test_data:en')
->will($this->returnValue((object) array('data' => $expected_views_data['views_test_data'])));
$this->cacheBackend->expects($this->never())
->method('set');
// We have a warm cache now, so this will only request the tables-specific
// cache entry and return that.
for ($i = 0; $i < 5; $i++) {
$views_data = $this->viewsData->get('views_test_data');
$this->assertSame($expected_views_data['views_test_data'], $views_data);
}
}
/**
* Tests the cache calls for a different table than the one in cache:
*
* Warm cache:
* - all tables
* - views_test_data
* Not warm cache:
* - views_test_data_2
*/
public function testCacheCallsWithWarmCacheAndDifferentTable() {
$expected_views_data = $this->viewsDataWithProvider();
$this->moduleHandler->expects($this->never())
->method('getImplementations');
// Setup a warm cache backend for a single table.
$this->cacheBackend->expects($this->at(0))
->method('get')
->with('views_data:views_test_data_2:en');
$this->cacheBackend->expects($this->at(1))
->method('get')
->with('views_data:en')
->will($this->returnValue((object) array('data' => $expected_views_data)));
$this->cacheBackend->expects($this->at(2))
->method('set')
->with('views_data:views_test_data_2:en', $expected_views_data['views_test_data_2']);
// Requests a different table as the cache contains. This will fail to get a
// table specific cache entry, load the cache entry for all tables and save
// a cache entry for this table but not all.
for ($i = 0; $i < 5; $i++) {
$views_data = $this->viewsData->get('views_test_data_2');
$this->assertSame($expected_views_data['views_test_data_2'], $views_data);
}
}
/**
* Tests the cache calls for an not existing table:
*
* Warm cache:
* - all tables
* - views_test_data
* Not warm cache:
* - $non_existing_table
*/
public function testCacheCallsWithWarmCacheAndInvalidTable() {
$expected_views_data = $this->viewsDataWithProvider();
$non_existing_table = $this->randomMachineName();
$this->moduleHandler->expects($this->never())
->method('getImplementations');
// Setup a warm cache backend for a single table.
$this->cacheBackend->expects($this->at(0))
->method('get')
->with("views_data:$non_existing_table:en");
$this->cacheBackend->expects($this->at(1))
->method('get')
->with('views_data:en')
->will($this->returnValue((object) array('data' => $expected_views_data)));
$this->cacheBackend->expects($this->at(2))
->method('set')
->with("views_data:$non_existing_table:en", array());
// Initialize the views data cache and request a non-existing table. This
// will result in the same cache requests as we explicitly write an empty
// cache entry for non-existing tables to avoid unnecessary requests in
// those situations. We do have to load the cache entry for all tables to
// check if the table does exist or not.
for ($i = 0; $i < 5; $i++) {
$views_data = $this->viewsData->get($non_existing_table);
$this->assertSame(array(), $views_data);
}
}
/**
* Tests the cache calls for an not existing table:
*
* Warm cache:
* - all tables
* - views_test_data
* - $non_existing_table
*/
public function testCacheCallsWithWarmCacheForInvalidTable() {
$non_existing_table = $this->randomMachineName();
$this->moduleHandler->expects($this->never())
->method('getImplementations');
// Setup a warm cache backend for a single table.
$this->cacheBackend->expects($this->once())
->method('get')
->with("views_data:$non_existing_table:en")
->will($this->returnValue((object) array('data' => array())));
$this->cacheBackend->expects($this->never())
->method('set');
// Initialize the views data cache and request a non-existing table. This
// will result in the same cache requests as we explicitly write an empty
// cache entry for non-existing tables to avoid unnecessary requests in
// those situations. We do have to load the cache entry for all tables to
// check if the table does exist or not.
for ($i = 0; $i < 5; $i++) {
$views_data = $this->viewsData->get($non_existing_table);
$this->assertSame(array(), $views_data);
}
}
/**
* Tests the cache calls for all views data without a warm cache.
*/
public function testCacheCallsWithoutWarmCacheAndGetAllTables() {
$expected_views_data = $this->viewsDataWithProvider();
$this->setupMockedModuleHandler();
// Setup a warm cache backend for a single table.
$this->cacheBackend->expects($this->once())
->method('get')
->with("views_data:en");
$this->cacheBackend->expects($this->once())
->method('set')
->with('views_data:en', $expected_views_data);
// Initialize the views data cache and repeat with no specified table. This
// should only load the cache entry for all tables.
for ($i = 0; $i < 5; $i++) {
$views_data = $this->viewsData->get();
$this->assertSame($expected_views_data, $views_data);
}
}
/**
* Tests the cache calls for all views data.
*
* Warm cache:
* - all tables
*/
public function testCacheCallsWithWarmCacheAndGetAllTables() {
$expected_views_data = $this->viewsDataWithProvider();
$this->moduleHandler->expects($this->never())
->method('getImplementations');
// Setup a warm cache backend for a single table.
$this->cacheBackend->expects($this->once())
->method('get')
->with("views_data:en")
->will($this->returnValue((object) array('data' => $expected_views_data)));
$this->cacheBackend->expects($this->never())
->method('set');
// Initialize the views data cache and repeat with no specified table. This
// should only load the cache entry for all tables.
for ($i = 0; $i < 5; $i++) {
$views_data = $this->viewsData->get();
$this->assertSame($expected_views_data, $views_data);
}
}
/**
* Tests the cache calls for multiple tables without warm caches.
*
* @covers ::get
*/
public function testCacheCallsWithoutWarmCacheAndGetMultipleTables() {
$expected_views_data = $this->viewsDataWithProvider();
$table_name = 'views_test_data';
$table_name_2 = 'views_test_data_2';
// Setup a warm cache backend for all table data, but not single tables.
$this->cacheBackend->expects($this->at(0))
->method('get')
->with("views_data:$table_name:en")
->will($this->returnValue(FALSE));
$this->cacheBackend->expects($this->at(1))
->method('get')
->with('views_data:en')
->will($this->returnValue((object) array('data' => $expected_views_data)));
$this->cacheBackend->expects($this->at(2))
->method('set')
->with("views_data:$table_name:en", $expected_views_data[$table_name]);
$this->cacheBackend->expects($this->at(3))
->method('get')
->with("views_data:$table_name_2:en")
->will($this->returnValue(FALSE));
$this->cacheBackend->expects($this->at(4))
->method('set')
->with("views_data:$table_name_2:en", $expected_views_data[$table_name_2]);
$this->assertSame($expected_views_data[$table_name], $this->viewsData->get($table_name));
$this->assertSame($expected_views_data[$table_name_2], $this->viewsData->get($table_name_2));
// Should only be invoked the first time.
$this->assertSame($expected_views_data[$table_name], $this->viewsData->get($table_name));
$this->assertSame($expected_views_data[$table_name_2], $this->viewsData->get($table_name_2));
}
}

View file

@ -0,0 +1,183 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\ViewsHandlerManagerTest.
*/
namespace Drupal\Tests\views\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\ViewsHandlerManager;
/**
* Tests the ViewsHandlerManager class.
*
* @group views
*
* @coversDefaultClass \Drupal\views\Plugin\ViewsHandlerManager
*/
class ViewsHandlerManagerTest extends UnitTestCase {
/**
* @var \Drupal\views\Plugin\ViewsHandlerManager
*/
protected $handlerManager;
/**
* @var \Drupal\Core\Extension\ModuleHandlerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $moduleHandler;
/**
* The mocked views data.
*
* @var \Drupal\views\ViewsData|\PHPUnit_Framework_MockObject_MockObject
*/
protected $viewsData;
/**
* The mocked factory.
*
* @var \Drupal\Component\Plugin\Factory\FactoryInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $factory;
/**
* {@inheritdoc}
*/
public function setUp() {
$this->viewsData = $this->getMockBuilder('Drupal\views\ViewsData')
->disableOriginalConstructor()
->getMock();
$cache_backend = $this->getMock('Drupal\Core\Cache\CacheBackendInterface');
$this->moduleHandler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');
$this->handlerManager = new ViewsHandlerManager('test', new \ArrayObject(array()), $this->viewsData, $cache_backend, $this->moduleHandler);
}
/**
* Setups of the plugin factory.
*/
protected function setupMockedFactory() {
$this->factory = $this->getMock('Drupal\Component\Plugin\Factory\FactoryInterface');
$reflection = new \ReflectionClass($this->handlerManager);
$property = $reflection->getProperty('factory');
$property->setAccessible(TRUE);
$property->setValue($this->handlerManager, $this->factory);
}
/**
* Tests that hook_views_plugins_TYPE_alter() is invoked for a handler type.
*
* @covers ::__construct
* @covers ::getDefinitions
*/
public function testAlterHookInvocation() {
$this->moduleHandler->expects($this->once())
->method('alter')
->with('views_plugins_test', array());
$this->handlerManager->getDefinitions();
}
/**
* Tests getHandler() and its base information propagation.
*/
public function testGetHandlerBaseInformationPropagation() {
$this->setupMockedFactory();
$item = [];
$item['table'] = 'test_table';
$item['field'] = 'test_field';
$views_data = [];
$views_data['test_field']['test']['id'] = 'test_id';
$views_data['test_field']['test']['more_information'] = 'test_id';
$views_data['test_field']['group'] = 'test_group';
$views_data['test_field']['title'] = 'test title';
$views_data['test_field']['real field'] = 'test real field';
$views_data['test_field']['real table'] = 'test real table';
$views_data['test_field']['entity field'] = 'test entity field';
$this->viewsData->expects($this->once())
->method('get')
->with('test_table')
->willReturn($views_data);
$expected_definition = [
'id' => 'test_id',
'more_information' => 'test_id',
'group' => 'test_group',
'title' => 'test title',
'real field' => 'test real field',
'real table' => 'test real table',
'entity field' => 'test entity field',
];
$plugin = $this->getMock('Drupal\views\Plugin\views\ViewsHandlerInterface');
$this->factory->expects($this->once())
->method('createInstance')
->with('test_id', $expected_definition)
->willReturn($plugin);
$result = $this->handlerManager->getHandler($item);
$this->assertSame($plugin, $result);
}
/**
* Tests getHandler() with an override.
*/
public function testGetHandlerOverride() {
$this->setupMockedFactory();
$item = [];
$item['table'] = 'test_table';
$item['field'] = 'test_field';
$views_data = [];
$views_data['test_field']['test']['id'] = 'test_id';
$this->viewsData->expects($this->once())
->method('get')
->with('test_table')
->willReturn($views_data);
$plugin = $this->getMock('Drupal\views\Plugin\views\ViewsHandlerInterface');
$this->factory->expects($this->once())
->method('createInstance')
->with('test_override')
->willReturn($plugin);
$result = $this->handlerManager->getHandler($item, 'test_override');
$this->assertSame($plugin, $result);
}
/**
* Tests getHandler() without an override.
*/
public function testGetHandlerNoOverride() {
$this->setupMockedFactory();
$item = [];
$item['table'] = 'test_table';
$item['field'] = 'test_field';
$views_data = [];
$views_data['test_field']['test']['id'] = 'test_id';
$this->viewsData->expects($this->once())
->method('get')
->with('test_table')
->willReturn($views_data);
$plugin = $this->getMock('Drupal\views\Plugin\views\ViewsHandlerInterface');
$this->factory->expects($this->once())
->method('createInstance')
->with('test_id')
->willReturn($plugin);
$result = $this->handlerManager->getHandler($item);
$this->assertSame($plugin, $result);
}
}

View file

@ -0,0 +1,206 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\ViewsTest.
*/
namespace Drupal\Tests\views\Unit;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Views;
use Drupal\views\Entity\View;
use Drupal\views\ViewExecutableFactory;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* @coversDefaultClass \Drupal\views\Views
* @group views
*/
class ViewsTest extends UnitTestCase {
/**
* The test container.
*
* @var \Drupal\Core\DependencyInjection\ContainerBuilder
*/
protected $container;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->container = new ContainerBuilder();
$user = $this->getMock('Drupal\Core\Session\AccountInterface');
$request_stack = new RequestStack();
$request_stack->push(new Request());
$views_data = $this->getMockBuilder('Drupal\views\ViewsData')
->disableOriginalConstructor()
->getMock();
$route_provider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface');
$this->container->set('views.executable', new ViewExecutableFactory($user, $request_stack, $views_data, $route_provider));
\Drupal::setContainer($this->container);
}
/**
* Tests the getView() method.
*
* @covers ::getView
*/
public function testGetView() {
$view = new View(['id' => 'test_view'], 'view');
$view_storage = $this->getMockBuilder('Drupal\Core\Config\Entity\ConfigEntityStorage')
->disableOriginalConstructor()
->getMock();
$view_storage->expects($this->once())
->method('load')
->with('test_view')
->will($this->returnValue($view));
$entity_manager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface');
$entity_manager->expects($this->once())
->method('getStorage')
->with('view')
->will($this->returnValue($view_storage));
$this->container->set('entity.manager', $entity_manager);
$executable = Views::getView('test_view');
$this->assertInstanceOf('Drupal\views\ViewExecutable', $executable);
$this->assertEquals($view->id(), $executable->storage->id());
$this->assertEquals(spl_object_hash($view), spl_object_hash($executable->storage));
}
/**
* @covers ::getApplicableViews
*
* @dataProvider providerTestGetApplicableViews
*/
public function testGetApplicableViews($applicable_type, $expected) {
$view_1 = new View([
'id' => 'test_view_1',
'display' => [
'default' => [
'display_plugin' => 'default',
'display_options' => [],
],
'type_a' => [
'display_plugin' => 'type_a',
'display_options' => [],
],
],
], 'view');
$view_2 = new View([
'id' => 'test_view_2',
'display' => [
'default' => [
'display_plugin' => 'default',
'display_options' => [],
],
'type_b' => [
'display_plugin' => 'type_b',
'display_options' => [
'enabled' => TRUE,
],
],
'type_b_2' => [
'display_plugin' => 'type_b',
'display_options' => [
'enabled' => FALSE,
],
],
],
], 'view');
$view_3 = new View([
'id' => 'test_view_3',
'display' => [
'default' => [
'display_plugin' => 'default',
'display_options' => [],
],
// Test with Type A but a disabled display.
'type_a' => [
'display_plugin' => 'type_a',
'display_options' => [
'enabled' => FALSE
],
],
// Type D intentionally doesn't exist.
'type_d' => [
'display_plugin' => 'type_d',
'display_options' => [],
],
],
], 'view');
$query = $this->getMock('Drupal\Core\Entity\Query\QueryInterface');
$query->expects($this->exactly(2))
->method('condition')
->willReturnSelf();
$query->expects($this->once())
->method('execute')
->willReturn(['test_view_1', 'test_view_2', 'test_view_3']);
$view_storage = $this->getMockBuilder('Drupal\Core\Config\Entity\ConfigEntityStorage')
->disableOriginalConstructor()
->getMock();
$view_storage->expects($this->once())
->method('getQuery')
->willReturn($query);
$view_storage->expects($this->once())
->method('loadMultiple')
->with(['test_view_1', 'test_view_2', 'test_view_3'])
->will($this->returnValue(['test_view_1' => $view_1, 'test_view_2' => $view_2, 'test_view_3' => $view_3]));
$entity_manager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface');
$entity_manager->expects($this->exactly(2))
->method('getStorage')
->with('view')
->will($this->returnValue($view_storage));
$this->container->set('entity.manager', $entity_manager);
$definitions = [
'type_a' => [
'type_a' => TRUE,
'type_b' => FALSE,
],
'type_b' => [
'type_a' => FALSE,
'type_b' => TRUE,
],
];
$display_manager = $this->getMock('Drupal\Component\Plugin\PluginManagerInterface');
$display_manager->expects($this->once())
->method('getDefinitions')
->willReturn($definitions);
$this->container->set('plugin.manager.views.display', $display_manager);
$entity_query = new QueryFactory($entity_manager);
$this->container->set('entity.query', $entity_query);
$result = Views::getApplicableViews($applicable_type);
$this->assertEquals($expected, $result);
}
/**
* Data provider for testGetApplicableViews.
*
* @return array
*/
public function providerTestGetApplicableViews() {
return [
['type_a', [['test_view_1', 'type_a']]],
['type_b', [['test_view_2', 'type_b']]],
['type_c', []],
];
}
}

View file

@ -0,0 +1,112 @@
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\WizardPluginBaseTest.
*/
namespace Drupal\Tests\views\Unit;
use Drupal\Core\Form\FormState;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\wizard\WizardPluginBase;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\wizard\WizardPluginBase
*
* @group views
*/
class WizardPluginBaseTest extends UnitTestCase {
/**
* @covers ::getSelected
*
* @dataProvider providerTestGetSelected
*/
public function testGetSelected($expected, $element = [], $parents = [], $user_input = [], $not_rebuilding_expected = NULL) {
$not_rebuilding_expected = $not_rebuilding_expected ?: $expected;
$form_state = new FormState();
$form_state->setUserInput($user_input);
$actual = WizardPluginBase::getSelected($form_state, $parents, 'the_default_value', $element);
$this->assertSame($not_rebuilding_expected, $actual);
$this->assertSame($user_input, $form_state->getUserInput());
$form_state->setRebuild();
$actual = WizardPluginBase::getSelected($form_state, $parents, 'the_default_value', $element);
$this->assertSame($expected, $actual);
$this->assertSame($user_input, $form_state->getUserInput());
}
/**
* Provides test data for testGetSelected().
*/
public function providerTestGetSelected() {
$data = [];
// A form element with an invalid #type.
$data['invalid_type'] = [
'the_default_value',
[
'#type' => 'checkbox',
],
];
// A form element with no #options.
$data['no_options'] = [
'the_default_value',
[
'#type' => 'select',
],
];
// A valid form element with no user input.
$data['no_user_input'] = [
'the_default_value',
[
'#type' => 'select',
'#options' => [
'option1' => 'Option 1',
],
],
];
// A valid form element with user input that doesn't correspond to it.
$data['mismatched_input'] = [
'the_default_value',
[
'#type' => 'select',
'#options' => [
'option1' => 'Option 1',
],
],
['foo', 'bar'],
['foo' => ['foo' => 'value1']],
];
// A valid form element with a valid dynamic value that matches the default
// value.
$data['matching_default'] = [
'the_default_value',
[
'#type' => 'select',
'#options' => [
'the_default_value' => 'Option 1',
],
],
['foo', 'bar'],
['foo' => ['bar' => 'the_default_value']],
];
// A valid form element with a valid dynamic value that does not match the
// default value.
$data['mismatched_value'] = [
'option1',
[
'#type' => 'select',
'#options' => [
'option1' => 'Option 1',
],
],
['foo', 'bar'],
['foo' => ['bar' => 'option1']],
'the_default_value',
];
return $data;
}
}