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.');
}
/**
* 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());
}
/**
* 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.');
}
/**
* 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.');
}
/**
* 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.');
}
/**
* 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.');
}
请发表评论