/** * Tests using entity fields of the field field type. */ public function testTestItem() { // Verify entity creation. $entity = entity_create('entity_test'); $value = rand(1, 10); $entity->field_test = $value; $entity->name->value = $this->randomName(); $entity->save(); // Verify entity has been created properly. $id = $entity->id(); $entity = entity_load('entity_test', $id); $this->assertTrue($entity->{$this->field_name} instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->{$this->field_name}[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->{$this->field_name}->value, $value); $this->assertEqual($entity->{$this->field_name}[0]->value, $value); // Verify changing the field value. $new_value = rand(1, 10); $entity->field_test->value = $new_value; $this->assertEqual($entity->{$this->field_name}->value, $new_value); // Read changed entity and assert changed values. $entity->save(); $entity = entity_load('entity_test', $id); $this->assertEqual($entity->{$this->field_name}->value, $new_value); // Test the schema for this field type. $expected_schema = array('columns' => array('value' => array('type' => 'int', 'size' => 'medium', 'not null' => FALSE)), 'unique keys' => array(), 'indexes' => array('value' => array('value')), 'foreign keys' => array()); $field_schema = FieldDefinition::create('test_field')->getSchema(); $this->assertEqual($field_schema, $expected_schema); }
public function testRecreateEntity() { $type_name = Unicode::strtolower($this->randomMachineName(16)); $content_type = entity_create('node_type', array('type' => $type_name, 'name' => 'Node type one')); $content_type->save(); node_add_body_field($content_type); /** @var \Drupal\Core\Config\StorageInterface $active */ $active = $this->container->get('config.storage'); /** @var \Drupal\Core\Config\StorageInterface $sync */ $sync = $this->container->get('config.storage.sync'); $config_name = $content_type->getEntityType()->getConfigPrefix() . '.' . $content_type->id(); $this->copyConfig($active, $sync); // Delete the content type. This will also delete a field storage, a field, // an entity view display and an entity form display. $content_type->delete(); $this->assertFalse($active->exists($config_name), 'Content type\'s old name does not exist active store.'); // Recreate with the same type - this will have a different UUID. $content_type = entity_create('node_type', array('type' => $type_name, 'name' => 'Node type two')); $content_type->save(); node_add_body_field($content_type); $this->configImporter->reset(); // A node type, a field, an entity view display and an entity form display // will be recreated. $creates = $this->configImporter->getUnprocessedConfiguration('create'); $deletes = $this->configImporter->getUnprocessedConfiguration('delete'); $this->assertEqual(5, count($creates), 'There are 5 configuration items to create.'); $this->assertEqual(5, count($deletes), 'There are 5 configuration items to delete.'); $this->assertEqual(0, count($this->configImporter->getUnprocessedConfiguration('update')), 'There are no configuration items to update.'); $this->assertIdentical($creates, array_reverse($deletes), 'Deletes and creates contain the same configuration names in opposite orders due to dependencies.'); $this->configImporter->import(); // Verify that there is nothing more to import. $this->assertFalse($this->configImporter->reset()->hasUnprocessedConfigurationChanges()); $content_type = NodeType::load($type_name); $this->assertEqual('Node type one', $content_type->label()); }
/** * Tests field item attributes. */ public function testFieldItemAttributes() { // Make sure the test field will be rendered. entity_get_display('entity_test', 'entity_test', 'default')->setComponent('field_test_text', array('type' => 'text_default'))->save(); // Create an entity and save test value in field_test_text. $test_value = $this->randomMachineName(); $entity = entity_create('entity_test'); $entity->field_test_text = $test_value; $entity->save(); // Browse to the entity and verify that the attribute is rendered in the // field item HTML markup. $this->drupalGet('entity_test/' . $entity->id()); $xpath = $this->xpath('//div[@data-field-item-attr="foobar"]/p[text()=:value]', array(':value' => $test_value)); $this->assertTrue($xpath, 'The field item attribute has been found in the rendered output of the field.'); // Enable the RDF module to ensure that two modules can add attributes to // the same field item. \Drupal::service('module_installer')->install(array('rdf')); $this->resetAll(); // Set an RDF mapping for the field_test_text field. This RDF mapping will // be turned into RDFa attributes in the field item output. $mapping = rdf_get_mapping('entity_test', 'entity_test'); $mapping->setFieldMapping('field_test_text', array('properties' => array('schema:text')))->save(); // Browse to the entity and verify that the attributes from both modules // are rendered in the field item HTML markup. $this->drupalGet('entity_test/' . $entity->id()); $xpath = $this->xpath('//div[@data-field-item-attr="foobar" and @property="schema:text"]/p[text()=:value]', array(':value' => $test_value)); $this->assertTrue($xpath, 'The field item attributes from both modules have been found in the rendered output of the field.'); }
/** * Verifies that a transaction rolls back the failed creation. */ function testFailedPageCreation() { // Create a node. $edit = array('uid' => $this->loggedInUser->id(), 'name' => $this->loggedInUser->name, 'type' => 'page', 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'title' => 'testing_transaction_exception'); try { // An exception is generated by node_test_exception_node_insert() if the // title is 'testing_transaction_exception'. entity_create('node', $edit)->save(); $this->fail(t('Expected exception has not been thrown.')); } catch (\Exception $e) { $this->pass(t('Expected exception has been thrown.')); } if (Database::getConnection()->supportsTransactions()) { // Check that the node does not exist in the database. $node = $this->drupalGetNodeByTitle($edit['title']); $this->assertFalse($node, 'Transactions supported, and node not found in database.'); } else { // Check that the node exists in the database. $node = $this->drupalGetNodeByTitle($edit['title']); $this->assertTrue($node, 'Transactions not supported, and node found in database.'); // Check that the failed rollback was logged. $records = db_query("SELECT wid FROM {watchdog} WHERE message LIKE 'Explicit rollback failed%'")->fetchAll(); $this->assertTrue(count($records) > 0, 'Transactions not supported, and rollback error logged to watchdog.'); } // Check that the rollback error was logged. $records = db_query("SELECT wid FROM {watchdog} WHERE variables LIKE '%Test exception for rollback.%'")->fetchAll(); $this->assertTrue(count($records) > 0, 'Rollback explanatory error logged to watchdog.'); }
/** * Assert sorting by field and property. */ public function testSort() { // Add text field to entity, to sort by. entity_create('field_storage_config', array('field_name' => 'field_text', 'entity_type' => 'node', 'type' => 'text', 'entity_types' => array('node')))->save(); entity_create('field_config', array('label' => 'Text Field', 'field_name' => 'field_text', 'entity_type' => 'node', 'bundle' => 'article', 'settings' => array(), 'required' => FALSE))->save(); // Build a set of test data. $node_values = array('published1' => array('type' => 'article', 'status' => 1, 'title' => 'Node published1 (<&>)', 'uid' => 1, 'field_text' => array(array('value' => 1))), 'published2' => array('type' => 'article', 'status' => 1, 'title' => 'Node published2 (<&>)', 'uid' => 1, 'field_text' => array(array('value' => 2)))); $nodes = array(); $node_labels = array(); foreach ($node_values as $key => $values) { $node = Node::create($values); $node->save(); $nodes[$key] = $node; $node_labels[$key] = SafeMarkup::checkPlain($node->label()); } $selection_options = array('target_type' => 'node', 'handler' => 'default', 'handler_settings' => array('target_bundles' => array(), 'sort' => array('field' => 'field_text.value', 'direction' => 'DESC'))); $handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options); // Not only assert the result, but make sure the keys are sorted as // expected. $result = $handler->getReferenceableEntities(); $expected_result = array($nodes['published2']->id() => $node_labels['published2'], $nodes['published1']->id() => $node_labels['published1']); $this->assertIdentical($result['article'], $expected_result, 'Query sorted by field returned expected values.'); // Assert sort by base field. $selection_options['handler_settings']['sort'] = array('field' => 'nid', 'direction' => 'ASC'); $handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options); $result = $handler->getReferenceableEntities(); $expected_result = array($nodes['published1']->id() => $node_labels['published1'], $nodes['published2']->id() => $node_labels['published2']); $this->assertIdentical($result['article'], $expected_result, 'Query sorted by property returned expected values.'); }
/** * Tests that default values are correctly translated to UUIDs in config. */ function testEntityReferenceDefaultValue() { // Create a node to be referenced. $referenced_node = $this->drupalCreateNode(array('type' => 'referenced_content')); $field_name = drupal_strtolower($this->randomMachineName()); $field_storage = entity_create('field_storage_config', array('field_name' => $field_name, 'entity_type' => 'node', 'type' => 'entity_reference', 'settings' => array('target_type' => 'node'))); $field_storage->save(); $field = entity_create('field_config', array('field_storage' => $field_storage, 'bundle' => 'reference_content', 'settings' => array('handler' => 'default', 'handler_settings' => array('target_bundles' => array('referenced_content'), 'sort' => array('field' => '_none'))))); $field->save(); // Set created node as default_value. $field_edit = array('default_value_input[' . $field_name . '][0][target_id]' => $referenced_node->getTitle() . ' (' . $referenced_node->id() . ')'); $this->drupalPostForm('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name, $field_edit, t('Save settings')); // Check that default value is selected in default value form. $this->drupalGet('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name); $this->assertRaw('name="default_value_input[' . $field_name . '][0][target_id]" value="' . $referenced_node->getTitle() . ' (' . $referenced_node->id() . ')', 'The default value is selected in instance settings page'); // Check if the ID has been converted to UUID in config entity. $config_entity = $this->container->get('config.factory')->get('field.field.node.reference_content.' . $field_name)->get(); $this->assertTrue(isset($config_entity['default_value'][0]['target_uuid']), 'Default value contains target_uuid property'); $this->assertEqual($config_entity['default_value'][0]['target_uuid'], $referenced_node->uuid(), 'Content uuid and config entity uuid are the same'); // Ensure the configuration has the expected dependency on the entity that // is being used a default value. $this->assertEqual(array($referenced_node->getConfigDependencyName()), $config_entity['dependencies']['content']); // Clear field definitions cache in order to avoid stale cache values. \Drupal::entityManager()->clearCachedFieldDefinitions(); // Create a new node to check that UUID has been converted to numeric ID. $new_node = entity_create('node', array('type' => 'reference_content')); $this->assertEqual($new_node->get($field_name)->offsetGet(0)->target_id, $referenced_node->id()); }
protected function setUp() { parent::setUp(); $this->entityStorage = $this->entityManager->getStorage('entity_test'); $this->factory = $this->container->get('entity.query'); // Add some fieldapi fields to be used in the test. for ($i = 1; $i <= 2; $i++) { $field_name = 'field_test_' . $i; entity_create('field_storage_config', array('field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => 'integer', 'cardinality' => 2))->save(); entity_create('field_config', array('field_name' => $field_name, 'entity_type' => 'entity_test', 'bundle' => 'entity_test'))->save(); } $entity = $this->entityStorage->create(array('id' => 1, 'user_id' => 1, 'field_test_1' => 1, 'field_test_2' => 2)); $entity->enforceIsNew(); $entity->save(); $entity = $this->entityStorage->create(array('id' => 2, 'user_id' => 2, 'field_test_1' => 1, 'field_test_2' => 7)); $entity->enforceIsNew(); $entity->save(); $entity = $this->entityStorage->create(array('id' => 3, 'user_id' => 2, 'field_test_1' => 2, 'field_test_2' => 1)); $entity->enforceIsNew(); $entity->save(); $entity = $this->entityStorage->create(array('id' => 4, 'user_id' => 2, 'field_test_1' => 2, 'field_test_2' => 8)); $entity->enforceIsNew(); $entity->save(); $entity = $this->entityStorage->create(array('id' => 5, 'user_id' => 3, 'field_test_1' => 2, 'field_test_2' => 2)); $entity->enforceIsNew(); $entity->save(); $entity = $this->entityStorage->create(array('id' => 6, 'user_id' => 3, 'field_test_1' => 3, 'field_test_2' => 8)); $entity->enforceIsNew(); $entity->save(); }
function testMenuTokens() { // Add a menu. $menu = entity_create('menu', array('id' => 'main-menu', 'label' => 'Main menu', 'description' => 'The <em>Main</em> menu is used on many sites to show the major sections of the site, often in a top navigation bar.')); $menu->save(); // Add a root link. /** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $root_link */ $root_link = entity_create('menu_link_content', array('link' => ['uri' => 'internal:/admin'], 'title' => 'Administration', 'menu_name' => 'main-menu')); $root_link->save(); // Add another link with the root link as the parent. /** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $parent_link */ $parent_link = entity_create('menu_link_content', array('link' => ['uri' => 'internal:/admin/config'], 'title' => 'Configuration', 'menu_name' => 'main-menu', 'parent' => $root_link->getPluginId())); $parent_link->save(); // Test menu link tokens. $tokens = array('id' => $parent_link->getPluginId(), 'title' => 'Configuration', 'menu' => 'Main menu', 'menu:name' => 'Main menu', 'menu:machine-name' => $menu->id(), 'menu:description' => 'The <em>Main</em> menu is used on many sites to show the major sections of the site, often in a top navigation bar.', 'menu:menu-link-count' => '2', 'menu:edit-url' => \Drupal::url('entity.menu.edit_form', ['menu' => 'main-menu'], array('absolute' => TRUE)), 'url' => \Drupal::url('system.admin_config', [], array('absolute' => TRUE)), 'url:absolute' => \Drupal::url('system.admin_config', [], array('absolute' => TRUE)), 'url:relative' => \Drupal::url('system.admin_config', [], array('absolute' => FALSE)), 'url:path' => 'admin/config', 'url:alias' => 'admin/config', 'edit-url' => \Drupal::url('entity.menu_link_content.canonical', ['menu_link_content' => $parent_link->id()], array('absolute' => TRUE)), 'parent' => 'Administration', 'parent:id' => $root_link->getPluginId(), 'parent:title' => 'Administration', 'parent:menu' => 'Main menu', 'parent:parent' => NULL, 'parents' => 'Administration', 'parents:count' => 1, 'parents:keys' => $root_link->getPluginId(), 'root' => 'Administration', 'root:id' => $root_link->getPluginId(), 'root:parent' => NULL, 'root:root' => NULL); $this->assertTokens('menu-link', array('menu-link' => $parent_link), $tokens); // Add a node. $node = $this->drupalCreateNode(); // Allow main menu for this node type. //$this->config('menu.entity.node.' . $node->getType())->set('available_menus', array('main-menu'))->save(); // Add a node menu link. /** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $node_link */ $node_link = entity_create('menu_link_content', array('link' => ['uri' => 'entity:node/' . $node->id()], 'title' => 'Node link', 'parent' => $parent_link->getPluginId(), 'menu_name' => 'main-menu')); $node_link->save(); // Test [node:menu] tokens. $tokens = array('menu-link' => 'Node link', 'menu-link:id' => $node_link->getPluginId(), 'menu-link:title' => 'Node link', 'menu-link:menu' => 'Main menu', 'menu-link:url' => $node->url('canonical', ['absolute' => TRUE]), 'menu-link:url:path' => 'node/' . $node->id(), 'menu-link:edit-url' => $node_link->url('edit-form', ['absolute' => TRUE]), 'menu-link:parent' => 'Configuration', 'menu-link:parent:id' => $parent_link->getPluginId(), 'menu-link:parents' => 'Administration, Configuration', 'menu-link:parents:count' => 2, 'menu-link:parents:keys' => $root_link->getPluginId() . ', ' . $parent_link->getPluginId(), 'menu-link:root' => 'Administration', 'menu-link:root:id' => $root_link->getPluginId()); $this->assertTokens('node', array('node' => $node), $tokens); // Reload the node which will not have $node->menu defined and re-test. $loaded_node = Node::load($node->id()); $this->assertTokens('node', array('node' => $loaded_node), $tokens); // Regression test for http://drupal.org/node/1317926 to ensure the // original node object is not changed when calling menu_node_prepare(). $this->assertTrue(!isset($loaded_node->menu), t('The $node->menu property was not modified during token replacement.'), 'Regression'); }
protected function setUp() { parent::setUp(); $this->installEntitySchema('taxonomy_term'); // We want an entity reference field. It needs a vocabulary, terms, a field // storage and a field. First, create the vocabulary. $vocabulary = entity_create('taxonomy_vocabulary', array('vid' => Unicode::strtolower($this->randomMachineName()))); $vocabulary->save(); // Second, create the field. entity_test_create_bundle('test_bundle'); $this->fieldName = strtolower($this->randomMachineName()); $handler_settings = array('target_bundles' => array($vocabulary->id() => $vocabulary->id()), 'auto_create' => TRUE); $this->createEntityReferenceField('entity_test', 'test_bundle', $this->fieldName, NULL, 'taxonomy_term', 'default', $handler_settings); // Create two terms and also two accounts. for ($i = 0; $i <= 1; $i++) { $term = entity_create('taxonomy_term', array('name' => $this->randomMachineName(), 'vid' => $vocabulary->id())); $term->save(); $this->terms[] = $term; $this->accounts[] = $this->createUser(); } // Create three entity_test entities, the 0th entity will point to the // 0th account and 0th term, the 1st and 2nd entity will point to the // 1st account and 1st term. for ($i = 0; $i <= 2; $i++) { $entity = entity_create('entity_test', array('type' => 'test_bundle')); $entity->name->value = $this->randomMachineName(); $index = $i ? 1 : 0; $entity->user_id->target_id = $this->accounts[$index]->id(); $entity->{$this->fieldName}->target_id = $this->terms[$index]->id(); $entity->save(); $this->entities[] = $entity; } $this->factory = \Drupal::service('entity.query'); }
/** * Tests the bubbling of cache tags. */ public function testCacheTags() { // Create the entity that will be commented upon. $commented_entity = entity_create('entity_test', array('name' => $this->randomMachineName())); $commented_entity->save(); // Verify cache tags on the rendered entity before it has comments. $build = \Drupal::entityManager()->getViewBuilder('entity_test')->view($commented_entity); drupal_render($build); $expected_cache_tags = array('entity_test_view', 'entity_test:' . $commented_entity->id(), 'comment_list'); sort($expected_cache_tags); $this->assertEqual($build['#cache']['tags'], $expected_cache_tags, 'The test entity has the expected cache tags before it has comments.'); // Create a comment on that entity. Comment loading requires that the uid // also exists in the {users} table. $user = $this->createUser(); $user->save(); $comment = entity_create('comment', array('subject' => 'Llama', 'comment_body' => array('value' => 'Llamas are cool!', 'format' => 'plain_text'), 'entity_id' => $commented_entity->id(), 'entity_type' => 'entity_test', 'field_name' => 'comment', 'comment_type' => 'comment', 'status' => CommentInterface::PUBLISHED, 'uid' => $user->id())); $comment->save(); // Load commented entity so comment_count gets computed. // @todo Remove the $reset = TRUE parameter after // https://www.drupal.org/node/597236 lands. It's a temporary work-around. $commented_entity = entity_load('entity_test', $commented_entity->id(), TRUE); // Verify cache tags on the rendered entity when it has comments. $build = \Drupal::entityManager()->getViewBuilder('entity_test')->view($commented_entity); drupal_render($build); $expected_cache_tags = array('entity_test_view', 'entity_test:' . $commented_entity->id(), 'comment_list', 'comment_view', 'comment:' . $comment->id(), 'config:filter.format.plain_text', 'user_view', 'user:2'); sort($expected_cache_tags); $this->assertEqual($build['#cache']['tags'], $expected_cache_tags, 'The test entity has the expected cache tags when it has comments.'); }
protected function setUp() { parent::setUp(); $this->addDefaultCommentField('node', 'page'); $web_user = $this->drupalCreateUser(array('edit own page content', 'create page content')); $this->drupalLogin($web_user); // Add a vocabulary so we can test different view modes. $vocabulary = entity_create('taxonomy_vocabulary', array('name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'vid' => $this->randomMachineName(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'help' => '')); $vocabulary->save(); $this->vocabulary = $vocabulary; // Add a term to the vocabulary. $term = entity_create('taxonomy_term', array('name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'vid' => $this->vocabulary->id(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED)); $term->save(); $this->term = $term; // Create an image field. FieldStorageConfig::create(['field_name' => 'field_image', 'entity_type' => 'node', 'type' => 'image', 'settings' => [], 'cardinality' => FieldStorageConfig::CARDINALITY_UNLIMITED])->save(); $field_config = FieldConfig::create(['field_name' => 'field_image', 'label' => 'Images', 'entity_type' => 'node', 'bundle' => 'page', 'required' => FALSE, 'settings' => []]); $field_config->save(); // Create a field. $this->fieldName = Unicode::strtolower($this->randomMachineName()); $handler_settings = array('target_bundles' => array($this->vocabulary->id() => $this->vocabulary->id()), 'auto_create' => TRUE); $this->createEntityReferenceField('node', 'page', $this->fieldName, 'Tags', 'taxonomy_term', 'default', $handler_settings, FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED); entity_get_form_display('node', 'page', 'default')->setComponent($this->fieldName, array('type' => 'entity_reference_autocomplete_tags'))->save(); // Show on default display and teaser. entity_get_display('node', 'page', 'default')->setComponent($this->fieldName, array('type' => 'entity_reference_label'))->save(); entity_get_display('node', 'page', 'teaser')->setComponent($this->fieldName, array('type' => 'entity_reference_label'))->save(); entity_get_form_display('node', 'page', 'default')->setComponent('field_image', array('type' => 'image_image', 'settings' => []))->save(); entity_get_display('node', 'page', 'default')->setComponent('field_image')->save(); }
protected function setUp() { parent::setUp(); // Enable user signatures. \Drupal::config('user.settings')->set('signatures', 1)->save(); // Create Basic page node type. $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page')); // Add a comment field with commenting enabled by default. $this->container->get('comment.manager')->addDefaultField('node', 'page'); // Prefetch and create text formats. $this->filtered_html_format = entity_create('filter_format', array('format' => 'filtered_html_format', 'name' => 'Filtered HTML', 'weight' => -1, 'filters' => array('filter_html' => array('module' => 'filter', 'status' => TRUE, 'settings' => array('allowed_html' => '<a> <em> <strong>'))))); $this->filtered_html_format->save(); $this->full_html_format = entity_create('filter_format', array('format' => 'full_html', 'name' => 'Full HTML')); $this->full_html_format->save(); user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, array($this->filtered_html_format->getPermissionName())); // Create regular and administrative users. $this->web_user = $this->drupalCreateUser(array('post comments')); $admin_permissions = array('post comments', 'administer comments', 'administer user form display', 'administer account settings'); foreach (filter_formats() as $format) { if ($permission = $format->getPermissionName()) { $admin_permissions[] = $permission; } } $this->admin_user = $this->drupalCreateUser($admin_permissions); }
/** * Tests the configurable text editor manager. */ public function testManager() { $this->editorManager = $this->container->get('plugin.manager.editor'); // Case 1: no text editor available: // - listOptions() should return an empty list of options // - getAttachments() should return an empty #attachments array (and not // a JS settings structure that is empty) $this->assertIdentical(array(), $this->editorManager->listOptions(), 'When no text editor is enabled, the manager works correctly.'); $this->assertIdentical(array(), $this->editorManager->getAttachments(array()), 'No attachments when no text editor is enabled and retrieving attachments for zero text formats.'); $this->assertIdentical(array(), $this->editorManager->getAttachments(array('filtered_html', 'full_html')), 'No attachments when no text editor is enabled and retrieving attachments for multiple text formats.'); // Enable the Text Editor Test module, which has the Unicorn Editor and // clear the editor manager's cache so it is picked up. $this->enableModules(array('editor_test')); $this->editorManager = $this->container->get('plugin.manager.editor'); $this->editorManager->clearCachedDefinitions(); // Case 2: a text editor available. $this->assertIdentical('Unicorn Editor', (string) $this->editorManager->listOptions()['unicorn'], 'When some text editor is enabled, the manager works correctly.'); // Case 3: a text editor available & associated (but associated only with // the 'Full HTML' text format). $unicorn_plugin = $this->editorManager->createInstance('unicorn'); $editor = entity_create('editor', array('format' => 'full_html', 'editor' => 'unicorn')); $editor->save(); $this->assertIdentical(array(), $this->editorManager->getAttachments(array()), 'No attachments when one text editor is enabled and retrieving attachments for zero text formats.'); $expected = array('library' => array(0 => 'editor_test/unicorn'), 'drupalSettings' => ['editor' => ['formats' => ['full_html' => ['format' => 'full_html', 'editor' => 'unicorn', 'editorSettings' => $unicorn_plugin->getJSSettings($editor), 'editorSupportsContentFiltering' => TRUE, 'isXssSafe' => FALSE]]]]); $this->assertIdentical($expected, $this->editorManager->getAttachments(array('filtered_html', 'full_html')), 'Correct attachments when one text editor is enabled and retrieving attachments for multiple text formats.'); // Case 4: a text editor available associated, but now with its JS settings // being altered via hook_editor_js_settings_alter(). \Drupal::state()->set('editor_test_js_settings_alter_enabled', TRUE); $expected['drupalSettings']['editor']['formats']['full_html']['editorSettings']['ponyModeEnabled'] = FALSE; $this->assertIdentical($expected, $this->editorManager->getAttachments(array('filtered_html', 'full_html')), 'hook_editor_js_settings_alter() works correctly.'); }
/** * Tests the views_ui_autocomplete_tag function. */ public function testViewsUiAutocompleteTag() { \Drupal::moduleHandler()->loadInclude('views_ui', 'inc', 'admin'); // Save 15 views with a tag. $tags = array(); for ($i = 0; $i < 16; $i++) { $suffix = $i % 2 ? 'odd' : 'even'; $tag = 'autocomplete_tag_test_' . $suffix . $this->randomMachineName(); $tags[] = $tag; entity_create('view', array('tag' => $tag, 'id' => $this->randomMachineName()))->save(); } // Make sure just ten results are returns. $controller = ViewsUIController::create($this->container); $request = $this->container->get('request_stack')->getCurrentRequest(); $request->query->set('q', 'autocomplete_tag_test'); $result = $controller->autocompleteTag($request); $matches = (array) json_decode($result->getContent()); $this->assertEqual(count($matches), 10, 'Make sure the maximum amount of tag results is 10.'); // Make sure that matching by a certain prefix works. $request->query->set('q', 'autocomplete_tag_test_even'); $result = $controller->autocompleteTag($request); $matches = (array) json_decode($result->getContent()); $this->assertEqual(count($matches), 8, 'Make sure that only a subset is returned.'); foreach ($matches as $tag) { $this->assertTrue(array_search($tag, $tags) !== FALSE, format_string('Make sure the returned tag @tag actually exists.', array('@tag' => $tag))); } // Make sure an invalid result doesn't return anything. $request->query->set('q', $this->randomMachineName()); $result = $controller->autocompleteTag($request); $matches = (array) json_decode($result->getContent()); $this->assertEqual(count($matches), 0, "Make sure an invalid tag doesn't return anything."); }
/** * Verifies that a transaction rolls back the failed creation. */ function testFailedTicketCreation() { // Create a support_ticket. $edit = array('uid' => $this->loggedInUser->id(), 'name' => $this->loggedInUser->name, 'support_ticket_type' => 'ticket', 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'title' => 'testing_transaction_exception'); try { // An exception is generated by support_ticket_test_exception_support_ticket_insert() if the // title is 'testing_transaction_exception'. entity_create('support_ticket', $edit)->save(); $this->fail(t('Expected exception has not been thrown.')); } catch (\Exception $e) { $this->pass(t('Expected exception has been thrown.')); } if (Database::getConnection()->supportsTransactions()) { // Check that the support_ticket does not exist in the database. $support_ticket = $this->supportTicketGetTicketByTitle($edit['title']); $this->assertFalse($support_ticket, 'Transactions supported, and support_ticket not found in database.'); } else { // Check that the support_ticket exists in the database. $support_ticket = $this->supportTicketGetTicketByTitle($edit['title']); $this->assertTrue($support_ticket, 'Transactions not supported, and support_ticket found in database.'); // Check that the failed rollback was logged. $records = static::getWatchdogIdsForFailedExplicitRollback(); $this->assertTrue(count($records) > 0, 'Transactions not supported, and rollback error logged to watchdog.'); } // Check that the rollback error was logged. $records = static::getWatchdogIdsForTestExceptionRollback(); $this->assertTrue(count($records) > 0, 'Rollback explanatory error logged to watchdog.'); }
/** * Creates taxonomy vocabulary with custom fields. * * To create and attach fields it internally calls * TMGMTEntityTestCaseUtility::attachFields(). You can than access these * fields calling $this->field_names['node']['YOUR_BUNDLE_NAME']. * * @param string $vid * Vocabulary id. * @param string $human_name * Vocabulary human readable name. * @param bool|array $fields_translatable * Flag or definition array to determine which or all fields should be * translatable. * * @return stdClass * Created vocabulary object. */ function createTaxonomyVocab($machine_name, $human_name, $fields_translatable = TRUE) { $vocabulary = entity_create('taxonomy_vocabulary', array('name' => $human_name, 'vid' => $machine_name)); $vocabulary->save(); $this->attachFields('taxonomy_term', $vocabulary->id(), $fields_translatable); return $vocabulary; }
/** * Displays the 'Add new entity_test' form. * * @param string $entity_type * Name of the entity type for which a create form should be displayed. * * @return array * The processed form for a new entity_test. * * @see \Drupal\entity_test\Routing\EntityTestRoutes::routes() */ public function testAdd($entity_type) { $entity = entity_create($entity_type, array()); $form = $this->entityFormBuilder()->getForm($entity); $form['#title'] = $this->t('Create an @type', array('@type' => $entity_type)); return $form; }
/** * Tests CRUD operations for text formats and filters. */ function testTextFormatCrud() { // Add a text format with minimum data only. $format = entity_create('filter_format'); $format->format = 'empty_format'; $format->name = 'Empty format'; $format->save(); $this->verifyTextFormat($format); // Add another text format specifying all possible properties. $format = entity_create('filter_format', array('format' => 'custom_format', 'name' => 'Custom format')); $format->setFilterConfig('filter_url', array('status' => 1, 'settings' => array('filter_url_length' => 30))); $format->save(); $this->verifyTextFormat($format); // Alter some text format properties and save again. $format->name = 'Altered format'; $format->setFilterConfig('filter_url', array('status' => 0)); $format->setFilterConfig('filter_autop', array('status' => 1)); $format->save(); $this->verifyTextFormat($format); // Add a filter_test_replace filter and save again. $format->setFilterConfig('filter_test_replace', array('status' => 1)); $format->save(); $this->verifyTextFormat($format); // Disable the text format. $format->disable()->save(); $formats = filter_formats(); $this->assertTrue(!isset($formats[$format->format]), 'filter_formats: Disabled text format no longer exists.'); }
/** * Creates a node, then tests the tokens generated from it. */ function testNodeTokenReplacement() { $url_options = array('absolute' => TRUE, 'language' => $this->interfaceLanguage); // Create a user and a node. $account = $this->createUser(); /* @var $node \Drupal\node\NodeInterface */ $node = entity_create('node', array('type' => 'article', 'tnid' => 0, 'uid' => $account->id(), 'title' => '<blink>Blinking Text</blink>', 'body' => array(array('value' => $this->randomMachineName(32), 'summary' => $this->randomMachineName(16), 'format' => 'plain_text')))); $node->save(); // Generate and test sanitized tokens. $tests = array(); $tests['[node:nid]'] = $node->id(); $tests['[node:vid]'] = $node->getRevisionId(); $tests['[node:type]'] = 'article'; $tests['[node:type-name]'] = 'Article'; $tests['[node:title]'] = SafeMarkup::checkPlain($node->getTitle()); $tests['[node:body]'] = $node->body->processed; $tests['[node:summary]'] = $node->body->summary_processed; $tests['[node:langcode]'] = SafeMarkup::checkPlain($node->language()->getId()); $tests['[node:url]'] = $node->url('canonical', $url_options); $tests['[node:edit-url]'] = $node->url('edit-form', $url_options); $tests['[node:author]'] = SafeMarkup::checkPlain($account->getUsername()); $tests['[node:author:uid]'] = $node->getOwnerId(); $tests['[node:author:name]'] = SafeMarkup::checkPlain($account->getUsername()); $tests['[node:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($node->getCreatedTime(), array('langcode' => $this->interfaceLanguage->getId())); $tests['[node:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($node->getChangedTime(), array('langcode' => $this->interfaceLanguage->getId())); // Test to make sure that we generated something for each token. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.'); foreach ($tests as $input => $expected) { $output = $this->tokenService->replace($input, array('node' => $node), array('langcode' => $this->interfaceLanguage->getId())); $this->assertEqual($output, $expected, format_string('Sanitized node token %token replaced.', array('%token' => $input))); } // Generate and test unsanitized tokens. $tests['[node:title]'] = $node->getTitle(); $tests['[node:body]'] = $node->body->value; $tests['[node:summary]'] = $node->body->summary; $tests['[node:langcode]'] = $node->language()->getId(); $tests['[node:author:name]'] = $account->getUsername(); foreach ($tests as $input => $expected) { $output = $this->tokenService->replace($input, array('node' => $node), array('langcode' => $this->interfaceLanguage->getId(), 'sanitize' => FALSE)); $this->assertEqual($output, $expected, format_string('Unsanitized node token %token replaced.', array('%token' => $input))); } // Repeat for a node without a summary. $node = entity_create('node', array('type' => 'article', 'uid' => $account->id(), 'title' => '<blink>Blinking Text</blink>', 'body' => array(array('value' => $this->randomMachineName(32), 'format' => 'plain_text')))); $node->save(); // Generate and test sanitized token - use full body as expected value. $tests = array(); $tests['[node:summary]'] = $node->body->processed; // Test to make sure that we generated something for each token. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated for node without a summary.'); foreach ($tests as $input => $expected) { $output = $this->tokenService->replace($input, array('node' => $node), array('language' => $this->interfaceLanguage)); $this->assertEqual($output, $expected, format_string('Sanitized node token %token replaced for node without a summary.', array('%token' => $input))); } // Generate and test unsanitized tokens. $tests['[node:summary]'] = $node->body->value; foreach ($tests as $input => $expected) { $output = $this->tokenService->replace($input, array('node' => $node), array('language' => $this->interfaceLanguage, 'sanitize' => FALSE)); $this->assertEqual($output, $expected, format_string('Unsanitized node token %token replaced for node without a summary.', array('%token' => $input))); } }
function addTerm($vocabulary, array $term = array()) { $term += array('name' => Unicode::strtolower($this->randomMachineName(5)), 'vid' => $vocabulary->id()); $term = entity_create('taxonomy_term', $term); $term->save(); return $term; }
/** * Tests using entity fields of the telephone field type. */ public function testTestItem() { // Verify entity creation. $entity = entity_create('entity_test'); $value = '+0123456789'; $entity->field_test = $value; $entity->name->value = $this->randomMachineName(); $entity->save(); // Verify entity has been created properly. $id = $entity->id(); $entity = entity_load('entity_test', $id); $this->assertTrue($entity->field_test instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->field_test[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->field_test->value, $value); $this->assertEqual($entity->field_test[0]->value, $value); // Verify changing the field value. $new_value = '+41' . rand(1000000, 9999999); $entity->field_test->value = $new_value; $this->assertEqual($entity->field_test->value, $new_value); // Read changed entity and assert changed values. $entity->save(); $entity = entity_load('entity_test', $id); $this->assertEqual($entity->field_test->value, $new_value); // Test sample item generation. $entity = entity_create('entity_test'); $entity->field_test->generateSampleItems(); $this->entityValidateAndSave($entity); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); // Create a test entity. $random_label = $this->randomMachineName(); $data = array('type' => 'entity_test', 'name' => $random_label); $this->entity = entity_create('entity_test', $data); $this->entity->save(); // Create a test entity with only canonical route. $random_label = $this->randomMachineName(); $data = array('type' => 'devel_entity_test_canonical', 'name' => $random_label); $this->entity_canonical = entity_create('devel_entity_test_canonical', $data); $this->entity_canonical->save(); // Create a test entity with only edit route. $random_label = $this->randomMachineName(); $data = array('type' => 'devel_entity_test_edit', 'name' => $random_label); $this->entity_edit = entity_create('devel_entity_test_edit', $data); $this->entity_edit->save(); // Create a test entity with no routes. $random_label = $this->randomMachineName(); $data = array('type' => 'devel_entity_test_no_links', 'name' => $random_label); $this->entity_no_links = entity_create('devel_entity_test_no_links', $data); $this->entity_no_links->save(); $this->drupalPlaceBlock('local_tasks_block'); $web_user = $this->drupalCreateUser(array('view test entity', 'administer entity_test content', 'access devel information')); $this->drupalLogin($web_user); }
/** * Tests the calculateDependencies method. */ public function testCalculateDependencies() { $comment_type = entity_create('comment_type', array('id' => 'comment', 'label' => 'Comment settings', 'description' => 'Comment settings', 'target_entity_type_id' => 'node')); $comment_type->save(); $content_type = entity_create('node_type', array('type' => $this->randomMachineName(), 'name' => $this->randomString())); $content_type->save(); $field_storage = entity_create('field_storage_config', array('field_name' => Unicode::strtolower($this->randomMachineName()), 'entity_type' => 'node', 'type' => 'comment')); $field_storage->save(); entity_create('field_config', array('field_storage' => $field_storage, 'bundle' => $content_type->id(), 'label' => $this->randomMachineName() . '_label', 'description' => $this->randomMachineName() . '_description', 'settings' => array('comment_type' => $comment_type->id())))->save(); entity_create('field_config', array('field_storage' => FieldStorageConfig::loadByName('node', 'body'), 'bundle' => $content_type->id(), 'label' => $this->randomMachineName() . '_body', 'settings' => array('display_summary' => TRUE)))->save(); $expected = []; $expected['test_field_get_entity'] = ['module' => ['comment', 'node', 'user']]; // Tests dependencies of relationships. $expected['test_relationship_dependency'] = ['module' => ['comment', 'node', 'user']]; $expected['test_plugin_dependencies'] = ['module' => ['comment', 'views_test_data'], 'content' => ['RowTest', 'StaticTest', 'StyleTest']]; $expected['test_argument_dependency'] = ['config' => ['core.entity_view_mode.node.teaser', 'field.storage.node.body'], 'content' => ['ArgumentDefaultTest', 'ArgumentValidatorTest'], 'module' => ['node', 'search', 'text', 'user']]; foreach ($this::$testViews as $view_id) { $view = Views::getView($view_id); $dependencies = $view->calculateDependencies(); $this->assertEqual($expected[$view_id], $dependencies); $config = $this->config('views.view.' . $view_id); \Drupal::service('config.storage.staging')->write($view_id, $config->get()); } // Ensure that dependencies are calculated on the display level. $expected_display['default'] = ['config' => ['core.entity_view_mode.node.teaser'], 'content' => ['ArgumentDefaultTest', 'ArgumentValidatorTest'], 'module' => ['core', 'node', 'search', 'user', 'views']]; $expected_display['page'] = ['config' => ['field.storage.node.body'], 'module' => ['core', 'text', 'views']]; $view = Views::getView('test_argument_dependency'); $view->initDisplay(); foreach ($view->displayHandlers as $display) { // Calculate the dependencies each display has. $this->assertEqual($expected_display[$display->getPluginId()], $display->calculateDependencies()); } }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->installEntitySchema('file'); $this->installSchema('file', ['file_usage']); // Create the user profile field and instance. entity_create('field_storage_config', array('entity_type' => 'user', 'field_name' => 'user_picture', 'type' => 'image', 'translatable' => '0'))->save(); entity_create('field_config', array('label' => 'User Picture', 'description' => '', 'field_name' => 'user_picture', 'entity_type' => 'user', 'bundle' => 'user', 'required' => 0))->save(); $file = entity_create('file', array('fid' => 2, 'uid' => 2, 'filename' => 'image-test.jpg', 'uri' => "public://image-test.jpg", 'filemime' => 'image/jpeg', 'created' => 1, 'changed' => 1, 'status' => FILE_STATUS_PERMANENT)); $file->enforceIsNew(); file_put_contents($file->getFileUri(), file_get_contents('core/modules/simpletest/files/image-1.png')); $file->save(); $file = entity_create('file', array('fid' => 8, 'uid' => 8, 'filename' => 'image-test.png', 'uri' => "public://image-test.png", 'filemime' => 'image/png', 'created' => 1, 'changed' => 1, 'status' => FILE_STATUS_PERMANENT)); $file->enforceIsNew(); file_put_contents($file->getFileUri(), file_get_contents('core/modules/simpletest/files/image-2.jpg')); $file->save(); // Load database dumps to provide source data. $dumps = array($this->getDumpDirectory() . '/Filters.php', $this->getDumpDirectory() . '/FilterFormats.php', $this->getDumpDirectory() . '/Variable.php', $this->getDumpDirectory() . '/ProfileFields.php', $this->getDumpDirectory() . '/Permission.php', $this->getDumpDirectory() . '/Role.php', $this->getDumpDirectory() . '/Users.php', $this->getDumpDirectory() . '/ProfileValues.php', $this->getDumpDirectory() . '/UsersRoles.php', $this->getDumpDirectory() . '/EventTimezones.php'); $this->loadDumps($dumps); $id_mappings = array('d6_user_role' => array(array(array(1), array('anonymous user')), array(array(2), array('authenticated user')), array(array(3), array('migrate test role 1')), array(array(4), array('migrate test role 2')), array(array(5), array('migrate test role 3'))), 'd6_user_picture_entity_display' => array(array(array(1), array('user', 'user', 'default', 'user_picture'))), 'd6_user_picture_entity_form_display' => array(array(array(1), array('user', 'user', 'default', 'user_picture'))), 'd6_user_picture_file' => array(array(array(2), array(2)), array(array(8), array(8)))); $this->prepareMigrations($id_mappings); // Migrate users. $migration = entity_load('migration', 'd6_user'); $executable = new MigrateExecutable($migration, $this); $executable->import(); }
/** * Create a simple hierarchy of links. */ function createLinkHierarchy($module = 'menu_test') { // First remove all the menu links in the menu. $this->menuLinkManager->deleteLinksInMenu('menu_test'); // Then create a simple link hierarchy: // - parent // - child-1 // - child-1-1 // - child-1-2 // - child-2 $base_options = array('title' => 'Menu link test', 'provider' => $module, 'menu_name' => 'menu_test', 'bundle' => 'menu_link_content'); $parent = $base_options + array('route_name' => 'menu_test.hierarchy_parent'); $link = entity_create('menu_link_content', $parent); $link->save(); $links['parent'] = $link->getPluginId(); $child_1 = $base_options + array('route_name' => 'menu_test.hierarchy_parent_child', 'parent' => $links['parent']); $link = entity_create('menu_link_content', $child_1); $link->save(); $links['child-1'] = $link->getPluginId(); $child_1_1 = $base_options + array('route_name' => 'menu_test.hierarchy_parent_child2', 'parent' => $links['child-1']); $link = entity_create('menu_link_content', $child_1_1); $link->save(); $links['child-1-1'] = $link->getPluginId(); $child_1_2 = $base_options + array('route_name' => 'menu_test.hierarchy_parent_child2', 'parent' => $links['child-1']); $link = entity_create('menu_link_content', $child_1_2); $link->save(); $links['child-1-2'] = $link->getPluginId(); $child_2 = $base_options + array('route_name' => 'menu_test.hierarchy_parent_child', 'parent' => $links['parent']); $link = entity_create('menu_link_content', $child_2); $link->save(); $links['child-2'] = $link->getPluginId(); return $links; }
function setUp() { parent::setUp(); $this->type = entity_create('profile_type', [ 'id' => 'personal', 'label' => 'Personal data', 'weight' => 0, 'registration' => TRUE, ]); $this->type->save(); $this->checkPermissions([], TRUE); $this->admin_user = $this->drupalCreateUser([ 'access user profiles', 'administer profile types', 'administer profile fields', 'administer profile display', 'bypass profile access', ]); $user_permissions = [ 'access user profiles', 'add own personal profile', 'edit own personal profile', 'view any personal profile', ]; $this->web_user = $this->drupalCreateUser($user_permissions); $this->other_user = $this->drupalCreateUser($user_permissions); }
/** * Tests the missing content event is fired. * * @see \Drupal\Core\Config\ConfigImporter::processMissingContent() * @see \Drupal\config_import_test\EventSubscriber */ function testMissingContent() { \Drupal::state()->set('config_import_test.config_import_missing_content', TRUE); // Update a configuration entity in the sync directory to have a dependency // on two content entities that do not exist. $storage = $this->container->get('config.storage'); $sync = $this->container->get('config.storage.sync'); $entity_one = entity_create('entity_test', array('name' => 'one')); $entity_two = entity_create('entity_test', array('name' => 'two')); $entity_three = entity_create('entity_test', array('name' => 'three')); $dynamic_name = 'config_test.dynamic.dotted.default'; $original_dynamic_data = $storage->read($dynamic_name); // Entity one will be resolved by // \Drupal\config_import_test\EventSubscriber::onConfigImporterMissingContentOne(). $original_dynamic_data['dependencies']['content'][] = $entity_one->getConfigDependencyName(); // Entity two will be resolved by // \Drupal\config_import_test\EventSubscriber::onConfigImporterMissingContentTwo(). $original_dynamic_data['dependencies']['content'][] = $entity_two->getConfigDependencyName(); // Entity three will be resolved by // \Drupal\Core\Config\Importer\FinalMissingContentSubscriber. $original_dynamic_data['dependencies']['content'][] = $entity_three->getConfigDependencyName(); $sync->write($dynamic_name, $original_dynamic_data); // Import. $this->configImporter->reset()->import(); $this->assertEqual([], $this->configImporter->getErrors(), 'There were no errors during the import.'); $this->assertEqual($entity_one->uuid(), \Drupal::state()->get('config_import_test.config_import_missing_content_one'), 'The missing content event is fired during configuration import.'); $this->assertEqual($entity_two->uuid(), \Drupal::state()->get('config_import_test.config_import_missing_content_two'), 'The missing content event is fired during configuration import.'); $original_dynamic_data = $storage->read($dynamic_name); $this->assertEqual([$entity_one->getConfigDependencyName(), $entity_two->getConfigDependencyName(), $entity_three->getConfigDependencyName()], $original_dynamic_data['dependencies']['content'], 'The imported configuration entity has the missing content entity dependency.'); }
/** * Tests basic context definition and value getters and setters. */ function testContext() { $this->installEntitySchema('user'); $name = $this->randomMachineName(); $manager = new MockBlockManager(); $plugin = $manager->createInstance('user_name'); // Create a node, add it as context, catch the exception. $node = entity_create('node', array('title' => $name, 'type' => 'page')); // Try to get context that is missing its definition. try { $plugin->getContextDefinition('not_exists'); $this->fail('The user context should not yet be set.'); } catch (ContextException $e) { $this->assertEqual($e->getMessage(), 'The not_exists context is not a valid context.'); } // Test the getContextDefinitions() method. $user_context_definition = ContextDefinition::create('entity:user')->setLabel(t('User')); $this->assertEqual($plugin->getContextDefinitions()['user']->getLabel(), $user_context_definition->getLabel()); // Test the getContextDefinition() method for a valid context. $this->assertEqual($plugin->getContextDefinition('user')->getLabel(), $user_context_definition->getLabel()); // Try to get a context with valid definition. $this->assertNotNull($plugin->getContext('user'), 'Succeeded to get a context with a valid definition.'); // Try to get a value of a valid context, while this value has not been set. try { $plugin->getContextValue('user'); } catch (ContextException $e) { $this->assertIdentical("The 'entity:user' context is required and not present.", $e->getMessage(), 'Requesting a non-set value of a required context should throw a context exception.'); } // Try to pass the wrong class type as a context value. $plugin->setContextValue('user', $node); $violations = $plugin->validateContexts(); $this->assertTrue(!empty($violations), 'The provided context value does not pass validation.'); // Set an appropriate context value and check to make sure its methods work // as expected. $user = entity_create('user', array('name' => $name)); $plugin->setContextValue('user', $user); $this->assertEqual($plugin->getContextValue('user')->getUsername(), $user->getUsername()); $this->assertEqual($user->label(), $plugin->getTitle()); // Test Optional context handling. $plugin = $manager->createInstance('user_name_optional'); $this->assertNull($plugin->getContextValue('user'), 'Requesting a non-set value of a valid context should return NULL.'); // Test Complex compound context handling. $complex_plugin = $manager->createInstance('complex_context'); $complex_plugin->setContextValue('user', $user); // With only the user context set, try to get the context values. $values = $complex_plugin->getContextValues(); $this->assertNull($values['node'], 'The node context is not yet set.'); $this->assertNotNull($values['user'], 'The user context is set'); $complex_plugin->setContextValue('node', $node); $context_wrappers = $complex_plugin->getContexts(); // Make sure what came out of the wrappers is good. $this->assertEqual($context_wrappers['user']->getContextValue()->label(), $user->label()); $this->assertEqual($context_wrappers['node']->getContextValue()->label(), $node->label()); // Make sure what comes out of the context values is good. $contexts = $complex_plugin->getContextValues(); $this->assertEqual($contexts['user']->label(), $user->label()); $this->assertEqual($contexts['node']->label(), $node->label()); // Test the title method for the complex context plugin. $this->assertEqual($user->label() . ' -- ' . $node->label(), $complex_plugin->getTitle()); }
/** * Test the behavior of a field module after being disabled and re-enabled. */ function testReEnabledField() { // Add a telephone field to the article content type. $field_storage = entity_create('field_storage_config', array('name' => 'field_telephone', 'entity_type' => 'node', 'type' => 'telephone')); $field_storage->save(); entity_create('field_instance_config', array('field_storage' => $field_storage, 'bundle' => 'article', 'label' => 'Telephone Number'))->save(); entity_get_form_display('node', 'article', 'default')->setComponent('field_telephone', array('type' => 'telephone_default', 'settings' => array('placeholder' => '123-456-7890')))->save(); entity_get_display('node', 'article', 'default')->setComponent('field_telephone', array('type' => 'telephone_link', 'weight' => 1))->save(); // Display the article node form and verify the telephone widget is present. $this->drupalGet('node/add/article'); $this->assertFieldByName("field_telephone[0][value]", '', 'Widget found.'); // Submit an article node with a telephone field so data exist for the // field. $edit = array('title[0][value]' => $this->randomName(), 'field_telephone[0][value]' => "123456789"); $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertRaw('<a href="tel:123456789">'); // Test that the module can't be uninstalled from the UI while there is data // for it's fields. $admin_user = $this->drupalCreateUser(array('access administration pages', 'administer modules')); $this->drupalLogin($admin_user); $this->drupalGet('admin/modules'); $this->assertText('Fields type(s) in use'); $field_storage->delete(); $this->drupalGet('admin/modules'); $this->assertText('Fields pending deletion'); $this->cronRun(); $this->assertNoText('Fields type(s) in use'); $this->assertNoText('Fields pending deletion'); }
/** * Tests the getEntity method. */ public function testGetEntity() { // The view is a view of comments, their nodes and their authors, so there // are three layers of entities. $account = entity_create('user', array('name' => $this->randomMachineName(), 'bundle' => 'user')); $account->save(); $this->drupalCreateContentType(array('type' => 'page')); $this->addDefaultCommentField('node', 'page'); $node = entity_create('node', array('uid' => $account->id(), 'type' => 'page')); $node->save(); $comment = entity_create('comment', array('uid' => $account->id(), 'entity_id' => $node->id(), 'entity_type' => 'node', 'field_name' => 'comment')); $comment->save(); $view = Views::getView('test_field_get_entity'); $this->executeView($view); $row = $view->result[0]; // Tests entities on the base level. $entity = $view->field['cid']->getEntity($row); $this->assertEqual($entity->id(), $comment->id(), 'Make sure the right comment entity got loaded.'); // Tests entities as relationship on first level. $entity = $view->field['nid']->getEntity($row); $this->assertEqual($entity->id(), $node->id(), 'Make sure the right node entity got loaded.'); // Tests entities as relationships on second level. $entity = $view->field['uid']->getEntity($row); $this->assertEqual($entity->id(), $account->id(), 'Make sure the right user entity got loaded.'); }