Update Composer, update everything

This commit is contained in:
Oliver Davies 2018-11-23 12:29:20 +00:00
parent ea3e94409f
commit dda5c284b6
19527 changed files with 1135420 additions and 351004 deletions

View file

@ -5,4 +5,4 @@ package: Testing
version: VERSION
core: 8.x
dependencies:
- comment
- drupal:comment

View file

@ -5,4 +5,4 @@ package: Testing
version: VERSION
core: 8.x
dependencies:
- comment
- drupal:comment

View file

@ -5,5 +5,5 @@ package: Testing
version: VERSION
core: 8.x
dependencies:
- comment
- views
- drupal:comment
- drupal:views

View file

@ -0,0 +1,120 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\node\Entity\NodeType;
use Drupal\Tests\BrowserTestBase;
/**
* Tests comment administration and preview access.
*
* @group comment
*/
class CommentAccessTest extends BrowserTestBase {
use CommentTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = [
'node',
'comment',
];
/**
* Node for commenting.
*
* @var \Drupal\node\NodeInterface
*/
protected $unpublishedNode;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$node_type = NodeType::create([
'type' => 'article',
'name' => 'Article',
]);
$node_type->save();
$node_author = $this->drupalCreateUser([
'create article content',
'access comments',
]);
$this->drupalLogin($this->drupalCreateUser([
'edit own comments',
'skip comment approval',
'post comments',
'access comments',
'access content',
]));
$this->addDefaultCommentField('node', 'article');
$this->unpublishedNode = $this->createNode([
'title' => 'This is unpublished',
'uid' => $node_author->id(),
'status' => 0,
'type' => 'article',
]);
$this->unpublishedNode->save();
}
/**
* Tests commenting disabled for access-blocked entities.
*/
public function testCannotCommentOnEntitiesYouCannotView() {
$assert = $this->assertSession();
$comment_url = 'comment/reply/node/' . $this->unpublishedNode->id() . '/comment';
// Commenting on an unpublished node results in access denied.
$this->drupalGet($comment_url);
$assert->statusCodeEquals(403);
// Publishing the node grants access.
$this->unpublishedNode->setPublished()->save();
$this->drupalGet($comment_url);
$assert->statusCodeEquals(200);
}
/**
* Tests cannot view comment reply form on entities you cannot view.
*/
public function testCannotViewCommentReplyFormOnEntitiesYouCannotView() {
$assert = $this->assertSession();
// Create a comment on an unpublished node.
$comment = Comment::create([
'entity_type' => 'node',
'name' => 'Tony',
'hostname' => 'magic.example.com',
'mail' => 'foo@example.com',
'subject' => 'Comment on unpublished node',
'entity_id' => $this->unpublishedNode->id(),
'comment_type' => 'comment',
'field_name' => 'comment',
'pid' => 0,
'uid' => $this->unpublishedNode->getOwnerId(),
'status' => 1,
]);
$comment->save();
$comment_url = 'comment/reply/node/' . $this->unpublishedNode->id() . '/comment/' . $comment->id();
// Replying to a comment on an unpublished node results in access denied.
$this->drupalGet($comment_url);
$assert->statusCodeEquals(403);
// Publishing the node grants access.
$this->unpublishedNode->setPublished()->save();
$this->drupalGet($comment_url);
$assert->statusCodeEquals(200);
}
}

View file

@ -0,0 +1,71 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Entity\Comment;
use Drupal\system\Entity\Action;
/**
* Tests actions provided by the Comment module.
*
* @group comment
*/
class CommentActionsTest extends CommentTestBase {
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['dblog', 'action'];
/**
* Tests comment publish and unpublish actions.
*/
public function testCommentPublishUnpublishActions() {
$this->drupalLogin($this->webUser);
$comment_text = $this->randomMachineName();
$subject = $this->randomMachineName();
$comment = $this->postComment($this->node, $comment_text, $subject);
// Unpublish a comment.
$action = Action::load('comment_unpublish_action');
$action->execute([$comment]);
$this->assertTrue($comment->isPublished() === FALSE, 'Comment was unpublished');
$this->assertArraySubset(['module' => ['comment']], $action->getDependencies());
// Publish a comment.
$action = Action::load('comment_publish_action');
$action->execute([$comment]);
$this->assertTrue($comment->isPublished() === TRUE, 'Comment was published');
}
/**
* Tests the unpublish comment by keyword action.
*/
public function testCommentUnpublishByKeyword() {
$this->drupalLogin($this->adminUser);
$keyword_1 = $this->randomMachineName();
$keyword_2 = $this->randomMachineName();
$action = Action::create([
'id' => 'comment_unpublish_by_keyword_action',
'label' => $this->randomMachineName(),
'type' => 'comment',
'configuration' => [
'keywords' => [$keyword_1, $keyword_2],
],
'plugin' => 'comment_unpublish_by_keyword_action',
]);
$action->save();
$comment = $this->postComment($this->node, $keyword_2, $this->randomMachineName());
// Load the full comment so that status is available.
$comment = Comment::load($comment->id());
$this->assertTrue($comment->isPublished() === TRUE, 'The comment status was set to published.');
$action->execute([$comment]);
$this->assertTrue($comment->isPublished() === FALSE, 'The comment status was set to not published.');
}
}

View file

@ -0,0 +1,282 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Component\Utility\Html;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\user\RoleInterface;
use Drupal\comment\Entity\Comment;
/**
* Tests comment approval functionality.
*
* @group comment
*/
class CommentAdminTest extends CommentTestBase {
protected function setUp() {
parent::setUp();
$this->drupalPlaceBlock('page_title_block');
}
/**
* Test comment approval functionality through admin/content/comment.
*/
public function testApprovalAdminInterface() {
// Set anonymous comments to require approval.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => TRUE,
'skip comment approval' => FALSE,
]);
$this->drupalLogin($this->adminUser);
// Ensure that doesn't require contact info.
$this->setCommentAnonymous('0');
// Test that the comments page loads correctly when there are no comments
$this->drupalGet('admin/content/comment');
$this->assertText(t('No comments available.'));
$this->drupalLogout();
// Post anonymous comment without contact info.
$subject = $this->randomMachineName();
$body = $this->randomMachineName();
// Set $contact to true so that it won't check for id and message.
$this->postComment($this->node, $body, $subject, TRUE);
$this->assertText(t('Your comment has been queued for review by site administrators and will be published after approval.'), 'Comment requires approval.');
// Get unapproved comment id.
$this->drupalLogin($this->adminUser);
$anonymous_comment4 = $this->getUnapprovedComment($subject);
$anonymous_comment4 = Comment::create([
'cid' => $anonymous_comment4,
'subject' => $subject,
'comment_body' => $body,
'entity_id' => $this->node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
]);
$this->drupalLogout();
$this->assertFalse($this->commentExists($anonymous_comment4), 'Anonymous comment was not published.');
// Approve comment.
$this->drupalLogin($this->adminUser);
$this->performCommentOperation($anonymous_comment4, 'publish', TRUE);
$this->drupalLogout();
$this->drupalGet('node/' . $this->node->id());
$this->assertTrue($this->commentExists($anonymous_comment4), 'Anonymous comment visible.');
// Post 2 anonymous comments without contact info.
$comments[] = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Publish multiple comments in one operation.
$this->drupalLogin($this->adminUser);
$this->drupalGet('admin/content/comment/approval');
$this->assertText(t('Unapproved comments (@count)', ['@count' => 2]), 'Two unapproved comments waiting for approval.');
$edit = [
"comments[{$comments[0]->id()}]" => 1,
"comments[{$comments[1]->id()}]" => 1,
];
$this->drupalPostForm(NULL, $edit, t('Update'));
$this->assertText(t('Unapproved comments (@count)', ['@count' => 0]), 'All comments were approved.');
// Delete multiple comments in one operation.
$edit = [
'operation' => 'delete',
"comments[{$comments[0]->id()}]" => 1,
"comments[{$comments[1]->id()}]" => 1,
"comments[{$anonymous_comment4->id()}]" => 1,
];
$this->drupalPostForm(NULL, $edit, t('Update'));
$this->assertText(t('Are you sure you want to delete these comments and all their children?'), 'Confirmation required.');
$this->drupalPostForm(NULL, [], t('Delete'));
$this->assertText(t('No comments available.'), 'All comments were deleted.');
// Test message when no comments selected.
$edit = [
'operation' => 'delete',
];
$this->drupalPostForm(NULL, $edit, t('Update'));
$this->assertText(t('Select one or more comments to perform the update on.'));
// Make sure the label of unpublished node is not visible on listing page.
$this->drupalGet('admin/content/comment');
$this->postComment($this->node, $this->randomMachineName());
$this->drupalGet('admin/content/comment');
$this->assertText(Html::escape($this->node->label()));
$this->node->setUnpublished()->save();
$this->drupalGet('admin/content/comment');
$this->assertNoText(Html::escape($this->node->label()));
}
/**
* Tests comment approval functionality through the node interface.
*/
public function testApprovalNodeInterface() {
// Set anonymous comments to require approval.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => TRUE,
'skip comment approval' => FALSE,
]);
$this->drupalLogin($this->adminUser);
// Ensure that doesn't require contact info.
$this->setCommentAnonymous('0');
$this->drupalLogout();
// Post anonymous comment without contact info.
$subject = $this->randomMachineName();
$body = $this->randomMachineName();
// Set $contact to true so that it won't check for id and message.
$this->postComment($this->node, $body, $subject, TRUE);
$this->assertText(t('Your comment has been queued for review by site administrators and will be published after approval.'), 'Comment requires approval.');
// Get unapproved comment id.
$this->drupalLogin($this->adminUser);
$anonymous_comment4 = $this->getUnapprovedComment($subject);
$anonymous_comment4 = Comment::create([
'cid' => $anonymous_comment4,
'subject' => $subject,
'comment_body' => $body,
'entity_id' => $this->node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
]);
$this->drupalLogout();
$this->assertFalse($this->commentExists($anonymous_comment4), 'Anonymous comment was not published.');
// Approve comment.
$this->drupalLogin($this->adminUser);
$this->drupalGet('comment/1/approve');
$this->assertResponse(403, 'Forged comment approval was denied.');
$this->drupalGet('comment/1/approve', ['query' => ['token' => 'forged']]);
$this->assertResponse(403, 'Forged comment approval was denied.');
$this->drupalGet('comment/1/edit');
$this->assertFieldChecked('edit-status-0');
$this->drupalGet('node/' . $this->node->id());
$this->clickLink(t('Approve'));
$this->drupalLogout();
$this->drupalGet('node/' . $this->node->id());
$this->assertTrue($this->commentExists($anonymous_comment4), 'Anonymous comment visible.');
}
/**
* Tests comment bundle admin.
*/
public function testCommentAdmin() {
// Login.
$this->drupalLogin($this->adminUser);
// Browse to comment bundle overview.
$this->drupalGet('admin/structure/comment');
$this->assertResponse(200);
// Make sure titles visible.
$this->assertText('Comment type');
$this->assertText('Description');
// Make sure the description is present.
$this->assertText('Default comment field');
// Manage fields.
$this->clickLink('Manage fields');
$this->assertResponse(200);
// Make sure comment_body field is shown.
$this->assertText('comment_body');
// Rest from here on in is field_ui.
}
/**
* Tests editing a comment as an admin.
*/
public function testEditComment() {
// Enable anonymous user comments.
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments',
'post comments',
'skip comment approval',
]);
// Log in as a web user.
$this->drupalLogin($this->webUser);
// Post a comment.
$comment = $this->postComment($this->node, $this->randomMachineName());
$this->drupalLogout();
// Post anonymous comment.
$this->drupalLogin($this->adminUser);
// Ensure that we need email id before posting comment.
$this->setCommentAnonymous('2');
$this->drupalLogout();
// Post comment with contact info (required).
$author_name = $this->randomMachineName();
$author_mail = $this->randomMachineName() . '@example.com';
$anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), ['name' => $author_name, 'mail' => $author_mail]);
// Log in as an admin user.
$this->drupalLogin($this->adminUser);
// Make sure the comment field is not visible when
// the comment was posted by an authenticated user.
$this->drupalGet('comment/' . $comment->id() . '/edit');
$this->assertNoFieldById('edit-mail', $comment->getAuthorEmail());
// Make sure the comment field is visible when
// the comment was posted by an anonymous user.
$this->drupalGet('comment/' . $anonymous_comment->id() . '/edit');
$this->assertFieldById('edit-mail', $anonymous_comment->getAuthorEmail());
}
/**
* Tests commented translation deletion admin view.
*/
public function testCommentedTranslationDeletion() {
\Drupal::service('module_installer')->install([
'language',
'locale',
]);
\Drupal::service('router.builder')->rebuildIfNeeded();
ConfigurableLanguage::createFromLangcode('ur')->save();
// Rebuild the container to update the default language container variable.
$this->rebuildContainer();
// Ensure that doesn't require contact info.
$this->setCommentAnonymous('0');
$this->drupalLogin($this->webUser);
$count_query = \Drupal::entityTypeManager()
->getStorage('comment')
->getQuery()
->count();
$before_count = $count_query->execute();
// Post 2 anonymous comments without contact info.
$comment1 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comment2 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comment1->addTranslation('ur', ['subject' => 'ur ' . $comment1->label()])
->save();
$comment2->addTranslation('ur', ['subject' => 'ur ' . $comment1->label()])
->save();
$this->drupalLogout();
$this->drupalLogin($this->adminUser);
// Delete multiple comments in one operation.
$edit = [
'operation' => 'delete',
"comments[{$comment1->id()}]" => 1,
"comments[{$comment2->id()}]" => 1,
];
$this->drupalPostForm('admin/content/comment', $edit, t('Update'));
$this->assertRaw(new FormattableMarkup('@label (Original translation) - <em>The following comment translations will be deleted:</em>', ['@label' => $comment1->label()]));
$this->assertRaw(new FormattableMarkup('@label (Original translation) - <em>The following comment translations will be deleted:</em>', ['@label' => $comment2->label()]));
$this->assertText('English');
$this->assertText('Urdu');
$this->drupalPostForm(NULL, [], t('Delete'));
$after_count = $count_query->execute();
$this->assertEqual($after_count, $before_count, 'No comment or translation found.');
}
}

View file

@ -0,0 +1,203 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\user\RoleInterface;
/**
* Tests anonymous commenting.
*
* @group comment
*/
class CommentAnonymousTest extends CommentTestBase {
protected function setUp() {
parent::setUp();
// Enable anonymous and authenticated user comments.
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments',
'post comments',
'skip comment approval',
]);
user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, [
'access comments',
'post comments',
'skip comment approval',
]);
}
/**
* Tests anonymous comment functionality.
*/
public function testAnonymous() {
$this->drupalLogin($this->adminUser);
$this->setCommentAnonymous(COMMENT_ANONYMOUS_MAYNOT_CONTACT);
$this->drupalLogout();
// Preview comments (with `skip comment approval` permission).
$edit = [];
$title = 'comment title with skip comment approval';
$body = 'comment body with skip comment approval';
$edit['subject[0][value]'] = $title;
$edit['comment_body[0][value]'] = $body;
$this->drupalPostForm($this->node->urlInfo(), $edit, t('Preview'));
// Cannot use assertRaw here since both title and body are in the form.
$preview = (string) $this->cssSelect('.preview')[0]->getHtml();
$this->assertTrue(strpos($preview, $title) !== FALSE, 'Anonymous user can preview comment title.');
$this->assertTrue(strpos($preview, $body) !== FALSE, 'Anonymous user can preview comment body.');
// Preview comments (without `skip comment approval` permission).
user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['skip comment approval']);
$edit = [];
$title = 'comment title without skip comment approval';
$body = 'comment body without skip comment approval';
$edit['subject[0][value]'] = $title;
$edit['comment_body[0][value]'] = $body;
$this->drupalPostForm($this->node->urlInfo(), $edit, t('Preview'));
// Cannot use assertRaw here since both title and body are in the form.
$preview = (string) $this->cssSelect('.preview')[0]->getHtml();
$this->assertTrue(strpos($preview, $title) !== FALSE, 'Anonymous user can preview comment title.');
$this->assertTrue(strpos($preview, $body) !== FALSE, 'Anonymous user can preview comment body.');
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['skip comment approval']);
// Post anonymous comment without contact info.
$anonymous_comment1 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName());
$this->assertTrue($this->commentExists($anonymous_comment1), 'Anonymous comment without contact info found.');
// Ensure anonymous users cannot post in the name of registered users.
$edit = [
'name' => $this->adminUser->getUsername(),
'comment_body[0][value]' => $this->randomMachineName(),
];
$this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', $edit, t('Save'));
$this->assertRaw(t('The name you used (%name) belongs to a registered user.', [
'%name' => $this->adminUser->getUsername(),
]));
// Allow contact info.
$this->drupalLogin($this->adminUser);
$this->setCommentAnonymous(COMMENT_ANONYMOUS_MAY_CONTACT);
// Attempt to edit anonymous comment.
$this->drupalGet('comment/' . $anonymous_comment1->id() . '/edit');
$edited_comment = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName());
$this->assertTrue($this->commentExists($edited_comment, FALSE), 'Modified reply found.');
$this->drupalLogout();
// Post anonymous comment with contact info (optional).
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$this->assertTrue($this->commentContactInfoAvailable(), 'Contact information available.');
// Check the presence of expected cache tags.
$this->assertCacheTag('config:field.field.node.article.comment');
$this->assertCacheTag('config:user.settings');
$anonymous_comment2 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName());
$this->assertTrue($this->commentExists($anonymous_comment2), 'Anonymous comment with contact info (optional) found.');
// Ensure anonymous users cannot post in the name of registered users.
$edit = [
'name' => $this->adminUser->getUsername(),
'mail' => $this->randomMachineName() . '@example.com',
'subject[0][value]' => $this->randomMachineName(),
'comment_body[0][value]' => $this->randomMachineName(),
];
$this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', $edit, t('Save'));
$this->assertRaw(t('The name you used (%name) belongs to a registered user.', [
'%name' => $this->adminUser->getUsername(),
]));
// Require contact info.
$this->drupalLogin($this->adminUser);
$this->setCommentAnonymous(COMMENT_ANONYMOUS_MUST_CONTACT);
$this->drupalLogout();
// Try to post comment with contact info (required).
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$this->assertTrue($this->commentContactInfoAvailable(), 'Contact information available.');
$anonymous_comment3 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Name should have 'Anonymous' for value by default.
$this->assertText(t('Email field is required.'), 'Email required.');
$this->assertFalse($this->commentExists($anonymous_comment3), 'Anonymous comment with contact info (required) not found.');
// Post comment with contact info (required).
$author_name = $this->randomMachineName();
$author_mail = $this->randomMachineName() . '@example.com';
$anonymous_comment3 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), ['name' => $author_name, 'mail' => $author_mail]);
$this->assertTrue($this->commentExists($anonymous_comment3), 'Anonymous comment with contact info (required) found.');
// Make sure the user data appears correctly when editing the comment.
$this->drupalLogin($this->adminUser);
$this->drupalGet('comment/' . $anonymous_comment3->id() . '/edit');
$this->assertRaw($author_name, "The anonymous user's name is correct when editing the comment.");
$this->assertFieldByName('uid', '', 'The author field is empty (i.e. anonymous) when editing the comment.');
$this->assertRaw($author_mail, "The anonymous user's email address is correct when editing the comment.");
// Unpublish comment.
$this->performCommentOperation($anonymous_comment3, 'unpublish');
$this->drupalGet('admin/content/comment/approval');
$this->assertRaw('comments[' . $anonymous_comment3->id() . ']', 'Comment was unpublished.');
// Publish comment.
$this->performCommentOperation($anonymous_comment3, 'publish', TRUE);
$this->drupalGet('admin/content/comment');
$this->assertRaw('comments[' . $anonymous_comment3->id() . ']', 'Comment was published.');
// Delete comment.
$this->performCommentOperation($anonymous_comment3, 'delete');
$this->drupalGet('admin/content/comment');
$this->assertNoRaw('comments[' . $anonymous_comment3->id() . ']', 'Comment was deleted.');
$this->drupalLogout();
// Comment 3 was deleted.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $anonymous_comment3->id());
$this->assertResponse(403);
// Reset.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => FALSE,
'post comments' => FALSE,
'skip comment approval' => FALSE,
]);
// Attempt to view comments while disallowed.
// NOTE: if authenticated user has permission to post comments, then a
// "Login or register to post comments" type link may be shown.
$this->drupalGet('node/' . $this->node->id());
$this->assertNoPattern('@<h2[^>]*>Comments</h2>@', 'Comments were not displayed.');
$this->assertNoLink('Add new comment', 'Link to add comment was found.');
// Attempt to view node-comment form while disallowed.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$this->assertResponse(403);
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => FALSE,
'skip comment approval' => FALSE,
]);
$this->drupalGet('node/' . $this->node->id());
$this->assertPattern('@<h2[^>]*>Comments</h2>@', 'Comments were displayed.');
$this->assertLink('Log in', 1, 'Link to login was found.');
$this->assertLink('register', 1, 'Link to register was found.');
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => FALSE,
'post comments' => TRUE,
'skip comment approval' => TRUE,
]);
$this->drupalGet('node/' . $this->node->id());
$this->assertNoPattern('@<h2[^>]*>Comments</h2>@', 'Comments were not displayed.');
$this->assertFieldByName('subject[0][value]', '', 'Subject field found.');
$this->assertFieldByName('comment_body[0][value]', '', 'Comment field found.');
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $anonymous_comment2->id());
$this->assertResponse(403);
}
}

View file

@ -0,0 +1,90 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\user\RoleInterface;
/**
* Tests comment block functionality.
*
* @group comment
*/
class CommentBlockTest extends CommentTestBase {
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['block', 'views'];
protected function setUp() {
parent::setUp();
// Update admin user to have the 'administer blocks' permission.
$this->adminUser = $this->drupalCreateUser([
'administer content types',
'administer comments',
'skip comment approval',
'post comments',
'access comments',
'access content',
'administer blocks',
]);
}
/**
* Tests the recent comments block.
*/
public function testRecentCommentBlock() {
$this->drupalLogin($this->adminUser);
$block = $this->drupalPlaceBlock('views_block:comments_recent-block_1');
// Add some test comments, with and without subjects. Because the 10 newest
// comments should be shown by the block, we create 11 to test that behavior
// below.
$timestamp = REQUEST_TIME;
for ($i = 0; $i < 11; ++$i) {
$subject = ($i % 2) ? $this->randomMachineName() : '';
$comments[$i] = $this->postComment($this->node, $this->randomMachineName(), $subject);
$comments[$i]->created->value = $timestamp--;
$comments[$i]->save();
}
// Test that a user without the 'access comments' permission cannot see the
// block.
$this->drupalLogout();
user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']);
$this->drupalGet('');
$this->assertNoText(t('Recent comments'));
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']);
// Test that a user with the 'access comments' permission can see the
// block.
$this->drupalLogin($this->webUser);
$this->drupalGet('');
$this->assertText(t('Recent comments'));
// Test the only the 10 latest comments are shown and in the proper order.
$this->assertNoText($comments[10]->getSubject(), 'Comment 11 not found in block.');
for ($i = 0; $i < 10; $i++) {
$this->assertText($comments[$i]->getSubject(), new FormattableMarkup('Comment @number found in block.', ['@number' => 10 - $i]));
if ($i > 1) {
$previous_position = $position;
$position = strpos($this->getSession()->getPage()->getContent(), $comments[$i]->getSubject());
$this->assertTrue($position > $previous_position, new FormattableMarkup('Comment @a appears after comment @b', ['@a' => 10 - $i, '@b' => 11 - $i]));
}
$position = strpos($this->getSession()->getPage()->getContent(), $comments[$i]->getSubject());
}
// Test that links to comments work when comments are across pages.
$this->setCommentsPerPage(1);
for ($i = 0; $i < 10; $i++) {
$this->clickLink($comments[$i]->getSubject());
$this->assertText($comments[$i]->getSubject(), 'Comment link goes to correct page.');
$this->assertRaw('<link rel="canonical"', 'Canonical URL was found in the HTML head');
}
}
}

View file

@ -0,0 +1,78 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\CommentInterface;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\node\Entity\Node;
use Drupal\Tests\BrowserTestBase;
use Drupal\comment\Entity\Comment;
/**
* Tests visibility of comments on book pages.
*
* @group comment
*/
class CommentBookTest extends BrowserTestBase {
use CommentTestTrait;
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['book', 'comment'];
protected function setUp() {
parent::setUp();
// Create comment field on book.
$this->addDefaultCommentField('node', 'book');
}
/**
* Tests comments in book export.
*/
public function testBookCommentPrint() {
$book_node = Node::create([
'type' => 'book',
'title' => 'Book title',
'body' => 'Book body',
]);
$book_node->book['bid'] = 'new';
$book_node->save();
$comment_subject = $this->randomMachineName(8);
$comment_body = $this->randomMachineName(8);
$comment = Comment::create([
'subject' => $comment_subject,
'comment_body' => $comment_body,
'entity_id' => $book_node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'status' => CommentInterface::PUBLISHED,
]);
$comment->save();
$commenting_user = $this->drupalCreateUser(['access printer-friendly version', 'access comments', 'post comments']);
$this->drupalLogin($commenting_user);
$this->drupalGet('node/' . $book_node->id());
$this->assertText($comment_subject, 'Comment subject found');
$this->assertText($comment_body, 'Comment body found');
$this->assertText(t('Add new comment'), 'Comment form found');
$this->assertField('subject[0][value]', 'Comment form subject found');
$this->drupalGet('book/export/html/' . $book_node->id());
$this->assertText(t('Comments'), 'Comment thread found');
$this->assertText($comment_subject, 'Comment subject found');
$this->assertText($comment_body, 'Comment body found');
$this->assertNoText(t('Add new comment'), 'Comment form not found');
$this->assertNoField('subject[0][value]', 'Comment form subject not found');
}
}

View file

@ -0,0 +1,137 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\Core\Language\LanguageInterface;
use Drupal\comment\CommentInterface;
use Drupal\user\RoleInterface;
use Drupal\comment\Entity\Comment;
use Drupal\Tests\Traits\Core\GeneratePermutationsTrait;
/**
* Tests CSS classes on comments.
*
* @group comment
*/
class CommentCSSTest extends CommentTestBase {
use GeneratePermutationsTrait;
protected function setUp() {
parent::setUp();
// Allow anonymous users to see comments.
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments',
'access content',
]);
}
/**
* Tests CSS classes on comments.
*/
public function testCommentClasses() {
// Create all permutations for comments, users, and nodes.
$parameters = [
'node_uid' => [0, $this->webUser->id()],
'comment_uid' => [0, $this->webUser->id(), $this->adminUser->id()],
'comment_status' => [CommentInterface::PUBLISHED, CommentInterface::NOT_PUBLISHED],
'user' => ['anonymous', 'authenticated', 'admin'],
];
$permutations = $this->generatePermutations($parameters);
foreach ($permutations as $case) {
// Create a new node.
$node = $this->drupalCreateNode(['type' => 'article', 'uid' => $case['node_uid']]);
// Add a comment.
/** @var \Drupal\comment\CommentInterface $comment */
$comment = Comment::create([
'entity_id' => $node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'uid' => $case['comment_uid'],
'status' => $case['comment_status'],
'subject' => $this->randomMachineName(),
'language' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
'comment_body' => [LanguageInterface::LANGCODE_NOT_SPECIFIED => [$this->randomMachineName()]],
]);
$comment->save();
// Adjust the current/viewing user.
switch ($case['user']) {
case 'anonymous':
if ($this->loggedInUser) {
$this->drupalLogout();
}
$case['user_uid'] = 0;
break;
case 'authenticated':
$this->drupalLogin($this->webUser);
$case['user_uid'] = $this->webUser->id();
break;
case 'admin':
$this->drupalLogin($this->adminUser);
$case['user_uid'] = $this->adminUser->id();
break;
}
// Request the node with the comment.
$this->drupalGet('node/' . $node->id());
$settings = $this->getDrupalSettings();
// Verify the data-history-node-id attribute, which is necessary for the
// by-viewer class and the "new" indicator, see below.
$this->assertIdentical(1, count($this->xpath('//*[@data-history-node-id="' . $node->id() . '"]')), 'data-history-node-id attribute is set on node.');
// Verify classes if the comment is visible for the current user.
if ($case['comment_status'] == CommentInterface::PUBLISHED || $case['user'] == 'admin') {
// Verify the by-anonymous class.
$comments = $this->xpath('//*[contains(@class, "comment") and contains(@class, "by-anonymous")]');
if ($case['comment_uid'] == 0) {
$this->assertTrue(count($comments) == 1, 'by-anonymous class found.');
}
else {
$this->assertFalse(count($comments), 'by-anonymous class not found.');
}
// Verify the by-node-author class.
$comments = $this->xpath('//*[contains(@class, "comment") and contains(@class, "by-node-author")]');
if ($case['comment_uid'] > 0 && $case['comment_uid'] == $case['node_uid']) {
$this->assertTrue(count($comments) == 1, 'by-node-author class found.');
}
else {
$this->assertFalse(count($comments), 'by-node-author class not found.');
}
// Verify the data-comment-user-id attribute, which is used by the
// drupal.comment-by-viewer library to add a by-viewer when the current
// user (the viewer) was the author of the comment. We do this in Java-
// Script to prevent breaking the render cache.
$this->assertIdentical(1, count($this->xpath('//*[contains(@class, "comment") and @data-comment-user-id="' . $case['comment_uid'] . '"]')), 'data-comment-user-id attribute is set on comment.');
$this->assertRaw(drupal_get_path('module', 'comment') . '/js/comment-by-viewer.js', 'drupal.comment-by-viewer library is present.');
}
// Verify the unpublished class.
$comments = $this->xpath('//*[contains(@class, "comment") and contains(@class, "unpublished")]');
if ($case['comment_status'] == CommentInterface::NOT_PUBLISHED && $case['user'] == 'admin') {
$this->assertTrue(count($comments) == 1, 'unpublished class found.');
}
else {
$this->assertFalse(count($comments), 'unpublished class not found.');
}
// Verify the data-comment-timestamp attribute, which is used by the
// drupal.comment-new-indicator library to add a "new" indicator to each
// comment that was created or changed after the last time the current
// user read the corresponding node.
if ($case['comment_status'] == CommentInterface::PUBLISHED || $case['user'] == 'admin') {
$this->assertIdentical(1, count($this->xpath('//*[contains(@class, "comment")]/*[@data-comment-timestamp="' . $comment->getChangedTime() . '"]')), 'data-comment-timestamp attribute is set on comment');
$expectedJS = ($case['user'] !== 'anonymous');
$this->assertIdentical($expectedJS, isset($settings['ajaxPageState']['libraries']) && in_array('comment/drupal.comment-new-indicator', explode(',', $settings['ajaxPageState']['libraries'])), 'drupal.comment-new-indicator library is present.');
}
}
}
}

View file

@ -0,0 +1,156 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\CommentInterface;
use Drupal\comment\CommentManagerInterface;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\Core\Entity\EntityInterface;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\system\Functional\Entity\EntityWithUriCacheTagsTestBase;
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;
/**
* Tests the Comment entity's cache tags.
*
* @group comment
*/
class CommentCacheTagsTest extends EntityWithUriCacheTagsTestBase {
use CommentTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['comment'];
/**
* @var \Drupal\entity_test\Entity\EntityTest
*/
protected $entityTestCamelid;
/**
* @var \Drupal\entity_test\Entity\EntityTest
*/
protected $entityTestHippopotamidae;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Give anonymous users permission to view comments, so that we can verify
// the cache tags of cached versions of comment pages.
$user_role = Role::load(RoleInterface::ANONYMOUS_ID);
$user_role->grantPermission('access comments');
$user_role->save();
}
/**
* {@inheritdoc}
*/
protected function createEntity() {
// Create a "bar" bundle for the "entity_test" entity type and create.
$bundle = 'bar';
entity_test_create_bundle($bundle, NULL, 'entity_test');
// Create a comment field on this bundle.
$this->addDefaultCommentField('entity_test', 'bar', 'comment');
// Display comments in a flat list; threaded comments are not render cached.
$field = FieldConfig::loadByName('entity_test', 'bar', 'comment');
$field->setSetting('default_mode', CommentManagerInterface::COMMENT_MODE_FLAT);
$field->save();
// Create a "Camelids" test entity that the comment will be assigned to.
$this->entityTestCamelid = EntityTest::create([
'name' => 'Camelids',
'type' => 'bar',
]);
$this->entityTestCamelid->save();
// Create a "Llama" comment.
$comment = Comment::create([
'subject' => 'Llama',
'comment_body' => [
'value' => 'The name "llama" was adopted by European settlers from native Peruvians.',
'format' => 'plain_text',
],
'entity_id' => $this->entityTestCamelid->id(),
'entity_type' => 'entity_test',
'field_name' => 'comment',
'status' => CommentInterface::PUBLISHED,
]);
$comment->save();
return $comment;
}
/**
* Test that comments correctly invalidate the cache tag of their host entity.
*/
public function testCommentEntity() {
$this->verifyPageCache($this->entityTestCamelid->urlInfo(), 'MISS');
$this->verifyPageCache($this->entityTestCamelid->urlInfo(), 'HIT');
// Create a "Hippopotamus" comment.
$this->entityTestHippopotamidae = EntityTest::create([
'name' => 'Hippopotamus',
'type' => 'bar',
]);
$this->entityTestHippopotamidae->save();
$this->verifyPageCache($this->entityTestHippopotamidae->urlInfo(), 'MISS');
$this->verifyPageCache($this->entityTestHippopotamidae->urlInfo(), 'HIT');
$hippo_comment = Comment::create([
'subject' => 'Hippopotamus',
'comment_body' => [
'value' => 'The common hippopotamus (Hippopotamus amphibius), or hippo, is a large, mostly herbivorous mammal in sub-Saharan Africa',
'format' => 'plain_text',
],
'entity_id' => $this->entityTestHippopotamidae->id(),
'entity_type' => 'entity_test',
'field_name' => 'comment',
'status' => CommentInterface::PUBLISHED,
]);
$hippo_comment->save();
// Ensure that a new comment only invalidates the commented entity.
$this->verifyPageCache($this->entityTestCamelid->urlInfo(), 'HIT');
$this->verifyPageCache($this->entityTestHippopotamidae->urlInfo(), 'MISS');
$this->assertText($hippo_comment->getSubject());
// Ensure that updating an existing comment only invalidates the commented
// entity.
$this->entity->save();
$this->verifyPageCache($this->entityTestCamelid->urlInfo(), 'MISS');
$this->verifyPageCache($this->entityTestHippopotamidae->urlInfo(), 'HIT');
}
/**
* {@inheritdoc}
*/
protected function getAdditionalCacheContextsForEntity(EntityInterface $entity) {
return [];
}
/**
* {@inheritdoc}
*
* Each comment must have a comment body, which always has a text format.
*/
protected function getAdditionalCacheTagsForEntity(EntityInterface $entity) {
/** @var \Drupal\comment\CommentInterface $entity */
return [
'config:filter.format.plain_text',
'user:' . $entity->getOwnerId(),
'user_view',
];
}
}

View file

@ -0,0 +1,80 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Entity\CommentType;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\comment\CommentInterface;
use Drupal\Tests\taxonomy\Functional\TaxonomyTestTrait;
use Drupal\comment\Entity\Comment;
/**
* Tests comments with other entities.
*
* @group comment
*/
class CommentEntityTest extends CommentTestBase {
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['block', 'comment', 'node', 'history', 'field_ui', 'datetime', 'taxonomy'];
use TaxonomyTestTrait;
protected $vocab;
protected $commentType;
protected function setUp() {
parent::setUp();
$this->vocab = $this->createVocabulary();
$this->commentType = CommentType::create([
'id' => 'taxonomy_comment',
'label' => 'Taxonomy comment',
'description' => '',
'target_entity_type_id' => 'taxonomy_term',
]);
$this->commentType->save();
$this->addDefaultCommentField(
'taxonomy_term',
$this->vocab->id(),
'field_comment',
CommentItemInterface::OPEN,
$this->commentType->id()
);
}
/**
* Tests CSS classes on comments.
*/
public function testEntityChanges() {
$this->drupalLogin($this->webUser);
// Create a new node.
$term = $this->createTerm($this->vocab, ['uid' => $this->webUser->id()]);
// Add a comment.
/** @var \Drupal\comment\CommentInterface $comment */
$comment = Comment::create([
'entity_id' => $term->id(),
'entity_type' => 'taxonomy_term',
'field_name' => 'field_comment',
'uid' => $this->webUser->id(),
'status' => CommentInterface::PUBLISHED,
'subject' => $this->randomMachineName(),
'language' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
'comment_body' => [LanguageInterface::LANGCODE_NOT_SPECIFIED => [$this->randomMachineName()]],
]);
$comment->save();
// Request the node with the comment.
$this->drupalGet('taxonomy/term/' . $term->id());
$settings = $this->getDrupalSettings();
$this->assertFalse(isset($settings['ajaxPageState']['libraries']) && in_array('comment/drupal.comment-new-indicator', explode(',', $settings['ajaxPageState']['libraries'])), 'drupal.comment-new-indicator library is present.');
$this->assertFalse(isset($settings['history']['lastReadTimestamps']) && in_array($term->id(), array_keys($settings['history']['lastReadTimestamps'])), 'history.lastReadTimestamps is present.');
}
}

View file

@ -0,0 +1,235 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\comment\Entity\CommentType;
/**
* Tests fields on comments.
*
* @group comment
*/
class CommentFieldsTest extends CommentTestBase {
/**
* Install the field UI.
*
* @var array
*/
public static $modules = ['field_ui'];
/**
* Tests that the default 'comment_body' field is correctly added.
*/
public function testCommentDefaultFields() {
// Do not make assumptions on default node types created by the test
// installation profile, and create our own.
$this->drupalCreateContentType(['type' => 'test_node_type']);
$this->addDefaultCommentField('node', 'test_node_type');
// Check that the 'comment_body' field is present on the comment bundle.
$field = FieldConfig::loadByName('comment', 'comment', 'comment_body');
$this->assertTrue(!empty($field), 'The comment_body field is added when a comment bundle is created');
$field->delete();
// Check that the 'comment_body' field is not deleted since it is persisted
// even if it has no fields.
$field_storage = FieldStorageConfig::loadByName('comment', 'comment_body');
$this->assertTrue($field_storage, 'The comment_body field storage was not deleted');
// Create a new content type.
$type_name = 'test_node_type_2';
$this->drupalCreateContentType(['type' => $type_name]);
$this->addDefaultCommentField('node', $type_name);
// Check that the 'comment_body' field exists and has an instance on the
// new comment bundle.
$field_storage = FieldStorageConfig::loadByName('comment', 'comment_body');
$this->assertTrue($field_storage, 'The comment_body field exists');
$field = FieldConfig::loadByName('comment', 'comment', 'comment_body');
$this->assertTrue(isset($field), format_string('The comment_body field is present for comments on type @type', ['@type' => $type_name]));
// Test adding a field that defaults to CommentItemInterface::CLOSED.
$this->addDefaultCommentField('node', 'test_node_type', 'who_likes_ponies', CommentItemInterface::CLOSED, 'who_likes_ponies');
$field = FieldConfig::load('node.test_node_type.who_likes_ponies');;
$this->assertEqual($field->getDefaultValueLiteral()[0]['status'], CommentItemInterface::CLOSED);
}
/**
* Tests that you can remove a comment field.
*/
public function testCommentFieldDelete() {
$this->drupalCreateContentType(['type' => 'test_node_type']);
$this->addDefaultCommentField('node', 'test_node_type');
// We want to test the handling of removing the primary comment field, so we
// ensure there is at least one other comment field attached to a node type
// so that comment_entity_load() runs for nodes.
$this->addDefaultCommentField('node', 'test_node_type', 'comment2');
// Create a sample node.
$node = $this->drupalCreateNode([
'title' => 'Baloney',
'type' => 'test_node_type',
]);
$this->drupalLogin($this->webUser);
$this->drupalGet('node/' . $node->nid->value);
$elements = $this->cssSelect('.field--type-comment');
$this->assertEqual(2, count($elements), 'There are two comment fields on the node.');
// Delete the first comment field.
FieldStorageConfig::loadByName('node', 'comment')->delete();
$this->drupalGet('node/' . $node->nid->value);
$elements = $this->cssSelect('.field--type-comment');
$this->assertEqual(1, count($elements), 'There is one comment field on the node.');
}
/**
* Tests link building with non-default comment field names.
*/
public function testCommentFieldLinksNonDefaultName() {
$this->drupalCreateContentType(['type' => 'test_node_type']);
$this->addDefaultCommentField('node', 'test_node_type', 'comment2');
$web_user2 = $this->drupalCreateUser([
'access comments',
'post comments',
'create article content',
'edit own comments',
'skip comment approval',
'access content',
]);
// Create a sample node.
$node = $this->drupalCreateNode([
'title' => 'Baloney',
'type' => 'test_node_type',
]);
// Go to the node first so that webuser2 see new comments.
$this->drupalLogin($web_user2);
$this->drupalGet($node->urlInfo());
$this->drupalLogout();
// Test that buildCommentedEntityLinks() does not break when the 'comment'
// field does not exist. Requires at least one comment.
$this->drupalLogin($this->webUser);
$this->postComment($node, 'Here is a comment', '', NULL, 'comment2');
$this->drupalLogout();
$this->drupalLogin($web_user2);
// We want to check the attached drupalSettings of
// \Drupal\comment\CommentLinkBuilder::buildCommentedEntityLinks. Therefore
// we need a node listing, let's use views for that.
$this->container->get('module_installer')->install(['views'], TRUE);
// We also need a router rebuild, as the router is lazily rebuild in the
// module installer.
\Drupal::service('router.builder')->rebuild();
$this->drupalGet('node');
$link_info = $this->getDrupalSettings()['comment']['newCommentsLinks']['node']['comment2']['2'];
$this->assertIdentical($link_info['new_comment_count'], 1);
$this->assertIdentical($link_info['first_new_comment_link'], $node->url('canonical', ['fragment' => 'new']));
}
/**
* Tests creating a comment field through the interface.
*/
public function testCommentFieldCreate() {
// Create user who can administer user fields.
$user = $this->drupalCreateUser([
'administer user fields',
]);
$this->drupalLogin($user);
// Create comment field in account settings.
$edit = [
'new_storage_type' => 'comment',
'label' => 'User comment',
'field_name' => 'user_comment',
];
$this->drupalPostForm('admin/config/people/accounts/fields/add-field', $edit, 'Save and continue');
// Try to save the comment field without selecting a comment type.
$edit = [];
$this->drupalPostForm('admin/config/people/accounts/fields/user.user.field_user_comment/storage', $edit, t('Save field settings'));
// We should get an error message.
$this->assertText(t('An illegal choice has been detected. Please contact the site administrator.'));
// Create a comment type for users.
$bundle = CommentType::create([
'id' => 'user_comment_type',
'label' => 'user_comment_type',
'description' => '',
'target_entity_type_id' => 'user',
]);
$bundle->save();
// Select a comment type and try to save again.
$edit = [
'settings[comment_type]' => 'user_comment_type',
];
$this->drupalPostForm('admin/config/people/accounts/fields/user.user.field_user_comment/storage', $edit, t('Save field settings'));
// We shouldn't get an error message.
$this->assertNoText(t('An illegal choice has been detected. Please contact the site administrator.'));
}
/**
* Tests that comment module works when installed after a content module.
*/
public function testCommentInstallAfterContentModule() {
// Create a user to do module administration.
$this->adminUser = $this->drupalCreateUser(['access administration pages', 'administer modules']);
$this->drupalLogin($this->adminUser);
// Drop default comment field added in CommentTestBase::setup().
FieldStorageConfig::loadByName('node', 'comment')->delete();
if ($field_storage = FieldStorageConfig::loadByName('node', 'comment_forum')) {
$field_storage->delete();
}
// Purge field data now to allow comment module to be uninstalled once the
// field has been deleted.
field_purge_batch(10);
// Uninstall the comment module.
$edit = [];
$edit['uninstall[comment]'] = TRUE;
$this->drupalPostForm('admin/modules/uninstall', $edit, t('Uninstall'));
$this->drupalPostForm(NULL, [], t('Uninstall'));
$this->rebuildContainer();
$this->assertFalse($this->container->get('module_handler')->moduleExists('comment'), 'Comment module uninstalled.');
// Install core content type module (book).
$edit = [];
$edit['modules[book][enable]'] = 'book';
$this->drupalPostForm('admin/modules', $edit, t('Install'));
// Now install the comment module.
$edit = [];
$edit['modules[comment][enable]'] = 'comment';
$this->drupalPostForm('admin/modules', $edit, t('Install'));
$this->rebuildContainer();
$this->assertTrue($this->container->get('module_handler')->moduleExists('comment'), 'Comment module enabled.');
// Create nodes of each type.
$this->addDefaultCommentField('node', 'book');
$book_node = $this->drupalCreateNode(['type' => 'book']);
$this->drupalLogout();
// Try to post a comment on each node. A failure will be triggered if the
// comment body is missing on one of these forms, due to postComment()
// asserting that the body is actually posted correctly.
$this->webUser = $this->drupalCreateUser(['access content', 'access comments', 'post comments', 'skip comment approval']);
$this->drupalLogin($this->webUser);
$this->postComment($book_node, $this->randomMachineName(), $this->randomMachineName());
}
}

View file

@ -0,0 +1,346 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\CommentManagerInterface;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\comment\Entity\Comment;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\Entity\Entity\EntityViewMode;
use Drupal\user\RoleInterface;
use Drupal\filter\Entity\FilterFormat;
/**
* Tests comment user interfaces.
*
* @group comment
*/
class CommentInterfaceTest extends CommentTestBase {
/**
* Set up comments to have subject and preview disabled.
*/
protected function setUp() {
parent::setUp();
$this->drupalLogin($this->adminUser);
// Make sure that comment field title is not displayed when there's no
// comments posted.
$this->drupalGet($this->node->urlInfo());
$this->assertNoPattern('@<h2[^>]*>Comments</h2>@', 'Comments title is not displayed.');
// Set comments to have subject and preview disabled.
$this->setCommentPreview(DRUPAL_DISABLED);
$this->setCommentForm(TRUE);
$this->setCommentSubject(FALSE);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.');
$this->drupalLogout();
}
/**
* Tests the comment interface.
*/
public function testCommentInterface() {
// Post comment #1 without subject or preview.
$this->drupalLogin($this->webUser);
$comment_text = $this->randomMachineName();
$comment = $this->postComment($this->node, $comment_text);
$this->assertTrue($this->commentExists($comment), 'Comment found.');
// Test the comment field title is displayed when there's comments.
$this->drupalGet($this->node->urlInfo());
$this->assertPattern('@<h2[^>]*>Comments</h2>@', 'Comments title is displayed.');
// Set comments to have subject and preview to required.
$this->drupalLogout();
$this->drupalLogin($this->adminUser);
$this->setCommentSubject(TRUE);
$this->setCommentPreview(DRUPAL_REQUIRED);
$this->drupalLogout();
// Create comment #2 that allows subject and requires preview.
$this->drupalLogin($this->webUser);
$subject_text = $this->randomMachineName();
$comment_text = $this->randomMachineName();
$comment = $this->postComment($this->node, $comment_text, $subject_text, TRUE);
$this->assertTrue($this->commentExists($comment), 'Comment found.');
// Comment as anonymous with preview required.
$this->drupalLogout();
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access content', 'access comments', 'post comments', 'skip comment approval']);
$anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$this->assertTrue($this->commentExists($anonymous_comment), 'Comment found.');
$anonymous_comment->delete();
// Check comment display.
$this->drupalLogin($this->webUser);
$this->drupalGet('node/' . $this->node->id());
$this->assertText($subject_text, 'Individual comment subject found.');
$this->assertText($comment_text, 'Individual comment body found.');
$arguments = [
':link' => base_path() . 'comment/' . $comment->id() . '#comment-' . $comment->id(),
];
$pattern_permalink = '//footer[contains(@class,"comment__meta")]/a[contains(@href,:link) and text()="Permalink"]';
$permalink = $this->xpath($pattern_permalink, $arguments);
$this->assertTrue(!empty($permalink), 'Permalink link found.');
// Set comments to have subject and preview to optional.
$this->drupalLogout();
$this->drupalLogin($this->adminUser);
$this->setCommentSubject(TRUE);
$this->setCommentPreview(DRUPAL_OPTIONAL);
$this->drupalGet('comment/' . $comment->id() . '/edit');
$this->assertTitle(t('Edit comment @title | Drupal', [
'@title' => $comment->getSubject(),
]));
// Test changing the comment author to "Anonymous".
$comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), ['uid' => '']);
$this->assertTrue($comment->getAuthorName() == t('Anonymous') && $comment->getOwnerId() == 0, 'Comment author successfully changed to anonymous.');
// Test changing the comment author to an unverified user.
$random_name = $this->randomMachineName();
$this->drupalGet('comment/' . $comment->id() . '/edit');
$comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), ['name' => $random_name]);
$this->drupalGet('node/' . $this->node->id());
$this->assertText($random_name . ' (' . t('not verified') . ')', 'Comment author successfully changed to an unverified user.');
// Test changing the comment author to a verified user.
$this->drupalGet('comment/' . $comment->id() . '/edit');
$comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), ['uid' => $this->webUser->getUsername() . ' (' . $this->webUser->id() . ')']);
$this->assertTrue($comment->getAuthorName() == $this->webUser->getUsername() && $comment->getOwnerId() == $this->webUser->id(), 'Comment author successfully changed to a registered user.');
$this->drupalLogout();
// Reply to comment #2 creating comment #3 with optional preview and no
// subject though field enabled.
$this->drupalLogin($this->webUser);
// Deliberately use the wrong url to test
// \Drupal\comment\Controller\CommentController::redirectNode().
$this->drupalGet('comment/' . $this->node->id() . '/reply');
// Verify we were correctly redirected.
$this->assertUrl(\Drupal::url('comment.reply', ['entity_type' => 'node', 'entity' => $this->node->id(), 'field_name' => 'comment'], ['absolute' => TRUE]));
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $comment->id());
$this->assertText($subject_text, 'Individual comment-reply subject found.');
$this->assertText($comment_text, 'Individual comment-reply body found.');
$reply = $this->postComment(NULL, $this->randomMachineName(), '', TRUE);
$reply_loaded = Comment::load($reply->id());
$this->assertTrue($this->commentExists($reply, TRUE), 'Reply found.');
$this->assertEqual($comment->id(), $reply_loaded->getParentComment()->id(), 'Pid of a reply to a comment is set correctly.');
// Check the thread of reply grows correctly.
$this->assertEqual(rtrim($comment->getThread(), '/') . '.00/', $reply_loaded->getThread());
// Second reply to comment #2 creating comment #4.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $comment->id());
$this->assertText($comment->getSubject(), 'Individual comment-reply subject found.');
$this->assertText($comment->comment_body->value, 'Individual comment-reply body found.');
$reply = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$reply_loaded = Comment::load($reply->id());
$this->assertTrue($this->commentExists($reply, TRUE), 'Second reply found.');
// Check the thread of second reply grows correctly.
$this->assertEqual(rtrim($comment->getThread(), '/') . '.01/', $reply_loaded->getThread());
// Reply to comment #4 creating comment #5.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $reply_loaded->id());
$this->assertText($reply_loaded->getSubject(), 'Individual comment-reply subject found.');
$this->assertText($reply_loaded->comment_body->value, 'Individual comment-reply body found.');
$reply = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$reply_loaded = Comment::load($reply->id());
$this->assertTrue($this->commentExists($reply, TRUE), 'Second reply found.');
// Check the thread of reply to second reply grows correctly.
$this->assertEqual(rtrim($comment->getThread(), '/') . '.01.00/', $reply_loaded->getThread());
// Edit reply.
$this->drupalGet('comment/' . $reply->id() . '/edit');
$reply = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$this->assertTrue($this->commentExists($reply, TRUE), 'Modified reply found.');
// Confirm a new comment is posted to the correct page.
$this->setCommentsPerPage(2);
$comment_new_page = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$this->assertTrue($this->commentExists($comment_new_page), 'Page one exists. %s');
$this->drupalGet('node/' . $this->node->id(), ['query' => ['page' => 2]]);
$this->assertTrue($this->commentExists($reply, TRUE), 'Page two exists. %s');
$this->setCommentsPerPage(50);
// Attempt to reply to an unpublished comment.
$reply_loaded->setUnpublished();
$reply_loaded->save();
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $reply_loaded->id());
$this->assertResponse(403);
// Attempt to post to node with comments disabled.
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'comment' => [['status' => CommentItemInterface::HIDDEN]]]);
$this->assertTrue($this->node, 'Article node created.');
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$this->assertResponse(403);
$this->assertNoField('edit-comment', 'Comment body field found.');
// Attempt to post to node with read-only comments.
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'comment' => [['status' => CommentItemInterface::CLOSED]]]);
$this->assertTrue($this->node, 'Article node created.');
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$this->assertResponse(403);
$this->assertNoField('edit-comment', 'Comment body field found.');
// Attempt to post to node with comments enabled (check field names etc).
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'comment' => [['status' => CommentItemInterface::OPEN]]]);
$this->assertTrue($this->node, 'Article node created.');
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$this->assertNoText('This discussion is closed', 'Posting to node with comments enabled');
$this->assertField('edit-comment-body-0-value', 'Comment body field found.');
// Delete comment and make sure that reply is also removed.
$this->drupalLogout();
$this->drupalLogin($this->adminUser);
$this->deleteComment($comment);
$this->deleteComment($comment_new_page);
$this->drupalGet('node/' . $this->node->id());
$this->assertFalse($this->commentExists($comment), 'Comment not found.');
$this->assertFalse($this->commentExists($reply, TRUE), 'Reply not found.');
// Enabled comment form on node page.
$this->drupalLogin($this->adminUser);
$this->setCommentForm(TRUE);
$this->drupalLogout();
// Submit comment through node form.
$this->drupalLogin($this->webUser);
$this->drupalGet('node/' . $this->node->id());
$form_comment = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$this->assertTrue($this->commentExists($form_comment), 'Form comment found.');
// Disable comment form on node page.
$this->drupalLogout();
$this->drupalLogin($this->adminUser);
$this->setCommentForm(FALSE);
}
/**
* Test that the subject is automatically filled if disabled or left blank.
*
* When the subject field is blank or disabled, the first 29 characters of the
* comment body are used for the subject. If this would break within a word,
* then the break is put at the previous word boundary instead.
*/
public function testAutoFilledSubject() {
$this->drupalLogin($this->webUser);
$this->drupalGet('node/' . $this->node->id());
// Break when there is a word boundary before 29 characters.
$body_text = 'Lorem ipsum Lorem ipsum Loreming ipsum Lorem ipsum';
$comment1 = $this->postComment(NULL, $body_text, '', TRUE);
$this->assertTrue($this->commentExists($comment1), 'Form comment found.');
$this->assertEqual('Lorem ipsum Lorem ipsum…', $comment1->getSubject());
// Break at 29 characters where there's no boundary before that.
$body_text2 = 'LoremipsumloremipsumLoremingipsumLoremipsum';
$comment2 = $this->postComment(NULL, $body_text2, '', TRUE);
$this->assertEqual('LoremipsumloremipsumLoreming…', $comment2->getSubject());
}
/**
* Test that automatic subject is correctly created from HTML comment text.
*
* This is the same test as in CommentInterfaceTest::testAutoFilledSubject()
* with the additional check that HTML is stripped appropriately prior to
* character-counting.
*/
public function testAutoFilledHtmlSubject() {
// Set up two default (i.e. filtered HTML) input formats, because then we
// can select one of them. Then create a user that can use these formats,
// log the user in, and then GET the node page on which to test the
// comments.
$filtered_html_format = FilterFormat::create([
'format' => 'filtered_html',
'name' => 'Filtered HTML',
]);
$filtered_html_format->save();
$full_html_format = FilterFormat::create([
'format' => 'full_html',
'name' => 'Full HTML',
]);
$full_html_format->save();
$html_user = $this->drupalCreateUser([
'access comments',
'post comments',
'edit own comments',
'skip comment approval',
'access content',
$filtered_html_format->getPermissionName(),
$full_html_format->getPermissionName(),
]);
$this->drupalLogin($html_user);
$this->drupalGet('node/' . $this->node->id());
// HTML should not be included in the character count.
$body_text1 = '<span></span><strong> </strong><span> </span><strong></strong>Hello World<br />';
$edit1 = [
'comment_body[0][value]' => $body_text1,
'comment_body[0][format]' => 'filtered_html',
];
$this->drupalPostForm(NULL, $edit1, t('Save'));
$this->assertEqual('Hello World', Comment::load(1)->getSubject());
// If there's nothing other than HTML, the subject should be '(No subject)'.
$body_text2 = '<span></span><strong> </strong><span> </span><strong></strong> <br />';
$edit2 = [
'comment_body[0][value]' => $body_text2,
'comment_body[0][format]' => 'filtered_html',
];
$this->drupalPostForm(NULL, $edit2, t('Save'));
$this->assertEqual('(No subject)', Comment::load(2)->getSubject());
}
/**
* Tests the comment formatter configured with a custom comment view mode.
*/
public function testViewMode() {
$this->drupalLogin($this->webUser);
$this->drupalGet($this->node->toUrl());
$comment_text = $this->randomMachineName();
// Post a comment.
$this->postComment($this->node, $comment_text);
// Comment displayed in 'default' display mode found and has body text.
$comment_element = $this->cssSelect('.comment-wrapper');
$this->assertTrue(!empty($comment_element));
$this->assertRaw('<p>' . $comment_text . '</p>');
// Create a new comment entity view mode.
$mode = mb_strtolower($this->randomMachineName());
EntityViewMode::create([
'targetEntityType' => 'comment',
'id' => "comment.$mode",
])->save();
// Create the corresponding entity view display for article node-type. Note
// that this new view display mode doesn't contain the comment body.
EntityViewDisplay::create([
'targetEntityType' => 'comment',
'bundle' => 'comment',
'mode' => $mode,
])->setStatus(TRUE)->save();
/** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $node_display */
$node_display = EntityViewDisplay::load('node.article.default');
$formatter = $node_display->getComponent('comment');
// Change the node comment field formatter to use $mode mode instead of
// 'default' mode.
$formatter['settings']['view_mode'] = $mode;
$node_display
->setComponent('comment', $formatter)
->save();
// Reloading the node page to show the same node with its same comment but
// with a different display mode.
$this->drupalGet($this->node->toUrl());
// The comment should exist but without the body text because we used $mode
// mode this time.
$comment_element = $this->cssSelect('.comment-wrapper');
$this->assertTrue(!empty($comment_element));
$this->assertNoRaw('<p>' . $comment_text . '</p>');
}
}

View file

@ -0,0 +1,136 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\BrowserTestBase;
/**
* Tests for comment language.
*
* @group comment
*/
class CommentLanguageTest extends BrowserTestBase {
use CommentTestTrait;
/**
* Modules to install.
*
* We also use the language_test module here to be able to turn on content
* language negotiation. Drupal core does not provide a way in itself to do
* that.
*
* @var array
*/
public static $modules = ['node', 'language', 'language_test', 'comment_test'];
protected function setUp() {
parent::setUp();
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
// Create and log in user.
$admin_user = $this->drupalCreateUser(['administer site configuration', 'administer languages', 'access administration pages', 'administer content types', 'administer comments', 'create article content', 'access comments', 'post comments', 'skip comment approval']);
$this->drupalLogin($admin_user);
// Add language.
$edit = ['predefined_langcode' => 'fr'];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Set "Article" content type to use multilingual support.
$edit = ['language_configuration[language_alterable]' => TRUE];
$this->drupalPostForm('admin/structure/types/manage/article', $edit, t('Save content type'));
// Enable content language negotiation UI.
\Drupal::state()->set('language_test.content_language_type', TRUE);
// Set interface language detection to user and content language detection
// to URL. Disable inheritance from interface language to ensure content
// language will fall back to the default language if no URL language can be
// detected.
$edit = [
'language_interface[enabled][language-user]' => TRUE,
'language_content[enabled][language-url]' => TRUE,
'language_content[enabled][language-interface]' => FALSE,
];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
// Change user language preference, this way interface language is always
// French no matter what path prefix the URLs have.
$edit = ['preferred_langcode' => 'fr'];
$this->drupalPostForm("user/" . $admin_user->id() . "/edit", $edit, t('Save'));
// Create comment field on article.
$this->addDefaultCommentField('node', 'article');
// Make comment body translatable.
$field_storage = FieldStorageConfig::loadByName('comment', 'comment_body');
$field_storage->setTranslatable(TRUE);
$field_storage->save();
$this->assertTrue($field_storage->isTranslatable(), 'Comment body is translatable.');
}
/**
* Test that comment language is properly set.
*/
public function testCommentLanguage() {
// Create two nodes, one for english and one for french, and comment each
// node using both english and french as content language by changing URL
// language prefixes. Meanwhile interface language is always French, which
// is the user language preference. This way we can ensure that node
// language and interface language do not influence comment language, as
// only content language has to.
foreach ($this->container->get('language_manager')->getLanguages() as $node_langcode => $node_language) {
// Create "Article" content.
$title = $this->randomMachineName();
$edit = [
'title[0][value]' => $title,
'body[0][value]' => $this->randomMachineName(),
'langcode[0][value]' => $node_langcode,
'comment[0][status]' => CommentItemInterface::OPEN,
];
$this->drupalPostForm("node/add/article", $edit, t('Save'));
$node = $this->drupalGetNodeByTitle($title);
$prefixes = language_negotiation_url_prefixes();
foreach ($this->container->get('language_manager')->getLanguages() as $langcode => $language) {
// Post a comment with content language $langcode.
$prefix = empty($prefixes[$langcode]) ? '' : $prefixes[$langcode] . '/';
$comment_values[$node_langcode][$langcode] = $this->randomMachineName();
$edit = [
'subject[0][value]' => $this->randomMachineName(),
'comment_body[0][value]' => $comment_values[$node_langcode][$langcode],
];
$this->drupalPostForm($prefix . 'node/' . $node->id(), $edit, t('Preview'));
$this->drupalPostForm(NULL, $edit, t('Save'));
// Check that comment language matches the current content language.
$cids = \Drupal::entityQuery('comment')
->condition('entity_id', $node->id())
->condition('entity_type', 'node')
->condition('field_name', 'comment')
->sort('cid', 'DESC')
->range(0, 1)
->execute();
$comment = Comment::load(reset($cids));
$args = ['%node_language' => $node_langcode, '%comment_language' => $comment->langcode->value, '%langcode' => $langcode];
$this->assertEqual($comment->langcode->value, $langcode, format_string('The comment posted with content language %langcode and belonging to the node with language %node_language has language %comment_language', $args));
$this->assertEqual($comment->comment_body->value, $comment_values[$node_langcode][$langcode], 'Comment body correctly stored.');
}
}
// Check that comment bodies appear in the administration UI.
$this->drupalGet('admin/content/comment');
foreach ($comment_values as $node_values) {
foreach ($node_values as $value) {
$this->assertRaw($value);
}
}
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\comment\Functional;
/**
* Tests comment links altering.
*
* @group comment
*/
class CommentLinksAlterTest extends CommentTestBase {
public static $modules = ['comment_test'];
protected function setUp() {
parent::setUp();
// Enable comment_test.module's hook_comment_links_alter() implementation.
$this->container->get('state')->set('comment_test_links_alter_enabled', TRUE);
}
/**
* Tests comment links altering.
*/
public function testCommentLinksAlter() {
$this->drupalLogin($this->webUser);
$comment_text = $this->randomMachineName();
$subject = $this->randomMachineName();
$comment = $this->postComment($this->node, $comment_text, $subject);
$this->drupalGet('node/' . $this->node->id());
$this->assertLink(t('Report'));
}
}

View file

@ -0,0 +1,146 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\comment\CommentInterface;
use Drupal\user\RoleInterface;
use Drupal\comment\Entity\Comment;
/**
* Basic comment links tests to ensure markup present.
*
* @group comment
*/
class CommentLinksTest extends CommentTestBase {
/**
* Comment being tested.
*
* @var \Drupal\comment\CommentInterface
*/
protected $comment;
/**
* Seen comments, array of comment IDs.
*
* @var array
*/
protected $seen = [];
/**
* Use the main node listing to test rendering on teasers.
*
* @var array
*
* @todo Remove this dependency.
*/
public static $modules = ['views'];
/**
* Tests that comment links are output and can be hidden.
*/
public function testCommentLinks() {
// Bartik theme alters comment links, so use a different theme.
\Drupal::service('theme_handler')->install(['stark']);
$this->config('system.theme')
->set('default', 'stark')
->save();
// Remove additional user permissions from $this->webUser added by setUp(),
// since this test is limited to anonymous and authenticated roles only.
$roles = $this->webUser->getRoles();
entity_delete_multiple('user_role', [reset($roles)]);
// Create a comment via CRUD API functionality, since
// $this->postComment() relies on actual user permissions.
$comment = Comment::create([
'cid' => NULL,
'entity_id' => $this->node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'pid' => 0,
'uid' => 0,
'status' => CommentInterface::PUBLISHED,
'subject' => $this->randomMachineName(),
'hostname' => '127.0.0.1',
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
'comment_body' => [['value' => $this->randomMachineName()]],
]);
$comment->save();
$this->comment = $comment;
// Change comment settings.
$this->setCommentSettings('form_location', CommentItemInterface::FORM_BELOW, 'Set comment form location');
$this->setCommentAnonymous(TRUE);
$this->node->comment = CommentItemInterface::OPEN;
$this->node->save();
// Change user permissions.
$perms = [
'access comments' => 1,
'post comments' => 1,
'skip comment approval' => 1,
'edit own comments' => 1,
];
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, $perms);
$nid = $this->node->id();
// Assert basic link is output, actual functionality is unit-tested in
// \Drupal\comment\Tests\CommentLinkBuilderTest.
foreach (['node', "node/$nid"] as $path) {
$this->drupalGet($path);
// In teaser view, a link containing the comment count is always
// expected.
if ($path == 'node') {
$this->assertLink(t('1 comment'));
}
$this->assertLink('Add new comment');
}
// Change weight to make links go before comment body.
entity_get_display('comment', 'comment', 'default')
->setComponent('links', ['weight' => -100])
->save();
$this->drupalGet($this->node->urlInfo());
$element = $this->cssSelect('article.js-comment > div');
// Get last child element.
$element = end($element);
$this->assertIdentical($element->getTagName(), 'div', 'Last element is comment body.');
// Change weight to make links go after comment body.
entity_get_display('comment', 'comment', 'default')
->setComponent('links', ['weight' => 100])
->save();
$this->drupalGet($this->node->urlInfo());
$element = $this->cssSelect('article.js-comment > div');
// Get last child element.
$element = end($element);
$this->assertNotEmpty($element->find('css', 'ul.links'), 'Last element is comment links.');
// Make sure we can hide node links.
entity_get_display('node', $this->node->bundle(), 'default')
->removeComponent('links')
->save();
$this->drupalGet($this->node->urlInfo());
$this->assertNoLink('1 comment');
$this->assertNoLink('Add new comment');
// Visit the full node, make sure there are links for the comment.
$this->drupalGet('node/' . $this->node->id());
$this->assertText($comment->getSubject());
$this->assertLink('Reply');
// Make sure we can hide comment links.
entity_get_display('comment', 'comment', 'default')
->removeComponent('links')
->save();
$this->drupalGet('node/' . $this->node->id());
$this->assertText($comment->getSubject());
$this->assertNoLink('Reply');
}
}

View file

@ -0,0 +1,137 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Language\LanguageInterface;
use Drupal\comment\CommentInterface;
use Drupal\Core\Url;
use Drupal\comment\Entity\Comment;
/**
* Tests the 'new' indicator posted on comments.
*
* @group comment
*/
class CommentNewIndicatorTest extends CommentTestBase {
/**
* Use the main node listing to test rendering on teasers.
*
* @var array
*
* @todo Remove this dependency.
*/
public static $modules = ['views'];
/**
* Get node "x new comments" metadata from the server for the current user.
*
* @param array $node_ids
* An array of node IDs.
*
* @return \Psr\Http\Message\ResponseInterface
* The HTTP response.
*/
protected function renderNewCommentsNodeLinks(array $node_ids) {
$client = $this->getHttpClient();
$url = Url::fromRoute('comment.new_comments_node_links');
return $client->request('POST', $this->buildUrl($url), [
'cookies' => $this->getSessionCookies(),
'http_errors' => FALSE,
'form_params' => [
'node_ids' => $node_ids,
'field_name' => 'comment',
],
]);
}
/**
* Tests new comment marker.
*/
public function testCommentNewCommentsIndicator() {
// Test if the right links are displayed when no comment is present for the
// node.
$this->drupalLogin($this->adminUser);
$this->drupalGet('node');
$this->assertNoLink(t('@count comments', ['@count' => 0]));
$this->assertLink(t('Read more'));
// Verify the data-history-node-last-comment-timestamp attribute, which is
// used by the drupal.node-new-comments-link library to determine whether
// a "x new comments" link might be necessary or not. We do this in
// JavaScript to prevent breaking the render cache.
$this->assertIdentical(0, count($this->xpath('//*[@data-history-node-last-comment-timestamp]')), 'data-history-node-last-comment-timestamp attribute is not set.');
// Create a new comment. This helper function may be run with different
// comment settings so use $comment->save() to avoid complex setup.
/** @var \Drupal\comment\CommentInterface $comment */
$comment = Comment::create([
'cid' => NULL,
'entity_id' => $this->node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'pid' => 0,
'uid' => $this->loggedInUser->id(),
'status' => CommentInterface::PUBLISHED,
'subject' => $this->randomMachineName(),
'hostname' => '127.0.0.1',
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
'comment_body' => [LanguageInterface::LANGCODE_NOT_SPECIFIED => [$this->randomMachineName()]],
]);
$comment->save();
$this->drupalLogout();
// Log in with 'web user' and check comment links.
$this->drupalLogin($this->webUser);
$this->drupalGet('node');
// Verify the data-history-node-last-comment-timestamp attribute. Given its
// value, the drupal.node-new-comments-link library would determine that the
// node received a comment after the user last viewed it, and hence it would
// perform an HTTP request to render the "new comments" node link.
$this->assertIdentical(1, count($this->xpath('//*[@data-history-node-last-comment-timestamp="' . $comment->getChangedTime() . '"]')), 'data-history-node-last-comment-timestamp attribute is set to the correct value.');
$this->assertIdentical(1, count($this->xpath('//*[@data-history-node-field-name="comment"]')), 'data-history-node-field-name attribute is set to the correct value.');
// The data will be pre-seeded on this particular page in drupalSettings, to
// avoid the need for the client to make a separate request to the server.
$settings = $this->getDrupalSettings();
$this->assertEqual($settings['history'], ['lastReadTimestamps' => [1 => 0]]);
$this->assertEqual($settings['comment'], [
'newCommentsLinks' => [
'node' => [
'comment' => [
1 => [
'new_comment_count' => 1,
'first_new_comment_link' => Url::fromRoute('entity.node.canonical', ['node' => 1])->setOptions([
'fragment' => 'new',
])->toString(),
],
],
],
],
]);
// Pretend the data was not present in drupalSettings, i.e. test the
// separate request to the server.
$response = $this->renderNewCommentsNodeLinks([$this->node->id()]);
$this->assertSame(200, $response->getStatusCode());
$json = Json::decode($response->getBody());
$expected = [
$this->node->id() => [
'new_comment_count' => 1,
'first_new_comment_link' => $this->node->url('canonical', ['fragment' => 'new']),
],
];
$this->assertIdentical($expected, $json);
// Failing to specify node IDs for the endpoint should return a 404.
$response = $this->renderNewCommentsNodeLinks([]);
$this->assertSame(404, $response->getStatusCode());
// Accessing the endpoint as the anonymous user should return a 403.
$this->drupalLogout();
$response = $this->renderNewCommentsNodeLinks([$this->node->id()]);
$this->assertSame(403, $response->getStatusCode());
$response = $this->renderNewCommentsNodeLinks([]);
$this->assertSame(403, $response->getStatusCode());
}
}

View file

@ -0,0 +1,82 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\CommentManagerInterface;
/**
* Tests comments with node access.
*
* Verifies there is no PostgreSQL error when viewing a node with threaded
* comments (a comment and a reply), if a node access module is in use.
*
* @group comment
*/
class CommentNodeAccessTest extends CommentTestBase {
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['node_access_test'];
protected function setUp() {
parent::setUp();
node_access_rebuild();
// Re-create user.
$this->webUser = $this->drupalCreateUser([
'access comments',
'post comments',
'create article content',
'edit own comments',
'node test view',
'skip comment approval',
]);
// Set the author of the created node to the web_user uid.
$this->node->setOwnerId($this->webUser->id())->save();
}
/**
* Test that threaded comments can be viewed.
*/
public function testThreadedCommentView() {
// Set comments to have subject required and preview disabled.
$this->drupalLogin($this->adminUser);
$this->setCommentPreview(DRUPAL_DISABLED);
$this->setCommentForm(TRUE);
$this->setCommentSubject(TRUE);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.');
$this->drupalLogout();
// Post comment.
$this->drupalLogin($this->webUser);
$comment_text = $this->randomMachineName();
$comment_subject = $this->randomMachineName();
$comment = $this->postComment($this->node, $comment_text, $comment_subject);
$this->assertTrue($this->commentExists($comment), 'Comment found.');
// Check comment display.
$this->drupalGet('node/' . $this->node->id());
$this->assertText($comment_subject, 'Individual comment subject found.');
$this->assertText($comment_text, 'Individual comment body found.');
// Reply to comment, creating second comment.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $comment->id());
$reply_text = $this->randomMachineName();
$reply_subject = $this->randomMachineName();
$reply = $this->postComment(NULL, $reply_text, $reply_subject, TRUE);
$this->assertTrue($this->commentExists($reply, TRUE), 'Reply found.');
// Go to the node page and verify comment and reply are visible.
$this->drupalGet('node/' . $this->node->id());
$this->assertText($comment_text);
$this->assertText($comment_subject);
$this->assertText($reply_text);
$this->assertText($reply_subject);
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Entity\Comment;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests that comments behave correctly when the node is changed.
*
* @group comment
*/
class CommentNodeChangesTest extends CommentTestBase {
/**
* Tests that comments are deleted with the node.
*/
public function testNodeDeletion() {
$this->drupalLogin($this->webUser);
$comment = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName());
$this->assertTrue($comment->id(), 'The comment could be loaded.');
$this->node->delete();
$this->assertFalse(Comment::load($comment->id()), 'The comment could not be loaded after the node was deleted.');
// Make sure the comment field storage and all its fields are deleted when
// the node type is deleted.
$this->assertNotNull(FieldStorageConfig::load('node.comment'), 'Comment field storage exists');
$this->assertNotNull(FieldConfig::load('node.article.comment'), 'Comment field exists');
// Delete the node type.
entity_delete_multiple('node_type', [$this->node->bundle()]);
$this->assertNull(FieldStorageConfig::load('node.comment'), 'Comment field storage deleted');
$this->assertNull(FieldConfig::load('node.article.comment'), 'Comment field deleted');
}
}

View file

@ -0,0 +1,497 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\CommentInterface;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Entity\CommentType;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\BrowserTestBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Tests\field_ui\Traits\FieldUiTestTrait;
use Drupal\user\RoleInterface;
/**
* Tests commenting on a test entity.
*
* @group comment
*/
class CommentNonNodeTest extends BrowserTestBase {
use FieldUiTestTrait;
use CommentTestTrait;
public static $modules = ['comment', 'user', 'field_ui', 'entity_test', 'block'];
/**
* An administrative user with permission to configure comment settings.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* The entity to use within tests.
*
* @var \Drupal\entity_test\Entity\EntityTest
*/
protected $entity;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->drupalPlaceBlock('system_breadcrumb_block');
$this->drupalPlaceBlock('page_title_block');
// Create a bundle for entity_test.
entity_test_create_bundle('entity_test', 'Entity Test', 'entity_test');
CommentType::create([
'id' => 'comment',
'label' => 'Comment settings',
'description' => 'Comment settings',
'target_entity_type_id' => 'entity_test',
])->save();
// Create comment field on entity_test bundle.
$this->addDefaultCommentField('entity_test', 'entity_test');
// Verify that bundles are defined correctly.
$bundles = \Drupal::entityManager()->getBundleInfo('comment');
$this->assertEqual($bundles['comment']['label'], 'Comment settings');
// Create test user.
$this->adminUser = $this->drupalCreateUser([
'administer comments',
'skip comment approval',
'post comments',
'access comments',
'view test entity',
'administer entity_test content',
]);
// Enable anonymous and authenticated user comments.
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments',
'post comments',
'skip comment approval',
]);
user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, [
'access comments',
'post comments',
'skip comment approval',
]);
// Create a test entity.
$random_label = $this->randomMachineName();
$data = ['type' => 'entity_test', 'name' => $random_label];
$this->entity = EntityTest::create($data);
$this->entity->save();
}
/**
* Posts a comment.
*
* @param \Drupal\Core\Entity\EntityInterface|null $entity
* Entity to post comment on or NULL to post to the previously loaded page.
* @param string $comment
* Comment body.
* @param string $subject
* Comment subject.
* @param mixed $contact
* Set to NULL for no contact info, TRUE to ignore success checking, and
* array of values to set contact info.
*
* @return \Drupal\comment\CommentInterface
* The new comment entity.
*/
public function postComment(EntityInterface $entity, $comment, $subject = '', $contact = NULL) {
$edit = [];
$edit['comment_body[0][value]'] = $comment;
$field = FieldConfig::loadByName('entity_test', 'entity_test', 'comment');
$preview_mode = $field->getSetting('preview');
// Must get the page before we test for fields.
if ($entity !== NULL) {
$this->drupalGet('comment/reply/entity_test/' . $entity->id() . '/comment');
}
// Determine the visibility of subject form field.
if (entity_get_form_display('comment', 'comment', 'default')->getComponent('subject')) {
// Subject input allowed.
$edit['subject[0][value]'] = $subject;
}
else {
$this->assertNoFieldByName('subject[0][value]', '', 'Subject field not found.');
}
if ($contact !== NULL && is_array($contact)) {
$edit += $contact;
}
switch ($preview_mode) {
case DRUPAL_REQUIRED:
// Preview required so no save button should be found.
$this->assertNoFieldByName('op', t('Save'), 'Save button not found.');
$this->drupalPostForm(NULL, $edit, t('Preview'));
// Don't break here so that we can test post-preview field presence and
// function below.
case DRUPAL_OPTIONAL:
$this->assertFieldByName('op', t('Preview'), 'Preview button found.');
$this->assertFieldByName('op', t('Save'), 'Save button found.');
$this->drupalPostForm(NULL, $edit, t('Save'));
break;
case DRUPAL_DISABLED:
$this->assertNoFieldByName('op', t('Preview'), 'Preview button not found.');
$this->assertFieldByName('op', t('Save'), 'Save button found.');
$this->drupalPostForm(NULL, $edit, t('Save'));
break;
}
$match = [];
// Get comment ID
preg_match('/#comment-([0-9]+)/', $this->getURL(), $match);
// Get comment.
if ($contact !== TRUE) {
// If true then attempting to find error message.
if ($subject) {
$this->assertText($subject, 'Comment subject posted.');
}
$this->assertText($comment, 'Comment body posted.');
$this->assertTrue((!empty($match) && !empty($match[1])), 'Comment ID found.');
}
if (isset($match[1])) {
return Comment::load($match[1]);
}
}
/**
* Checks current page for specified comment.
*
* @param \Drupal\comment\CommentInterface $comment
* The comment object.
* @param bool $reply
* Boolean indicating whether the comment is a reply to another comment.
*
* @return bool
* Boolean indicating whether the comment was found.
*/
public function commentExists(CommentInterface $comment = NULL, $reply = FALSE) {
if ($comment) {
$regex = '/' . ($reply ? '<div class="indented">(.*?)' : '');
$regex .= '<a id="comment-' . $comment->id() . '"(.*?)';
$regex .= $comment->getSubject() . '(.*?)';
$regex .= $comment->comment_body->value . '(.*?)';
$regex .= '/s';
return (boolean) preg_match($regex, $this->getSession()->getPage()->getContent());
}
else {
return FALSE;
}
}
/**
* Checks whether the commenter's contact information is displayed.
*
* @return bool
* Contact info is available.
*/
public function commentContactInfoAvailable() {
return preg_match('/(input).*?(name="name").*?(input).*?(name="mail").*?(input).*?(name="homepage")/s', $this->getSession()->getPage()->getContent());
}
/**
* Performs the specified operation on the specified comment.
*
* @param object $comment
* Comment to perform operation on.
* @param string $operation
* Operation to perform.
* @param bool $approval
* Operation is found on approval page.
*/
public function performCommentOperation($comment, $operation, $approval = FALSE) {
$edit = [];
$edit['operation'] = $operation;
$edit['comments[' . $comment->id() . ']'] = TRUE;
$this->drupalPostForm('admin/content/comment' . ($approval ? '/approval' : ''), $edit, t('Update'));
if ($operation == 'delete') {
$this->drupalPostForm(NULL, [], t('Delete'));
$this->assertRaw(\Drupal::translation()->formatPlural(1, 'Deleted 1 comment.', 'Deleted @count comments.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation]));
}
else {
$this->assertText(t('The update has been performed.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation]));
}
}
/**
* Gets the comment ID for an unapproved comment.
*
* @param string $subject
* Comment subject to find.
*
* @return int
* Comment ID.
*/
public function getUnapprovedComment($subject) {
$this->drupalGet('admin/content/comment/approval');
preg_match('/href="(.*?)#comment-([^"]+)"(.*?)>(' . $subject . ')/', $this->getSession()->getPage()->getContent(), $match);
return $match[2];
}
/**
* Tests anonymous comment functionality.
*/
public function testCommentFunctionality() {
$limited_user = $this->drupalCreateUser([
'administer entity_test fields',
]);
$this->drupalLogin($limited_user);
// Test that default field exists.
$this->drupalGet('entity_test/structure/entity_test/fields');
$this->assertText(t('Comments'));
$this->assertLinkByHref('entity_test/structure/entity_test/fields/entity_test.entity_test.comment');
// Test widget hidden option is not visible when there's no comments.
$this->drupalGet('entity_test/structure/entity_test/fields/entity_test.entity_test.comment');
$this->assertResponse(200);
$this->assertNoField('edit-default-value-input-comment-und-0-status-0');
// Test that field to change cardinality is not available.
$this->drupalGet('entity_test/structure/entity_test/fields/entity_test.entity_test.comment/storage');
$this->assertResponse(200);
$this->assertNoField('cardinality_number');
$this->assertNoField('cardinality');
$this->drupalLogin($this->adminUser);
// Test breadcrumb on comment add page.
$this->drupalGet('comment/reply/entity_test/' . $this->entity->id() . '/comment');
$xpath = '//nav[@class="breadcrumb"]/ol/li[last()]/a';
$this->assertEqual(current($this->xpath($xpath))->getText(), $this->entity->label(), 'Last breadcrumb item is equal to node title on comment reply page.');
// Post a comment.
/** @var \Drupal\comment\CommentInterface $comment1 */
$comment1 = $this->postComment($this->entity, $this->randomMachineName(), $this->randomMachineName());
$this->assertTrue($this->commentExists($comment1), 'Comment on test entity exists.');
// Test breadcrumb on comment reply page.
$this->drupalGet('comment/reply/entity_test/' . $this->entity->id() . '/comment/' . $comment1->id());
$xpath = '//nav[@class="breadcrumb"]/ol/li[last()]/a';
$this->assertEqual(current($this->xpath($xpath))->getText(), $comment1->getSubject(), 'Last breadcrumb item is equal to comment title on comment reply page.');
// Test breadcrumb on comment edit page.
$this->drupalGet('comment/' . $comment1->id() . '/edit');
$xpath = '//nav[@class="breadcrumb"]/ol/li[last()]/a';
$this->assertEqual(current($this->xpath($xpath))->getText(), $comment1->getSubject(), 'Last breadcrumb item is equal to comment subject on edit page.');
// Test breadcrumb on comment delete page.
$this->drupalGet('comment/' . $comment1->id() . '/delete');
$xpath = '//nav[@class="breadcrumb"]/ol/li[last()]/a';
$this->assertEqual(current($this->xpath($xpath))->getText(), $comment1->getSubject(), 'Last breadcrumb item is equal to comment subject on delete confirm page.');
// Unpublish the comment.
$this->performCommentOperation($comment1, 'unpublish');
$this->drupalGet('admin/content/comment/approval');
$this->assertRaw('comments[' . $comment1->id() . ']', 'Comment was unpublished.');
// Publish the comment.
$this->performCommentOperation($comment1, 'publish', TRUE);
$this->drupalGet('admin/content/comment');
$this->assertRaw('comments[' . $comment1->id() . ']', 'Comment was published.');
// Delete the comment.
$this->performCommentOperation($comment1, 'delete');
$this->drupalGet('admin/content/comment');
$this->assertNoRaw('comments[' . $comment1->id() . ']', 'Comment was deleted.');
// Post another comment.
$comment1 = $this->postComment($this->entity, $this->randomMachineName(), $this->randomMachineName());
$this->assertTrue($this->commentExists($comment1), 'Comment on test entity exists.');
// Check that the comment was found.
$this->drupalGet('admin/content/comment');
$this->assertRaw('comments[' . $comment1->id() . ']', 'Comment was published.');
// Check that entity access applies to administrative page.
$this->assertText($this->entity->label(), 'Name of commented account found.');
$limited_user = $this->drupalCreateUser([
'administer comments',
]);
$this->drupalLogin($limited_user);
$this->drupalGet('admin/content/comment');
$this->assertNoText($this->entity->label(), 'No commented account name found.');
$this->drupalLogout();
// Deny anonymous users access to comments.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => FALSE,
'post comments' => FALSE,
'skip comment approval' => FALSE,
'view test entity' => TRUE,
]);
// Attempt to view comments while disallowed.
$this->drupalGet('entity-test/' . $this->entity->id());
$this->assertNoPattern('@<h2[^>]*>Comments</h2>@', 'Comments were not displayed.');
$this->assertNoLink('Add new comment', 'Link to add comment was found.');
// Attempt to view test entity comment form while disallowed.
$this->drupalGet('comment/reply/entity_test/' . $this->entity->id() . '/comment');
$this->assertResponse(403);
$this->assertNoFieldByName('subject[0][value]', '', 'Subject field not found.');
$this->assertNoFieldByName('comment_body[0][value]', '', 'Comment field not found.');
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => FALSE,
'view test entity' => TRUE,
'skip comment approval' => FALSE,
]);
$this->drupalGet('entity_test/' . $this->entity->id());
$this->assertPattern('@<h2[^>]*>Comments</h2>@', 'Comments were displayed.');
$this->assertLink('Log in', 0, 'Link to login was found.');
$this->assertLink('register', 0, 'Link to register was found.');
$this->assertNoFieldByName('subject[0][value]', '', 'Subject field not found.');
$this->assertNoFieldByName('comment_body[0][value]', '', 'Comment field not found.');
// Test the combination of anonymous users being able to post, but not view
// comments, to ensure that access to post comments doesn't grant access to
// view them.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => FALSE,
'post comments' => TRUE,
'skip comment approval' => TRUE,
'view test entity' => TRUE,
]);
$this->drupalGet('entity_test/' . $this->entity->id());
$this->assertNoPattern('@<h2[^>]*>Comments</h2>@', 'Comments were not displayed.');
$this->assertFieldByName('subject[0][value]', '', 'Subject field found.');
$this->assertFieldByName('comment_body[0][value]', '', 'Comment field found.');
$this->drupalGet('comment/reply/entity_test/' . $this->entity->id() . '/comment/' . $comment1->id());
$this->assertResponse(403);
$this->assertNoText($comment1->getSubject(), 'Comment not displayed.');
// Test comment field widget changes.
$limited_user = $this->drupalCreateUser([
'administer entity_test fields',
'view test entity',
'administer entity_test content',
'administer comments',
]);
$this->drupalLogin($limited_user);
$this->drupalGet('entity_test/structure/entity_test/fields/entity_test.entity_test.comment');
$this->assertNoFieldChecked('edit-default-value-input-comment-0-status-0');
$this->assertNoFieldChecked('edit-default-value-input-comment-0-status-1');
$this->assertFieldChecked('edit-default-value-input-comment-0-status-2');
// Test comment option change in field settings.
$edit = [
'default_value_input[comment][0][status]' => CommentItemInterface::CLOSED,
'settings[anonymous]' => COMMENT_ANONYMOUS_MAY_CONTACT,
];
$this->drupalPostForm(NULL, $edit, t('Save settings'));
$this->drupalGet('entity_test/structure/entity_test/fields/entity_test.entity_test.comment');
$this->assertNoFieldChecked('edit-default-value-input-comment-0-status-0');
$this->assertFieldChecked('edit-default-value-input-comment-0-status-1');
$this->assertNoFieldChecked('edit-default-value-input-comment-0-status-2');
$this->assertFieldByName('settings[anonymous]', COMMENT_ANONYMOUS_MAY_CONTACT);
// Add a new comment-type.
$bundle = CommentType::create([
'id' => 'foobar',
'label' => 'Foobar',
'description' => '',
'target_entity_type_id' => 'entity_test',
]);
$bundle->save();
// Add a new comment field.
$storage_edit = [
'settings[comment_type]' => 'foobar',
];
$this->fieldUIAddNewField('entity_test/structure/entity_test', 'foobar', 'Foobar', 'comment', $storage_edit);
// Add a third comment field.
$this->fieldUIAddNewField('entity_test/structure/entity_test', 'barfoo', 'BarFoo', 'comment', $storage_edit);
// Check the field contains the correct comment type.
$field_storage = FieldStorageConfig::load('entity_test.field_barfoo');
$this->assertTrue($field_storage);
$this->assertEqual($field_storage->getSetting('comment_type'), 'foobar');
$this->assertEqual($field_storage->getCardinality(), 1);
// Test the new entity commenting inherits default.
$random_label = $this->randomMachineName();
$data = ['bundle' => 'entity_test', 'name' => $random_label];
$new_entity = EntityTest::create($data);
$new_entity->save();
$this->drupalGet('entity_test/manage/' . $new_entity->id() . '/edit');
$this->assertNoFieldChecked('edit-field-foobar-0-status-1');
$this->assertFieldChecked('edit-field-foobar-0-status-2');
$this->assertNoField('edit-field-foobar-0-status-0');
// @todo Check proper url and form https://www.drupal.org/node/2458323
$this->drupalGet('comment/reply/entity_test/comment/' . $new_entity->id());
$this->assertNoFieldByName('subject[0][value]', '', 'Subject field found.');
$this->assertNoFieldByName('comment_body[0][value]', '', 'Comment field found.');
// Test removal of comment_body field.
$limited_user = $this->drupalCreateUser([
'administer entity_test fields',
'post comments',
'administer comment fields',
'administer comment types',
'view test entity',
]);
$this->drupalLogin($limited_user);
$this->drupalGet('comment/reply/entity_test/' . $this->entity->id() . '/comment');
$this->assertFieldByName('comment_body[0][value]', '', 'Comment body field found.');
$this->fieldUIDeleteField('admin/structure/comment/manage/comment', 'comment.comment.comment_body', 'Comment', 'Comment settings');
$this->drupalGet('comment/reply/entity_test/' . $this->entity->id() . '/comment');
$this->assertNoFieldByName('comment_body[0][value]', '', 'Comment body field not found.');
// Set subject field to autogenerate it.
$edit = ['subject[0][value]' => ''];
$this->drupalPostForm(NULL, $edit, t('Save'));
}
/**
* Tests comment fields cannot be added to entity types without integer IDs.
*/
public function testsNonIntegerIdEntities() {
// Create a bundle for entity_test_string_id.
entity_test_create_bundle('entity_test', 'Entity Test', 'entity_test_string_id');
$limited_user = $this->drupalCreateUser([
'administer entity_test_string_id fields',
]);
$this->drupalLogin($limited_user);
// Visit the Field UI field add page.
$this->drupalGet('entity_test_string_id/structure/entity_test/fields/add-field');
// Ensure field isn't shown for string IDs.
$this->assertNoOption('edit-new-storage-type', 'comment');
// Ensure a core field type shown.
$this->assertOption('edit-new-storage-type', 'boolean');
// Create a bundle for entity_test_no_id.
entity_test_create_bundle('entity_test', 'Entity Test', 'entity_test_no_id');
$this->drupalLogin($this->drupalCreateUser([
'administer entity_test_no_id fields',
]));
// Visit the Field UI field add page.
$this->drupalGet('entity_test_no_id/structure/entity_test/fields/add-field');
// Ensure field isn't shown for empty IDs.
$this->assertNoOption('edit-new-storage-type', 'comment');
// Ensure a core field type shown.
$this->assertOption('edit-new-storage-type', 'boolean');
}
}

View file

@ -0,0 +1,433 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\CommentManagerInterface;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\node\Entity\Node;
/**
* Tests paging of comments and their settings.
*
* @group comment
*/
class CommentPagerTest extends CommentTestBase {
/**
* Confirms comment paging works correctly with flat and threaded comments.
*/
public function testCommentPaging() {
$this->drupalLogin($this->adminUser);
// Set comment variables.
$this->setCommentForm(TRUE);
$this->setCommentSubject(TRUE);
$this->setCommentPreview(DRUPAL_DISABLED);
// Create a node and three comments.
$node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]);
$comments = [];
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_FLAT, 'Comment paging changed.');
// Set comments to one per page so that we are able to test paging without
// needing to insert large numbers of comments.
$this->setCommentsPerPage(1);
// Check the first page of the node, and confirm the correct comments are
// shown.
$this->drupalGet('node/' . $node->id());
$this->assertRaw(t('next'), 'Paging links found.');
$this->assertTrue($this->commentExists($comments[0]), 'Comment 1 appears on page 1.');
$this->assertFalse($this->commentExists($comments[1]), 'Comment 2 does not appear on page 1.');
$this->assertFalse($this->commentExists($comments[2]), 'Comment 3 does not appear on page 1.');
// Check the second page.
$this->drupalGet('node/' . $node->id(), ['query' => ['page' => 1]]);
$this->assertTrue($this->commentExists($comments[1]), 'Comment 2 appears on page 2.');
$this->assertFalse($this->commentExists($comments[0]), 'Comment 1 does not appear on page 2.');
$this->assertFalse($this->commentExists($comments[2]), 'Comment 3 does not appear on page 2.');
// Check the third page.
$this->drupalGet('node/' . $node->id(), ['query' => ['page' => 2]]);
$this->assertTrue($this->commentExists($comments[2]), 'Comment 3 appears on page 3.');
$this->assertFalse($this->commentExists($comments[0]), 'Comment 1 does not appear on page 3.');
$this->assertFalse($this->commentExists($comments[1]), 'Comment 2 does not appear on page 3.');
// Post a reply to the oldest comment and test again.
$oldest_comment = reset($comments);
$this->drupalGet('comment/reply/node/' . $node->id() . '/comment/' . $oldest_comment->id());
$reply = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$this->setCommentsPerPage(2);
// We are still in flat view - the replies should not be on the first page,
// even though they are replies to the oldest comment.
$this->drupalGet('node/' . $node->id(), ['query' => ['page' => 0]]);
$this->assertFalse($this->commentExists($reply, TRUE), 'In flat mode, reply does not appear on page 1.');
// If we switch to threaded mode, the replies on the oldest comment
// should be bumped to the first page and comment 6 should be bumped
// to the second page.
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Switched to threaded mode.');
$this->drupalGet('node/' . $node->id(), ['query' => ['page' => 0]]);
$this->assertTrue($this->commentExists($reply, TRUE), 'In threaded mode, reply appears on page 1.');
$this->assertFalse($this->commentExists($comments[1]), 'In threaded mode, comment 2 has been bumped off of page 1.');
// If (# replies > # comments per page) in threaded expanded view,
// the overage should be bumped.
$reply2 = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$this->drupalGet('node/' . $node->id(), ['query' => ['page' => 0]]);
$this->assertFalse($this->commentExists($reply2, TRUE), 'In threaded mode where # replies > # comments per page, the newest reply does not appear on page 1.');
// Test that the page build process does not somehow generate errors when
// # comments per page is set to 0.
$this->setCommentsPerPage(0);
$this->drupalGet('node/' . $node->id(), ['query' => ['page' => 0]]);
$this->assertFalse($this->commentExists($reply2, TRUE), 'Threaded mode works correctly when comments per page is 0.');
$this->drupalLogout();
}
/**
* Confirms comment paging works correctly with flat and threaded comments.
*/
public function testCommentPermalink() {
$this->drupalLogin($this->adminUser);
// Set comment variables.
$this->setCommentForm(TRUE);
$this->setCommentSubject(TRUE);
$this->setCommentPreview(DRUPAL_DISABLED);
// Create a node and three comments.
$node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]);
$comments = [];
$comments[] = $this->postComment($node, 'comment 1: ' . $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, 'comment 2: ' . $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, 'comment 3: ' . $this->randomMachineName(), $this->randomMachineName(), TRUE);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_FLAT, 'Comment paging changed.');
// Set comments to one per page so that we are able to test paging without
// needing to insert large numbers of comments.
$this->setCommentsPerPage(1);
// Navigate to each comment permalink as anonymous and assert it appears on
// the page.
foreach ($comments as $index => $comment) {
$this->drupalGet($comment->toUrl());
$this->assertTrue($this->commentExists($comment), sprintf('Comment %d appears on page %d.', $index + 1, $index + 1));
}
}
/**
* Tests comment ordering and threading.
*/
public function testCommentOrderingThreading() {
$this->drupalLogin($this->adminUser);
// Set comment variables.
$this->setCommentForm(TRUE);
$this->setCommentSubject(TRUE);
$this->setCommentPreview(DRUPAL_DISABLED);
// Display all the comments on the same page.
$this->setCommentsPerPage(1000);
// Create a node and three comments.
$node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]);
$comments = [];
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Post a reply to the second comment.
$this->drupalGet('comment/reply/node/' . $node->id() . '/comment/' . $comments[1]->id());
$comments[] = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Post a reply to the first comment.
$this->drupalGet('comment/reply/node/' . $node->id() . '/comment/' . $comments[0]->id());
$comments[] = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Post a reply to the last comment.
$this->drupalGet('comment/reply/node/' . $node->id() . '/comment/' . $comments[2]->id());
$comments[] = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Post a reply to the second comment.
$this->drupalGet('comment/reply/node/' . $node->id() . '/comment/' . $comments[3]->id());
$comments[] = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// At this point, the comment tree is:
// - 0
// - 4
// - 1
// - 3
// - 6
// - 2
// - 5
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_FLAT, 'Comment paging changed.');
$expected_order = [
0,
1,
2,
3,
4,
5,
6,
];
$this->drupalGet('node/' . $node->id());
$this->assertCommentOrder($comments, $expected_order);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Switched to threaded mode.');
$expected_order = [
0,
4,
1,
3,
6,
2,
5,
];
$this->drupalGet('node/' . $node->id());
$this->assertCommentOrder($comments, $expected_order);
}
/**
* Asserts that the comments are displayed in the correct order.
*
* @param \Drupal\comment\CommentInterface[] $comments
* An array of comments, must be of the type CommentInterface.
* @param array $expected_order
* An array of keys from $comments describing the expected order.
*/
public function assertCommentOrder(array $comments, array $expected_order) {
$expected_cids = [];
// First, rekey the expected order by cid.
foreach ($expected_order as $key) {
$expected_cids[] = $comments[$key]->id();
}
$comment_anchors = $this->xpath('//a[starts-with(@id,"comment-")]');
$result_order = [];
foreach ($comment_anchors as $anchor) {
$result_order[] = substr($anchor->getAttribute('id'), 8);
}
return $this->assertEqual($expected_cids, $result_order, format_string('Comment order: expected @expected, returned @returned.', ['@expected' => implode(',', $expected_cids), '@returned' => implode(',', $result_order)]));
}
/**
* Tests calculation of first page with new comment.
*/
public function testCommentNewPageIndicator() {
$this->drupalLogin($this->adminUser);
// Set comment variables.
$this->setCommentForm(TRUE);
$this->setCommentSubject(TRUE);
$this->setCommentPreview(DRUPAL_DISABLED);
// Set comments to one per page so that we are able to test paging without
// needing to insert large numbers of comments.
$this->setCommentsPerPage(1);
// Create a node and three comments.
$node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]);
$comments = [];
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Post a reply to the second comment.
$this->drupalGet('comment/reply/node/' . $node->id() . '/comment/' . $comments[1]->id());
$comments[] = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Post a reply to the first comment.
$this->drupalGet('comment/reply/node/' . $node->id() . '/comment/' . $comments[0]->id());
$comments[] = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Post a reply to the last comment.
$this->drupalGet('comment/reply/node/' . $node->id() . '/comment/' . $comments[2]->id());
$comments[] = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// At this point, the comment tree is:
// - 0
// - 4
// - 1
// - 3
// - 2
// - 5
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_FLAT, 'Comment paging changed.');
$expected_pages = [
// Page of comment 5
1 => 5,
// Page of comment 4
2 => 4,
// Page of comment 3
3 => 3,
// Page of comment 2
4 => 2,
// Page of comment 1
5 => 1,
// Page of comment 0
6 => 0,
];
$node = Node::load($node->id());
foreach ($expected_pages as $new_replies => $expected_page) {
$returned_page = \Drupal::entityManager()->getStorage('comment')
->getNewCommentPageNumber($node->get('comment')->comment_count, $new_replies, $node, 'comment');
$this->assertIdentical($expected_page, $returned_page, format_string('Flat mode, @new replies: expected page @expected, returned page @returned.', ['@new' => $new_replies, '@expected' => $expected_page, '@returned' => $returned_page]));
}
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Switched to threaded mode.');
$expected_pages = [
// Page of comment 5
1 => 5,
// Page of comment 4
2 => 1,
// Page of comment 4
3 => 1,
// Page of comment 4
4 => 1,
// Page of comment 4
5 => 1,
// Page of comment 0
6 => 0,
];
\Drupal::entityManager()->getStorage('node')->resetCache([$node->id()]);
$node = Node::load($node->id());
foreach ($expected_pages as $new_replies => $expected_page) {
$returned_page = \Drupal::entityManager()->getStorage('comment')
->getNewCommentPageNumber($node->get('comment')->comment_count, $new_replies, $node, 'comment');
$this->assertEqual($expected_page, $returned_page, format_string('Threaded mode, @new replies: expected page @expected, returned page @returned.', ['@new' => $new_replies, '@expected' => $expected_page, '@returned' => $returned_page]));
}
}
/**
* Confirms comment paging works correctly with two pagers.
*/
public function testTwoPagers() {
// Add another field to article content-type.
$this->addDefaultCommentField('node', 'article', 'comment_2');
// Set default to display comment list with unique pager id.
entity_get_display('node', 'article', 'default')
->setComponent('comment_2', [
'label' => 'hidden',
'type' => 'comment_default',
'weight' => 30,
'settings' => [
'pager_id' => 1,
'view_mode' => 'default',
],
])
->save();
// Make sure pager appears in formatter summary and settings form.
$account = $this->drupalCreateUser(['administer node display']);
$this->drupalLogin($account);
$this->drupalGet('admin/structure/types/manage/article/display');
$this->assertNoText(t('Pager ID: @id', ['@id' => 0]), 'No summary for standard pager');
$this->assertText(t('Pager ID: @id', ['@id' => 1]));
$this->drupalPostForm(NULL, [], 'comment_settings_edit');
// Change default pager to 2.
$this->drupalPostForm(NULL, ['fields[comment][settings_edit_form][settings][pager_id]' => 2], t('Save'));
$this->assertText(t('Pager ID: @id', ['@id' => 2]));
// Revert the changes.
$this->drupalPostForm(NULL, [], 'comment_settings_edit');
$this->drupalPostForm(NULL, ['fields[comment][settings_edit_form][settings][pager_id]' => 0], t('Save'));
$this->assertNoText(t('Pager ID: @id', ['@id' => 0]), 'No summary for standard pager');
$this->drupalLogin($this->adminUser);
// Add a new node with both comment fields open.
$node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]);
// Set comment options.
$comments = [];
foreach (['comment', 'comment_2'] as $field_name) {
$this->setCommentForm(TRUE, $field_name);
$this->setCommentPreview(DRUPAL_OPTIONAL, $field_name);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_FLAT, 'Comment paging changed.', $field_name);
// Set comments to one per page so that we are able to test paging without
// needing to insert large numbers of comments.
$this->setCommentsPerPage(1, $field_name);
for ($i = 0; $i < 3; $i++) {
$comment = t('Comment @count on field @field', [
'@count' => $i + 1,
'@field' => $field_name,
]);
$comments[] = $this->postComment($node, $comment, $comment, TRUE, $field_name);
}
}
// Check the first page of the node, and confirm the correct comments are
// shown.
$this->drupalGet('node/' . $node->id());
$this->assertRaw(t('next'), 'Paging links found.');
$this->assertRaw('Comment 1 on field comment');
$this->assertRaw('Comment 1 on field comment_2');
// Navigate to next page of field 1.
$this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', [':label' => 'Comment 1 on field comment']);
// Check only one pager updated.
$this->assertRaw('Comment 2 on field comment');
$this->assertRaw('Comment 1 on field comment_2');
// Return to page 1.
$this->drupalGet('node/' . $node->id());
// Navigate to next page of field 2.
$this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', [':label' => 'Comment 1 on field comment_2']);
// Check only one pager updated.
$this->assertRaw('Comment 1 on field comment');
$this->assertRaw('Comment 2 on field comment_2');
// Navigate to next page of field 1.
$this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', [':label' => 'Comment 1 on field comment']);
// Check only one pager updated.
$this->assertRaw('Comment 2 on field comment');
$this->assertRaw('Comment 2 on field comment_2');
}
/**
* Follows a link found at a give xpath query.
*
* Will click the first link found with the given xpath query by default,
* or a later one if an index is given.
*
* If the link is discovered and clicked, the test passes. Fail otherwise.
*
* @param string $xpath
* Xpath query that targets an anchor tag, or set of anchor tags.
* @param array $arguments
* An array of arguments with keys in the form ':name' matching the
* placeholders in the query. The values may be either strings or numeric
* values.
* @param int $index
* Link position counting from zero.
*
* @return string|false
* Page contents on success, or FALSE on failure.
*
* @see WebTestBase::clickLink()
*/
protected function clickLinkWithXPath($xpath, $arguments = [], $index = 0) {
$url_before = $this->getUrl();
$urls = $this->xpath($xpath, $arguments);
if (isset($urls[$index])) {
$url_target = $this->getAbsoluteUrl($urls[$index]->getAttribute('href'));
$this->pass(new FormattableMarkup('Clicked link %label (@url_target) from @url_before', ['%label' => $xpath, '@url_target' => $url_target, '@url_before' => $url_before]), 'Browser');
return $this->drupalGet($url_target);
}
$this->fail(new FormattableMarkup('Link %label does not exist on @url_before', ['%label' => $xpath, '@url_before' => $url_before]), 'Browser');
return FALSE;
}
}

View file

@ -0,0 +1,212 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\CommentManagerInterface;
use Drupal\Component\Render\MarkupInterface;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\comment\Entity\Comment;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests comment preview.
*
* @group comment
*/
class CommentPreviewTest extends CommentTestBase {
use TestFileCreationTrait {
getTestFiles as drupalGetTestFiles;
}
/**
* The profile to install as a basis for testing.
*
* Using the standard profile to test user picture display in comments.
*
* @var string
*/
protected $profile = 'standard';
/**
* Tests comment preview.
*/
public function testCommentPreview() {
// As admin user, configure comment settings.
$this->drupalLogin($this->adminUser);
$this->setCommentPreview(DRUPAL_OPTIONAL);
$this->setCommentForm(TRUE);
$this->setCommentSubject(TRUE);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.');
$this->drupalLogout();
// Log in as web user.
$this->drupalLogin($this->webUser);
// Test escaping of the username on the preview form.
\Drupal::service('module_installer')->install(['user_hooks_test']);
\Drupal::state()->set('user_hooks_test_user_format_name_alter', TRUE);
$edit = [];
$edit['subject[0][value]'] = $this->randomMachineName(8);
$edit['comment_body[0][value]'] = $this->randomMachineName(16);
$this->drupalPostForm('node/' . $this->node->id(), $edit, t('Preview'));
$this->assertEscaped('<em>' . $this->webUser->id() . '</em>');
\Drupal::state()->set('user_hooks_test_user_format_name_alter_safe', TRUE);
$this->drupalPostForm('node/' . $this->node->id(), $edit, t('Preview'));
$this->assertTrue($this->webUser->getDisplayName() instanceof MarkupInterface, 'Username is marked safe');
$this->assertNoEscaped('<em>' . $this->webUser->id() . '</em>');
$this->assertRaw('<em>' . $this->webUser->id() . '</em>');
// Add a user picture.
$image = current($this->drupalGetTestFiles('image'));
$user_edit['files[user_picture_0]'] = \Drupal::service('file_system')->realpath($image->uri);
$this->drupalPostForm('user/' . $this->webUser->id() . '/edit', $user_edit, t('Save'));
// As the web user, fill in the comment form and preview the comment.
$this->drupalPostForm('node/' . $this->node->id(), $edit, t('Preview'));
// Check that the preview is displaying the title and body.
$this->assertTitle(t('Preview comment | Drupal'), 'Page title is "Preview comment".');
$this->assertText($edit['subject[0][value]'], 'Subject displayed.');
$this->assertText($edit['comment_body[0][value]'], 'Comment displayed.');
// Check that the title and body fields are displayed with the correct values.
$this->assertFieldByName('subject[0][value]', $edit['subject[0][value]'], 'Subject field displayed.');
$this->assertFieldByName('comment_body[0][value]', $edit['comment_body[0][value]'], 'Comment field displayed.');
// Check that the user picture is displayed.
$this->assertFieldByXPath("//article[contains(@class, 'preview')]//div[contains(@class, 'user-picture')]//img", NULL, 'User picture displayed.');
}
/**
* Tests comment preview.
*/
public function testCommentPreviewDuplicateSubmission() {
// As admin user, configure comment settings.
$this->drupalLogin($this->adminUser);
$this->setCommentPreview(DRUPAL_OPTIONAL);
$this->setCommentForm(TRUE);
$this->setCommentSubject(TRUE);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.');
$this->drupalLogout();
// Log in as web user.
$this->drupalLogin($this->webUser);
// As the web user, fill in the comment form and preview the comment.
$edit = [];
$edit['subject[0][value]'] = $this->randomMachineName(8);
$edit['comment_body[0][value]'] = $this->randomMachineName(16);
$this->drupalPostForm('node/' . $this->node->id(), $edit, t('Preview'));
// Check that the preview is displaying the title and body.
$this->assertTitle(t('Preview comment | Drupal'), 'Page title is "Preview comment".');
$this->assertText($edit['subject[0][value]'], 'Subject displayed.');
$this->assertText($edit['comment_body[0][value]'], 'Comment displayed.');
// Check that the title and body fields are displayed with the correct values.
$this->assertFieldByName('subject[0][value]', $edit['subject[0][value]'], 'Subject field displayed.');
$this->assertFieldByName('comment_body[0][value]', $edit['comment_body[0][value]'], 'Comment field displayed.');
// Store the content of this page.
$this->drupalPostForm(NULL, [], 'Save');
$this->assertText('Your comment has been posted.');
$elements = $this->xpath('//section[contains(@class, "comment-wrapper")]/article');
$this->assertEqual(1, count($elements));
// Go back and re-submit the form.
$this->getSession()->getDriver()->back();
$submit_button = $this->assertSession()->buttonExists('Save');
$submit_button->click();
$this->assertText('Your comment has been posted.');
$elements = $this->xpath('//section[contains(@class, "comment-wrapper")]/article');
$this->assertEqual(2, count($elements));
}
/**
* Tests comment edit, preview, and save.
*/
public function testCommentEditPreviewSave() {
$web_user = $this->drupalCreateUser(['access comments', 'post comments', 'skip comment approval', 'edit own comments']);
$this->drupalLogin($this->adminUser);
$this->setCommentPreview(DRUPAL_OPTIONAL);
$this->setCommentForm(TRUE);
$this->setCommentSubject(TRUE);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.');
$edit = [];
$date = new DrupalDateTime('2008-03-02 17:23');
$edit['subject[0][value]'] = $this->randomMachineName(8);
$edit['comment_body[0][value]'] = $this->randomMachineName(16);
$edit['uid'] = $web_user->getUsername() . ' (' . $web_user->id() . ')';
$edit['date[date]'] = $date->format('Y-m-d');
$edit['date[time]'] = $date->format('H:i:s');
$raw_date = $date->getTimestamp();
$expected_text_date = format_date($raw_date);
$expected_form_date = $date->format('Y-m-d');
$expected_form_time = $date->format('H:i:s');
$comment = $this->postComment($this->node, $edit['subject[0][value]'], $edit['comment_body[0][value]'], TRUE);
$this->drupalPostForm('comment/' . $comment->id() . '/edit', $edit, t('Preview'));
// Check that the preview is displaying the subject, comment, author and date correctly.
$this->assertTitle(t('Preview comment | Drupal'), 'Page title is "Preview comment".');
$this->assertText($edit['subject[0][value]'], 'Subject displayed.');
$this->assertText($edit['comment_body[0][value]'], 'Comment displayed.');
$this->assertText($web_user->getUsername(), 'Author displayed.');
$this->assertText($expected_text_date, 'Date displayed.');
// Check that the subject, comment, author and date fields are displayed with the correct values.
$this->assertFieldByName('subject[0][value]', $edit['subject[0][value]'], 'Subject field displayed.');
$this->assertFieldByName('comment_body[0][value]', $edit['comment_body[0][value]'], 'Comment field displayed.');
$this->assertFieldByName('uid', $edit['uid'], 'Author field displayed.');
$this->assertFieldByName('date[date]', $edit['date[date]'], 'Date field displayed.');
$this->assertFieldByName('date[time]', $edit['date[time]'], 'Time field displayed.');
// Check that saving a comment produces a success message.
$this->drupalPostForm('comment/' . $comment->id() . '/edit', $edit, t('Save'));
$this->assertText(t('Your comment has been posted.'), 'Comment posted.');
// Check that the comment fields are correct after loading the saved comment.
$this->drupalGet('comment/' . $comment->id() . '/edit');
$this->assertFieldByName('subject[0][value]', $edit['subject[0][value]'], 'Subject field displayed.');
$this->assertFieldByName('comment_body[0][value]', $edit['comment_body[0][value]'], 'Comment field displayed.');
$this->assertFieldByName('uid', $edit['uid'], 'Author field displayed.');
$this->assertFieldByName('date[date]', $expected_form_date, 'Date field displayed.');
$this->assertFieldByName('date[time]', $expected_form_time, 'Time field displayed.');
// Submit the form using the displayed values.
$displayed = [];
$displayed['subject[0][value]'] = current($this->xpath("//input[@id='edit-subject-0-value']"))->getValue();
$displayed['comment_body[0][value]'] = current($this->xpath("//textarea[@id='edit-comment-body-0-value']"))->getValue();
$displayed['uid'] = current($this->xpath("//input[@id='edit-uid']"))->getValue();
$displayed['date[date]'] = current($this->xpath("//input[@id='edit-date-date']"))->getValue();
$displayed['date[time]'] = current($this->xpath("//input[@id='edit-date-time']"))->getValue();
$this->drupalPostForm('comment/' . $comment->id() . '/edit', $displayed, t('Save'));
// Check that the saved comment is still correct.
$comment_storage = \Drupal::entityManager()->getStorage('comment');
$comment_storage->resetCache([$comment->id()]);
/** @var \Drupal\comment\CommentInterface $comment_loaded */
$comment_loaded = Comment::load($comment->id());
$this->assertEqual($comment_loaded->getSubject(), $edit['subject[0][value]'], 'Subject loaded.');
$this->assertEqual($comment_loaded->comment_body->value, $edit['comment_body[0][value]'], 'Comment body loaded.');
$this->assertEqual($comment_loaded->getOwner()->id(), $web_user->id(), 'Name loaded.');
$this->assertEqual($comment_loaded->getCreatedTime(), $raw_date, 'Date loaded.');
$this->drupalLogout();
// Check that the date and time of the comment are correct when edited by
// non-admin users.
$user_edit = [];
$expected_created_time = $comment_loaded->getCreatedTime();
$this->drupalLogin($web_user);
// Web user cannot change the comment author.
unset($edit['uid']);
$this->drupalPostForm('comment/' . $comment->id() . '/edit', $user_edit, t('Save'));
$comment_storage->resetCache([$comment->id()]);
$comment_loaded = Comment::load($comment->id());
$this->assertEqual($comment_loaded->getCreatedTime(), $expected_created_time, 'Expected date and time for comment edited.');
$this->drupalLogout();
}
}

View file

@ -0,0 +1,79 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\system\Tests\Cache\AssertPageCacheContextsAndTagsTrait;
/**
* Tests comments as part of an RSS feed.
*
* @group comment
*/
class CommentRssTest extends CommentTestBase {
use AssertPageCacheContextsAndTagsTrait;
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['views'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Setup the rss view display.
EntityViewDisplay::create([
'status' => TRUE,
'targetEntityType' => 'node',
'bundle' => 'article',
'mode' => 'rss',
'content' => ['links' => ['weight' => 100]],
])->save();
}
/**
* Tests comments as part of an RSS feed.
*/
public function testCommentRss() {
// Find comment in RSS feed.
$this->drupalLogin($this->webUser);
$this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName());
$this->drupalGet('rss.xml');
$cache_contexts = [
'languages:language_interface',
'theme',
'url.site',
'user.node_grants:view',
'user.permissions',
'timezone',
];
$this->assertCacheContexts($cache_contexts);
$cache_context_tags = \Drupal::service('cache_contexts_manager')->convertTokensToKeys($cache_contexts)->getCacheTags();
$this->assertCacheTags(Cache::mergeTags($cache_context_tags, [
'config:views.view.frontpage',
'node:1', 'node_list',
'node_view',
'user:3',
]));
$raw = '<comments>' . $this->node->url('canonical', ['fragment' => 'comments', 'absolute' => TRUE]) . '</comments>';
$this->assertRaw($raw, 'Comments as part of RSS feed.');
// Hide comments from RSS feed and check presence.
$this->node->set('comment', CommentItemInterface::HIDDEN);
$this->node->save();
$this->drupalGet('rss.xml');
$this->assertNoRaw($raw, 'Hidden comments is not a part of RSS feed.');
}
}

View file

@ -0,0 +1,118 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\CommentManagerInterface;
use Drupal\comment\Entity\Comment;
use Drupal\user\RoleInterface;
/**
* Tests comment statistics on nodes.
*
* @group comment
*/
class CommentStatisticsTest extends CommentTestBase {
/**
* A secondary user for posting comments.
*
* @var \Drupal\user\UserInterface
*/
protected $webUser2;
protected function setUp() {
parent::setUp();
// Create a second user to post comments.
$this->webUser2 = $this->drupalCreateUser([
'post comments',
'create article content',
'edit own comments',
'post comments',
'skip comment approval',
'access comments',
'access content',
]);
}
/**
* Tests the node comment statistics.
*/
public function testCommentNodeCommentStatistics() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
// Set comments to have subject and preview disabled.
$this->drupalLogin($this->adminUser);
$this->setCommentPreview(DRUPAL_DISABLED);
$this->setCommentForm(TRUE);
$this->setCommentSubject(FALSE);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.');
$this->drupalLogout();
// Checks the initial values of node comment statistics with no comment.
$node = $node_storage->load($this->node->id());
$this->assertEqual($node->get('comment')->last_comment_timestamp, $this->node->getCreatedTime(), 'The initial value of node last_comment_timestamp is the node created date.');
$this->assertEqual($node->get('comment')->last_comment_name, NULL, 'The initial value of node last_comment_name is NULL.');
$this->assertEqual($node->get('comment')->last_comment_uid, $this->webUser->id(), 'The initial value of node last_comment_uid is the node uid.');
$this->assertEqual($node->get('comment')->comment_count, 0, 'The initial value of node comment_count is zero.');
// Post comment #1 as web_user2.
$this->drupalLogin($this->webUser2);
$comment_text = $this->randomMachineName();
$this->postComment($this->node, $comment_text);
// Checks the new values of node comment statistics with comment #1.
// The node cache needs to be reset before reload.
$node_storage->resetCache([$this->node->id()]);
$node = $node_storage->load($this->node->id());
$this->assertEqual($node->get('comment')->last_comment_name, NULL, 'The value of node last_comment_name is NULL.');
$this->assertEqual($node->get('comment')->last_comment_uid, $this->webUser2->id(), 'The value of node last_comment_uid is the comment #1 uid.');
$this->assertEqual($node->get('comment')->comment_count, 1, 'The value of node comment_count is 1.');
// Prepare for anonymous comment submission (comment approval enabled).
$this->drupalLogin($this->adminUser);
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => TRUE,
'skip comment approval' => FALSE,
]);
// Ensure that the poster can leave some contact info.
$this->setCommentAnonymous('1');
$this->drupalLogout();
// Post comment #2 as anonymous (comment approval enabled).
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), '', TRUE);
// Checks the new values of node comment statistics with comment #2 and
// ensure they haven't changed since the comment has not been moderated.
// The node needs to be reloaded with the cache reset.
$node_storage->resetCache([$this->node->id()]);
$node = $node_storage->load($this->node->id());
$this->assertEqual($node->get('comment')->last_comment_name, NULL, 'The value of node last_comment_name is still NULL.');
$this->assertEqual($node->get('comment')->last_comment_uid, $this->webUser2->id(), 'The value of node last_comment_uid is still the comment #1 uid.');
$this->assertEqual($node->get('comment')->comment_count, 1, 'The value of node comment_count is still 1.');
// Prepare for anonymous comment submission (no approval required).
$this->drupalLogin($this->adminUser);
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => TRUE,
'skip comment approval' => TRUE,
]);
$this->drupalLogout();
// Post comment #3 as anonymous.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), '', ['name' => $this->randomMachineName()]);
$comment_loaded = Comment::load($anonymous_comment->id());
// Checks the new values of node comment statistics with comment #3.
// The node needs to be reloaded with the cache reset.
$node_storage->resetCache([$this->node->id()]);
$node = $node_storage->load($this->node->id());
$this->assertEqual($node->get('comment')->last_comment_name, $comment_loaded->getAuthorName(), 'The value of node last_comment_name is the name of the anonymous user.');
$this->assertEqual($node->get('comment')->last_comment_uid, 0, 'The value of node last_comment_uid is zero.');
$this->assertEqual($node->get('comment')->comment_count, 2, 'The value of node comment_count is 2.');
}
}

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\node\Entity\NodeType;
use Drupal\Tests\BrowserTestBase;
@ -86,14 +85,14 @@ class CommentStatusFieldAccessTest extends BrowserTestBase {
$assert->fieldNotExists('comment[0][status]');
$this->submitForm([
'title[0][value]' => 'Node 1',
], t('Save and publish'));
], t('Save'));
$assert->fieldExists('subject[0][value]');
$this->drupalLogin($this->commentAdmin);
$this->drupalGet('node/add/article');
$assert->fieldExists('comment[0][status]');
$this->submitForm([
'title[0][value]' => 'Node 2',
], t('Save and publish'));
], t('Save'));
$assert->fieldExists('subject[0][value]');
}

View file

@ -0,0 +1,403 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Entity\CommentType;
use Drupal\comment\Entity\Comment;
use Drupal\comment\CommentInterface;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\field\Entity\FieldConfig;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\node\Entity\NodeType;
use Drupal\Tests\BrowserTestBase;
/**
* Provides setup and helper methods for comment tests.
*/
abstract class CommentTestBase extends BrowserTestBase {
use CommentTestTrait;
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['block', 'comment', 'node', 'history', 'field_ui', 'datetime'];
/**
* An administrative user with permission to configure comment settings.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* A normal user with permission to post comments.
*
* @var \Drupal\user\UserInterface
*/
protected $webUser;
/**
* A test node to which comments will be posted.
*
* @var \Drupal\node\NodeInterface
*/
protected $node;
protected function setUp() {
parent::setUp();
// Create an article content type only if it does not yet exist, so that
// child classes may specify the standard profile.
$types = NodeType::loadMultiple();
if (empty($types['article'])) {
$this->drupalCreateContentType(['type' => 'article', 'name' => t('Article')]);
}
// Create two test users.
$this->adminUser = $this->drupalCreateUser([
'administer content types',
'administer comments',
'administer comment types',
'administer comment fields',
'administer comment display',
'skip comment approval',
'post comments',
'access comments',
// Usernames aren't shown in comment edit form autocomplete unless this
// permission is granted.
'access user profiles',
'access content',
]);
$this->webUser = $this->drupalCreateUser([
'access comments',
'post comments',
'create article content',
'edit own comments',
'skip comment approval',
'access content',
]);
// Create comment field on article.
$this->addDefaultCommentField('node', 'article');
// Create a test node authored by the web user.
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]);
$this->drupalPlaceBlock('local_tasks_block');
}
/**
* Posts a comment.
*
* @param \Drupal\Core\Entity\EntityInterface|null $entity
* Node to post comment on or NULL to post to the previously loaded page.
* @param string $comment
* Comment body.
* @param string $subject
* Comment subject.
* @param string $contact
* Set to NULL for no contact info, TRUE to ignore success checking, and
* array of values to set contact info.
* @param string $field_name
* (optional) Field name through which the comment should be posted.
* Defaults to 'comment'.
*
* @return \Drupal\comment\CommentInterface|null
* The posted comment or NULL when posted comment was not found.
*/
public function postComment($entity, $comment, $subject = '', $contact = NULL, $field_name = 'comment') {
$edit = [];
$edit['comment_body[0][value]'] = $comment;
if ($entity !== NULL) {
$field = FieldConfig::loadByName($entity->getEntityTypeId(), $entity->bundle(), $field_name);
}
else {
$field = FieldConfig::loadByName('node', 'article', $field_name);
}
$preview_mode = $field->getSetting('preview');
// Must get the page before we test for fields.
if ($entity !== NULL) {
$this->drupalGet('comment/reply/' . $entity->getEntityTypeId() . '/' . $entity->id() . '/' . $field_name);
}
// Determine the visibility of subject form field.
if (entity_get_form_display('comment', 'comment', 'default')->getComponent('subject')) {
// Subject input allowed.
$edit['subject[0][value]'] = $subject;
}
else {
$this->assertNoFieldByName('subject[0][value]', '', 'Subject field not found.');
}
if ($contact !== NULL && is_array($contact)) {
$edit += $contact;
}
switch ($preview_mode) {
case DRUPAL_REQUIRED:
// Preview required so no save button should be found.
$this->assertNoFieldByName('op', t('Save'), 'Save button not found.');
$this->drupalPostForm(NULL, $edit, t('Preview'));
// Don't break here so that we can test post-preview field presence and
// function below.
case DRUPAL_OPTIONAL:
$this->assertFieldByName('op', t('Preview'), 'Preview button found.');
$this->assertFieldByName('op', t('Save'), 'Save button found.');
$this->drupalPostForm(NULL, $edit, t('Save'));
break;
case DRUPAL_DISABLED:
$this->assertNoFieldByName('op', t('Preview'), 'Preview button not found.');
$this->assertFieldByName('op', t('Save'), 'Save button found.');
$this->drupalPostForm(NULL, $edit, t('Save'));
break;
}
$match = [];
// Get comment ID
preg_match('/#comment-([0-9]+)/', $this->getURL(), $match);
// Get comment.
if ($contact !== TRUE) {
// If true then attempting to find error message.
if ($subject) {
$this->assertText($subject, 'Comment subject posted.');
}
$this->assertText($comment, 'Comment body posted.');
$this->assertTrue((!empty($match) && !empty($match[1])), 'Comment id found.');
}
if (isset($match[1])) {
\Drupal::entityManager()->getStorage('comment')->resetCache([$match[1]]);
return Comment::load($match[1]);
}
}
/**
* Checks current page for specified comment.
*
* @param \Drupal\comment\CommentInterface $comment
* The comment object.
* @param bool $reply
* Boolean indicating whether the comment is a reply to another comment.
*
* @return bool
* Boolean indicating whether the comment was found.
*/
public function commentExists(CommentInterface $comment = NULL, $reply = FALSE) {
if ($comment) {
$comment_element = $this->cssSelect('.comment-wrapper ' . ($reply ? '.indented ' : '') . '#comment-' . $comment->id() . ' ~ article');
if (empty($comment_element)) {
return FALSE;
}
$comment_title = $comment_element[0]->find('xpath', 'div/h3/a');
if (empty($comment_title) || $comment_title->getText() !== $comment->getSubject()) {
return FALSE;
}
$comment_body = $comment_element[0]->find('xpath', 'div/div/p');
if (empty($comment_body) || $comment_body->getText() !== $comment->comment_body->value) {
return FALSE;
}
return TRUE;
}
else {
return FALSE;
}
}
/**
* Deletes a comment.
*
* @param \Drupal\comment\CommentInterface $comment
* Comment to delete.
*/
public function deleteComment(CommentInterface $comment) {
$this->drupalPostForm('comment/' . $comment->id() . '/delete', [], t('Delete'));
$this->assertText(t('The comment and all its replies have been deleted.'), 'Comment deleted.');
}
/**
* Sets the value governing whether the subject field should be enabled.
*
* @param bool $enabled
* Boolean specifying whether the subject field should be enabled.
*/
public function setCommentSubject($enabled) {
$form_display = entity_get_form_display('comment', 'comment', 'default');
if ($enabled) {
$form_display->setComponent('subject', [
'type' => 'string_textfield',
]);
}
else {
$form_display->removeComponent('subject');
}
$form_display->save();
// Display status message.
$this->pass('Comment subject ' . ($enabled ? 'enabled' : 'disabled') . '.');
}
/**
* Sets the value governing the previewing mode for the comment form.
*
* @param int $mode
* The preview mode: DRUPAL_DISABLED, DRUPAL_OPTIONAL or DRUPAL_REQUIRED.
* @param string $field_name
* (optional) Field name through which the comment should be posted.
* Defaults to 'comment'.
*/
public function setCommentPreview($mode, $field_name = 'comment') {
switch ($mode) {
case DRUPAL_DISABLED:
$mode_text = 'disabled';
break;
case DRUPAL_OPTIONAL:
$mode_text = 'optional';
break;
case DRUPAL_REQUIRED:
$mode_text = 'required';
break;
}
$this->setCommentSettings('preview', $mode, format_string('Comment preview @mode_text.', ['@mode_text' => $mode_text]), $field_name);
}
/**
* Sets the value governing whether the comment form is on its own page.
*
* @param bool $enabled
* TRUE if the comment form should be displayed on the same page as the
* comments; FALSE if it should be displayed on its own page.
* @param string $field_name
* (optional) Field name through which the comment should be posted.
* Defaults to 'comment'.
*/
public function setCommentForm($enabled, $field_name = 'comment') {
$this->setCommentSettings('form_location', ($enabled ? CommentItemInterface::FORM_BELOW : CommentItemInterface::FORM_SEPARATE_PAGE), 'Comment controls ' . ($enabled ? 'enabled' : 'disabled') . '.', $field_name);
}
/**
* Sets the value governing restrictions on anonymous comments.
*
* @param int $level
* The level of the contact information allowed for anonymous comments:
* - 0: No contact information allowed.
* - 1: Contact information allowed but not required.
* - 2: Contact information required.
*/
public function setCommentAnonymous($level) {
$this->setCommentSettings('anonymous', $level, format_string('Anonymous commenting set to level @level.', ['@level' => $level]));
}
/**
* Sets the value specifying the default number of comments per page.
*
* @param int $number
* Comments per page value.
* @param string $field_name
* (optional) Field name through which the comment should be posted.
* Defaults to 'comment'.
*/
public function setCommentsPerPage($number, $field_name = 'comment') {
$this->setCommentSettings('per_page', $number, format_string('Number of comments per page set to @number.', ['@number' => $number]), $field_name);
}
/**
* Sets a comment settings variable for the article content type.
*
* @param string $name
* Name of variable.
* @param string $value
* Value of variable.
* @param string $message
* Status message to display.
* @param string $field_name
* (optional) Field name through which the comment should be posted.
* Defaults to 'comment'.
*/
public function setCommentSettings($name, $value, $message, $field_name = 'comment') {
$field = FieldConfig::loadByName('node', 'article', $field_name);
$field->setSetting($name, $value);
$field->save();
// Display status message.
$this->pass($message);
}
/**
* Checks whether the commenter's contact information is displayed.
*
* @return bool
* Contact info is available.
*/
public function commentContactInfoAvailable() {
return preg_match('/(input).*?(name="name").*?(input).*?(name="mail").*?(input).*?(name="homepage")/s', $this->getSession()->getPage()->getContent());
}
/**
* Performs the specified operation on the specified comment.
*
* @param \Drupal\comment\CommentInterface $comment
* Comment to perform operation on.
* @param string $operation
* Operation to perform.
* @param bool $approval
* Operation is found on approval page.
*/
public function performCommentOperation(CommentInterface $comment, $operation, $approval = FALSE) {
$edit = [];
$edit['operation'] = $operation;
$edit['comments[' . $comment->id() . ']'] = TRUE;
$this->drupalPostForm('admin/content/comment' . ($approval ? '/approval' : ''), $edit, t('Update'));
if ($operation == 'delete') {
$this->drupalPostForm(NULL, [], t('Delete'));
$this->assertRaw(\Drupal::translation()->formatPlural(1, 'Deleted 1 comment.', 'Deleted @count comments.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation]));
}
else {
$this->assertText(t('The update has been performed.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation]));
}
}
/**
* Gets the comment ID for an unapproved comment.
*
* @param string $subject
* Comment subject to find.
*
* @return int
* Comment id.
*/
public function getUnapprovedComment($subject) {
$this->drupalGet('admin/content/comment/approval');
preg_match('/href="(.*?)#comment-([^"]+)"(.*?)>(' . $subject . ')/', $this->getSession()->getPage()->getContent(), $match);
return $match[2];
}
/**
* Creates a comment comment type (bundle).
*
* @param string $label
* The comment type label.
*
* @return \Drupal\comment\Entity\CommentType
* Created comment type.
*/
protected function createCommentType($label) {
$bundle = CommentType::create([
'id' => $label,
'label' => $label,
'description' => '',
'target_entity_type_id' => 'node',
]);
$bundle->save();
return $bundle;
}
}

View file

@ -0,0 +1,171 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\CommentManagerInterface;
/**
* Tests to make sure the comment number increments properly.
*
* @group comment
*/
class CommentThreadingTest extends CommentTestBase {
/**
* Tests the comment threading.
*/
public function testCommentThreading() {
// Set comments to have a subject with preview disabled.
$this->drupalLogin($this->adminUser);
$this->setCommentPreview(DRUPAL_DISABLED);
$this->setCommentForm(TRUE);
$this->setCommentSubject(TRUE);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.');
$this->drupalLogout();
// Create a node.
$this->drupalLogin($this->webUser);
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]);
// Post comment #1.
$this->drupalLogin($this->webUser);
$subject_text = $this->randomMachineName();
$comment_text = $this->randomMachineName();
$comment1 = $this->postComment($this->node, $comment_text, $subject_text, TRUE);
// Confirm that the comment was created and has the correct threading.
$this->assertTrue($this->commentExists($comment1), 'Comment #1. Comment found.');
$this->assertEqual($comment1->getThread(), '01/');
// Confirm that there is no reference to a parent comment.
$this->assertNoParentLink($comment1->id());
// Post comment #2 following the comment #1 to test if it correctly jumps
// out the indentation in case there is a thread above.
$subject_text = $this->randomMachineName();
$comment_text = $this->randomMachineName();
$this->postComment($this->node, $comment_text, $subject_text, TRUE);
// Reply to comment #1 creating comment #1_3.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $comment1->id());
$comment1_3 = $this->postComment(NULL, $this->randomMachineName(), '', TRUE);
// Confirm that the comment was created and has the correct threading.
$this->assertTrue($this->commentExists($comment1_3, TRUE), 'Comment #1_3. Reply found.');
$this->assertEqual($comment1_3->getThread(), '01.00/');
// Confirm that there is a link to the parent comment.
$this->assertParentLink($comment1_3->id(), $comment1->id());
// Reply to comment #1_3 creating comment #1_3_4.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $comment1_3->id());
$comment1_3_4 = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Confirm that the comment was created and has the correct threading.
$this->assertTrue($this->commentExists($comment1_3_4, TRUE), 'Comment #1_3_4. Second reply found.');
$this->assertEqual($comment1_3_4->getThread(), '01.00.00/');
// Confirm that there is a link to the parent comment.
$this->assertParentLink($comment1_3_4->id(), $comment1_3->id());
// Reply to comment #1 creating comment #1_5.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $comment1->id());
$comment1_5 = $this->postComment(NULL, $this->randomMachineName(), '', TRUE);
// Confirm that the comment was created and has the correct threading.
$this->assertTrue($this->commentExists($comment1_5), 'Comment #1_5. Third reply found.');
$this->assertEqual($comment1_5->getThread(), '01.01/');
// Confirm that there is a link to the parent comment.
$this->assertParentLink($comment1_5->id(), $comment1->id());
// Post comment #3 overall comment #5.
$this->drupalLogin($this->webUser);
$subject_text = $this->randomMachineName();
$comment_text = $this->randomMachineName();
$comment5 = $this->postComment($this->node, $comment_text, $subject_text, TRUE);
// Confirm that the comment was created and has the correct threading.
$this->assertTrue($this->commentExists($comment5), 'Comment #5. Second comment found.');
$this->assertEqual($comment5->getThread(), '03/');
// Confirm that there is no link to a parent comment.
$this->assertNoParentLink($comment5->id());
// Reply to comment #5 creating comment #5_6.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $comment5->id());
$comment5_6 = $this->postComment(NULL, $this->randomMachineName(), '', TRUE);
// Confirm that the comment was created and has the correct threading.
$this->assertTrue($this->commentExists($comment5_6, TRUE), 'Comment #6. Reply found.');
$this->assertEqual($comment5_6->getThread(), '03.00/');
// Confirm that there is a link to the parent comment.
$this->assertParentLink($comment5_6->id(), $comment5->id());
// Reply to comment #5_6 creating comment #5_6_7.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $comment5_6->id());
$comment5_6_7 = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Confirm that the comment was created and has the correct threading.
$this->assertTrue($this->commentExists($comment5_6_7, TRUE), 'Comment #5_6_7. Second reply found.');
$this->assertEqual($comment5_6_7->getThread(), '03.00.00/');
// Confirm that there is a link to the parent comment.
$this->assertParentLink($comment5_6_7->id(), $comment5_6->id());
// Reply to comment #5 creating comment #5_8.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $comment5->id());
$comment5_8 = $this->postComment(NULL, $this->randomMachineName(), '', TRUE);
// Confirm that the comment was created and has the correct threading.
$this->assertTrue($this->commentExists($comment5_8), 'Comment #5_8. Third reply found.');
$this->assertEqual($comment5_8->getThread(), '03.01/');
// Confirm that there is a link to the parent comment.
$this->assertParentLink($comment5_8->id(), $comment5->id());
}
/**
* Asserts that the link to the specified parent comment is present.
*
* @param int $cid
* The comment ID to check.
* @param int $pid
* The expected parent comment ID.
*/
protected function assertParentLink($cid, $pid) {
// This pattern matches a markup structure like:
// <a id="comment-2"></a>
// <article>
// <p class="parent">
// <a href="...comment-1"></a>
// </p>
// </article>
$pattern = "//a[@id='comment-$cid']/following-sibling::article//p[contains(@class, 'parent')]//a[contains(@href, 'comment-$pid')]";
$this->assertFieldByXpath($pattern, NULL, format_string(
'Comment %cid has a link to parent %pid.',
[
'%cid' => $cid,
'%pid' => $pid,
]
));
}
/**
* Asserts that the specified comment does not have a link to a parent.
*
* @param int $cid
* The comment ID to check.
*/
protected function assertNoParentLink($cid) {
// This pattern matches a markup structure like:
// <a id="comment-2"></a>
// <article>
// <p class="parent"></p>
// </article>
$pattern = "//a[@id='comment-$cid']/following-sibling::article//p[contains(@class, 'parent')]";
$this->assertNoFieldByXpath($pattern, NULL, format_string(
'Comment %cid does not have a link to a parent.',
[
'%cid' => $cid,
]
));
}
}

View file

@ -0,0 +1,83 @@
<?php
namespace Drupal\Tests\comment\Functional;
/**
* Tests to ensure that appropriate and accessible markup is created for comment
* titles.
*
* @group comment
*/
class CommentTitleTest extends CommentTestBase {
/**
* Tests markup for comments with empty titles.
*/
public function testCommentEmptyTitles() {
// Installs module that sets comments to an empty string.
\Drupal::service('module_installer')->install(['comment_empty_title_test']);
// Set comments to have a subject with preview disabled.
$this->setCommentPreview(DRUPAL_DISABLED);
$this->setCommentForm(TRUE);
$this->setCommentSubject(TRUE);
// Create a node.
$this->drupalLogin($this->webUser);
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]);
// Post comment #1 and verify that h3's are not rendered.
$subject_text = $this->randomMachineName();
$comment_text = $this->randomMachineName();
$comment = $this->postComment($this->node, $comment_text, $subject_text, TRUE);
// The entity fields for name and mail have no meaning if the user is not
// Anonymous.
$this->assertNull($comment->name->value);
$this->assertNull($comment->mail->value);
// Confirm that the comment was created.
$regex = '/<a id="comment-' . $comment->id() . '"(.*?)';
$regex .= $comment->comment_body->value . '(.*?)';
$regex .= '/s';
$this->assertPattern($regex, 'Comment is created successfully');
// Tests that markup is not generated for the comment without header.
$this->assertNoPattern('|<h3[^>]*></h3>|', 'Comment title H3 element not found when title is an empty string.');
}
/**
* Tests markup for comments with populated titles.
*/
public function testCommentPopulatedTitles() {
// Set comments to have a subject with preview disabled.
$this->setCommentPreview(DRUPAL_DISABLED);
$this->setCommentForm(TRUE);
$this->setCommentSubject(TRUE);
// Create a node.
$this->drupalLogin($this->webUser);
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]);
// Post comment #1 and verify that title is rendered in h3.
$subject_text = $this->randomMachineName();
$comment_text = $this->randomMachineName();
$comment1 = $this->postComment($this->node, $comment_text, $subject_text, TRUE);
// The entity fields for name and mail have no meaning if the user is not
// Anonymous.
$this->assertNull($comment1->name->value);
$this->assertNull($comment1->mail->value);
// Confirm that the comment was created.
$this->assertTrue($this->commentExists($comment1), 'Comment #1. Comment found.');
// Tests that markup is created for comment with heading.
$this->assertPattern('|<h3[^>]*><a[^>]*>' . $subject_text . '</a></h3>|', 'Comment title is rendered in h3 when title populated.');
// Tests that the comment's title link is the permalink of the comment.
$comment_permalink = $this->cssSelect('.permalink');
$comment_permalink = $comment_permalink[0]->getAttribute('href');
// Tests that the comment's title link contains the url fragment.
$this->assertTrue(strpos($comment_permalink, '#comment-' . $comment1->id()), "The comment's title link contains the url fragment.");
$this->assertEqual($comment1->permalink()->toString(), $comment_permalink, "The comment's title has the correct link.");
}
}

View file

@ -0,0 +1,182 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\UrlHelper;
use Drupal\comment\Entity\Comment;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\user\Entity\User;
/**
* Generates text using placeholders for dummy content to check comment token
* replacement.
*
* @group comment
*/
class CommentTokenReplaceTest extends CommentTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['taxonomy'];
/**
* Creates a comment, then tests the tokens generated from it.
*/
public function testCommentTokenReplacement() {
$token_service = \Drupal::token();
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
$url_options = [
'absolute' => TRUE,
'language' => $language_interface,
];
// Setup vocabulary.
Vocabulary::create([
'vid' => 'tags',
'name' => 'Tags',
])->save();
// Change the title of the admin user.
$this->adminUser->name->value = 'This is a title with some special & > " stuff.';
$this->adminUser->save();
$this->drupalLogin($this->adminUser);
// Set comment variables.
$this->setCommentSubject(TRUE);
// Create a node and a comment.
$node = $this->drupalCreateNode(['type' => 'article', 'title' => '<script>alert("123")</script>']);
$parent_comment = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Post a reply to the comment.
$this->drupalGet('comment/reply/node/' . $node->id() . '/comment/' . $parent_comment->id());
$child_comment = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName());
$comment = Comment::load($child_comment->id());
$comment->setHomepage('http://example.org/');
// Add HTML to ensure that sanitation of some fields tested directly.
$comment->setSubject('<blink>Blinking Comment</blink>');
// Generate and test tokens.
$tests = [];
$tests['[comment:cid]'] = $comment->id();
$tests['[comment:hostname]'] = $comment->getHostname();
$tests['[comment:author]'] = Html::escape($comment->getAuthorName());
$tests['[comment:mail]'] = $this->adminUser->getEmail();
$tests['[comment:homepage]'] = UrlHelper::filterBadProtocol($comment->getHomepage());
$tests['[comment:title]'] = Html::escape($comment->getSubject());
$tests['[comment:body]'] = $comment->comment_body->processed;
$tests['[comment:langcode]'] = $comment->language()->getId();
$tests['[comment:url]'] = $comment->url('canonical', $url_options + ['fragment' => 'comment-' . $comment->id()]);
$tests['[comment:edit-url]'] = $comment->url('edit-form', $url_options);
$tests['[comment:created]'] = \Drupal::service('date.formatter')->format($comment->getCreatedTime(), 'medium', ['langcode' => $language_interface->getId()]);
$tests['[comment:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getCreatedTime(), ['langcode' => $language_interface->getId()]);
$tests['[comment:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getChangedTimeAcrossTranslations(), ['langcode' => $language_interface->getId()]);
$tests['[comment:parent:cid]'] = $comment->hasParentComment() ? $comment->getParentComment()->id() : NULL;
$tests['[comment:parent:title]'] = $parent_comment->getSubject();
$tests['[comment:entity]'] = Html::escape($node->getTitle());
// Test node specific tokens.
$tests['[comment:entity:nid]'] = $comment->getCommentedEntityId();
$tests['[comment:entity:title]'] = Html::escape($node->getTitle());
$tests['[comment:author:uid]'] = $comment->getOwnerId();
$tests['[comment:author:name]'] = Html::escape($this->adminUser->getDisplayName());
$base_bubbleable_metadata = BubbleableMetadata::createFromObject($comment);
$metadata_tests = [];
$metadata_tests['[comment:cid]'] = $base_bubbleable_metadata;
$metadata_tests['[comment:hostname]'] = $base_bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$bubbleable_metadata->addCacheableDependency($this->adminUser);
$metadata_tests['[comment:author]'] = $bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$bubbleable_metadata->addCacheableDependency($this->adminUser);
$metadata_tests['[comment:mail]'] = $bubbleable_metadata;
$metadata_tests['[comment:homepage]'] = $base_bubbleable_metadata;
$metadata_tests['[comment:title]'] = $base_bubbleable_metadata;
$metadata_tests['[comment:body]'] = $base_bubbleable_metadata;
$metadata_tests['[comment:langcode]'] = $base_bubbleable_metadata;
$metadata_tests['[comment:url]'] = $base_bubbleable_metadata;
$metadata_tests['[comment:edit-url]'] = $base_bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[comment:created]'] = $bubbleable_metadata->addCacheTags(['rendered']);
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[comment:created:since]'] = $bubbleable_metadata->setCacheMaxAge(0);
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[comment:changed:since]'] = $bubbleable_metadata->setCacheMaxAge(0);
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[comment:parent:cid]'] = $bubbleable_metadata->addCacheTags(['comment:1']);
$metadata_tests['[comment:parent:title]'] = $bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[comment:entity]'] = $bubbleable_metadata->addCacheTags(['node:2']);
// Test node specific tokens.
$metadata_tests['[comment:entity:nid]'] = $bubbleable_metadata;
$metadata_tests['[comment:entity:title]'] = $bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[comment:author:uid]'] = $bubbleable_metadata->addCacheTags(['user:2']);
$metadata_tests['[comment:author:name]'] = $bubbleable_metadata;
// 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) {
$bubbleable_metadata = new BubbleableMetadata();
$output = $token_service->replace($input, ['comment' => $comment], ['langcode' => $language_interface->getId()], $bubbleable_metadata);
$this->assertEqual($output, $expected, new FormattableMarkup('Comment token %token replaced.', ['%token' => $input]));
$this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
}
// Test anonymous comment author.
$author_name = 'This is a random & " > string';
$comment->setOwnerId(0)->setAuthorName($author_name);
$input = '[comment:author]';
$output = $token_service->replace($input, ['comment' => $comment], ['langcode' => $language_interface->getId()]);
$this->assertEqual($output, Html::escape($author_name), format_string('Comment author token %token replaced.', ['%token' => $input]));
// Add comment field to user and term entities.
$this->addDefaultCommentField('user', 'user', 'comment', CommentItemInterface::OPEN, 'comment_user');
$this->addDefaultCommentField('taxonomy_term', 'tags', 'comment', CommentItemInterface::OPEN, 'comment_term');
// Create a user and a comment.
$user = User::create(['name' => 'alice']);
$user->activate();
$user->save();
$this->postComment($user, 'user body', 'user subject', TRUE);
// Create a term and a comment.
$term = Term::create([
'vid' => 'tags',
'name' => 'term',
]);
$term->save();
$this->postComment($term, 'term body', 'term subject', TRUE);
// Load node, user and term again so comment_count gets computed.
$node = Node::load($node->id());
$user = User::load($user->id());
$term = Term::load($term->id());
// Generate comment tokens for node (it has 2 comments, both new),
// user and term.
$tests = [];
$tests['[entity:comment-count]'] = 2;
$tests['[entity:comment-count-new]'] = 2;
$tests['[node:comment-count]'] = 2;
$tests['[node:comment-count-new]'] = 2;
$tests['[user:comment-count]'] = 1;
$tests['[user:comment-count-new]'] = 1;
$tests['[term:comment-count]'] = 1;
$tests['[term:comment-count-new]'] = 1;
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, ['entity' => $node, 'node' => $node, 'user' => $user, 'term' => $term], ['langcode' => $language_interface->getId()]);
$this->assertEqual($output, $expected, format_string('Comment token %token replaced.', ['%token' => $input]));
}
}
}

View file

@ -0,0 +1,226 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Tests\content_translation\Functional\ContentTranslationUITestBase;
/**
* Tests the Comment Translation UI.
*
* @group comment
*/
class CommentTranslationUITest extends ContentTranslationUITestBase {
use CommentTestTrait;
/**
* The subject of the test comment.
*/
protected $subject;
/**
* An administrative user with permission to administer comments.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* {inheritdoc}
*/
protected $defaultCacheContexts = [
'languages:language_interface',
'session',
'theme',
'timezone',
'url.query_args:_wrapper_format',
'url.query_args.pagers:0',
'user.permissions',
'user.roles',
];
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['language', 'content_translation', 'node', 'comment'];
protected function setUp() {
$this->entityTypeId = 'comment';
$this->nodeBundle = 'article';
$this->bundle = 'comment_article';
$this->testLanguageSelector = FALSE;
$this->subject = $this->randomMachineName();
parent::setUp();
}
/**
* {@inheritdoc}
*/
public function setupBundle() {
parent::setupBundle();
$this->drupalCreateContentType(['type' => $this->nodeBundle, 'name' => $this->nodeBundle]);
// Add a comment field to the article content type.
$this->addDefaultCommentField('node', 'article', 'comment_article', CommentItemInterface::OPEN, 'comment_article');
// Create a page content type.
$this->drupalCreateContentType(['type' => 'page', 'name' => 'page']);
// Add a comment field to the page content type - this one won't be
// translatable.
$this->addDefaultCommentField('node', 'page', 'comment');
// Mark this bundle as translatable.
$this->container->get('content_translation.manager')->setEnabled('comment', 'comment_article', TRUE);
}
/**
* {@inheritdoc}
*/
protected function getTranslatorPermissions() {
return array_merge(parent::getTranslatorPermissions(), ['post comments', 'administer comments', 'access comments']);
}
/**
* {@inheritdoc}
*/
protected function createEntity($values, $langcode, $comment_type = 'comment_article') {
if ($comment_type == 'comment_article') {
// This is the article node type, with the 'comment_article' field.
$node_type = 'article';
$field_name = 'comment_article';
}
else {
// This is the page node type with the non-translatable 'comment' field.
$node_type = 'page';
$field_name = 'comment';
}
$node = $this->drupalCreateNode([
'type' => $node_type,
$field_name => [
['status' => CommentItemInterface::OPEN],
],
]);
$values['entity_id'] = $node->id();
$values['entity_type'] = 'node';
$values['field_name'] = $field_name;
$values['uid'] = $node->getOwnerId();
return parent::createEntity($values, $langcode, $comment_type);
}
/**
* {@inheritdoc}
*/
protected function getNewEntityValues($langcode) {
// Comment subject is not translatable hence we use a fixed value.
return [
'subject' => [['value' => $this->subject]],
'comment_body' => [['value' => $this->randomMachineName(16)]],
] + parent::getNewEntityValues($langcode);
}
/**
* {@inheritdoc}
*/
protected function doTestPublishedStatus() {
$entity_manager = \Drupal::entityManager();
$storage = $entity_manager->getStorage($this->entityTypeId);
$storage->resetCache();
$entity = $storage->load($this->entityId);
// Unpublish translations.
foreach ($this->langcodes as $index => $langcode) {
if ($index > 0) {
$edit = ['status' => 0];
$url = $entity->urlInfo('edit-form', ['language' => ConfigurableLanguage::load($langcode)]);
$this->drupalPostForm($url, $edit, $this->getFormSubmitAction($entity, $langcode));
$storage->resetCache();
$entity = $storage->load($this->entityId);
$this->assertFalse($this->manager->getTranslationMetadata($entity->getTranslation($langcode))->isPublished(), 'The translation has been correctly unpublished.');
}
}
}
/**
* {@inheritdoc}
*/
protected function doTestAuthoringInfo() {
$storage = $this->container->get('entity_type.manager')
->getStorage($this->entityTypeId);
$storage->resetCache([$this->entityId]);
$entity = $storage->load($this->entityId);
$languages = $this->container->get('language_manager')->getLanguages();
$values = [];
// Post different authoring information for each translation.
foreach ($this->langcodes as $langcode) {
$url = $entity->urlInfo('edit-form', ['language' => $languages[$langcode]]);
$user = $this->drupalCreateUser();
$values[$langcode] = [
'uid' => $user->id(),
'created' => REQUEST_TIME - mt_rand(0, 1000),
];
$edit = [
'uid' => $user->getUsername() . ' (' . $user->id() . ')',
'date[date]' => format_date($values[$langcode]['created'], 'custom', 'Y-m-d'),
'date[time]' => format_date($values[$langcode]['created'], 'custom', 'H:i:s'),
];
$this->drupalPostForm($url, $edit, $this->getFormSubmitAction($entity, $langcode));
}
$storage->resetCache([$this->entityId]);
$entity = $storage->load($this->entityId);
foreach ($this->langcodes as $langcode) {
$metadata = $this->manager->getTranslationMetadata($entity->getTranslation($langcode));
$this->assertEqual($metadata->getAuthor()->id(), $values[$langcode]['uid'], 'Translation author correctly stored.');
$this->assertEqual($metadata->getCreatedTime(), $values[$langcode]['created'], 'Translation date correctly stored.');
}
}
/**
* Tests translate link on comment content admin page.
*/
public function testTranslateLinkCommentAdminPage() {
$this->adminUser = $this->drupalCreateUser(array_merge(parent::getTranslatorPermissions(), ['access administration pages', 'administer comments', 'skip comment approval']));
$this->drupalLogin($this->adminUser);
$cid_translatable = $this->createEntity([], $this->langcodes[0]);
$cid_untranslatable = $this->createEntity([], $this->langcodes[0], 'comment');
// Verify translation links.
$this->drupalGet('admin/content/comment');
$this->assertResponse(200);
$this->assertLinkByHref('comment/' . $cid_translatable . '/translations');
$this->assertNoLinkByHref('comment/' . $cid_untranslatable . '/translations');
}
/**
* {@inheritdoc}
*/
protected function doTestTranslationEdit() {
$storage = $this->container->get('entity_type.manager')
->getStorage($this->entityTypeId);
$storage->resetCache([$this->entityId]);
$entity = $storage->load($this->entityId);
$languages = $this->container->get('language_manager')->getLanguages();
foreach ($this->langcodes as $langcode) {
// We only want to test the title for non-english translations.
if ($langcode != 'en') {
$options = ['language' => $languages[$langcode]];
$url = $entity->urlInfo('edit-form', $options);
$this->drupalGet($url);
$title = t('Edit @type @title [%language translation]', [
'@type' => $this->entityTypeId,
'@title' => $entity->getTranslation($langcode)->label(),
'%language' => $languages[$langcode]->getName(),
]);
$this->assertRaw($title);
}
}
}
}

View file

@ -0,0 +1,191 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Entity\CommentType;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\node\Entity\Node;
/**
* Ensures that comment type functions work correctly.
*
* @group comment
*/
class CommentTypeTest extends CommentTestBase {
/**
* Admin user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $adminUser;
/**
* Permissions to grant admin user.
*
* @var array
*/
protected $permissions = [
'administer comments',
'administer comment fields',
'administer comment types',
];
/**
* Sets the test up.
*/
protected function setUp() {
parent::setUp();
$this->drupalPlaceBlock('page_title_block');
$this->adminUser = $this->drupalCreateUser($this->permissions);
}
/**
* Tests creating a comment type programmatically and via a form.
*/
public function testCommentTypeCreation() {
// Create a comment type programmatically.
$type = $this->createCommentType('other');
$comment_type = CommentType::load('other');
$this->assertTrue($comment_type, 'The new comment type has been created.');
// Log in a test user.
$this->drupalLogin($this->adminUser);
$this->drupalGet('admin/structure/comment/manage/' . $type->id());
$this->assertResponse(200, 'The new comment type can be accessed at the edit form.');
// Create a comment type via the user interface.
$edit = [
'id' => 'foo',
'label' => 'title for foo',
'description' => '',
'target_entity_type_id' => 'node',
];
$this->drupalPostForm('admin/structure/comment/types/add', $edit, t('Save'));
$comment_type = CommentType::load('foo');
$this->assertTrue($comment_type, 'The new comment type has been created.');
// Check that the comment type was created in site default language.
$default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
$this->assertEqual($comment_type->language()->getId(), $default_langcode);
// Edit the comment-type and ensure that we cannot change the entity-type.
$this->drupalGet('admin/structure/comment/manage/foo');
$this->assertNoField('target_entity_type_id', 'Entity type file not present');
$this->assertText(t('Target entity type'));
// Save the form and ensure the entity-type value is preserved even though
// the field isn't present.
$this->drupalPostForm(NULL, [], t('Save'));
\Drupal::entityManager()->getStorage('comment_type')->resetCache(['foo']);
$comment_type = CommentType::load('foo');
$this->assertEqual($comment_type->getTargetEntityTypeId(), 'node');
}
/**
* Tests editing a comment type using the UI.
*/
public function testCommentTypeEditing() {
$this->drupalLogin($this->adminUser);
$field = FieldConfig::loadByName('comment', 'comment', 'comment_body');
$this->assertEqual($field->getLabel(), 'Comment', 'Comment body field was found.');
// Change the comment type name.
$this->drupalGet('admin/structure/comment');
$edit = [
'label' => 'Bar',
];
$this->drupalPostForm('admin/structure/comment/manage/comment', $edit, t('Save'));
$this->drupalGet('admin/structure/comment');
$this->assertRaw('Bar', 'New name was displayed.');
$this->clickLink('Manage fields');
$this->assertUrl(\Drupal::url('entity.comment.field_ui_fields', ['comment_type' => 'comment'], ['absolute' => TRUE]), [], 'Original machine name was used in URL.');
$this->assertTrue($this->cssSelect('tr#comment-body'), 'Body field exists.');
// Remove the body field.
$this->drupalPostForm('admin/structure/comment/manage/comment/fields/comment.comment.comment_body/delete', [], t('Delete'));
// Resave the settings for this type.
$this->drupalPostForm('admin/structure/comment/manage/comment', [], t('Save'));
// Check that the body field doesn't exist.
$this->drupalGet('admin/structure/comment/manage/comment/fields');
$this->assertFalse($this->cssSelect('tr#comment-body'), 'Body field does not exist.');
}
/**
* Tests deleting a comment type that still has content.
*/
public function testCommentTypeDeletion() {
// Create a comment type programmatically.
$type = $this->createCommentType('foo');
$this->drupalCreateContentType(['type' => 'page']);
$this->addDefaultCommentField('node', 'page', 'foo', CommentItemInterface::OPEN, 'foo');
$field_storage = FieldStorageConfig::loadByName('node', 'foo');
$this->drupalLogin($this->adminUser);
// Create a node.
$node = Node::create([
'type' => 'page',
'title' => 'foo',
]);
$node->save();
// Add a new comment of this type.
$comment = Comment::create([
'comment_type' => 'foo',
'entity_type' => 'node',
'field_name' => 'foo',
'entity_id' => $node->id(),
]);
$comment->save();
// Attempt to delete the comment type, which should not be allowed.
$this->drupalGet('admin/structure/comment/manage/' . $type->id() . '/delete');
$this->assertRaw(
t('%label is used by 1 comment on your site. You can not remove this comment type until you have removed all of the %label comments.', ['%label' => $type->label()]),
'The comment type will not be deleted until all comments of that type are removed.'
);
$this->assertRaw(
t('%label is used by the %field field on your site. You can not remove this comment type until you have removed the field.', [
'%label' => 'foo',
'%field' => 'node.foo',
]),
'The comment type will not be deleted until all fields of that type are removed.'
);
$this->assertNoText(t('This action cannot be undone.'), 'The comment type deletion confirmation form is not available.');
// Delete the comment and the field.
$comment->delete();
$field_storage->delete();
// Attempt to delete the comment type, which should now be allowed.
$this->drupalGet('admin/structure/comment/manage/' . $type->id() . '/delete');
$this->assertRaw(
t('Are you sure you want to delete the comment type %type?', ['%type' => $type->id()]),
'The comment type is available for deletion.'
);
$this->assertText(t('This action cannot be undone.'), 'The comment type deletion confirmation form is available.');
// Test exception thrown when re-using an existing comment type.
try {
$this->addDefaultCommentField('comment', 'comment', 'bar');
$this->fail('Exception not thrown.');
}
catch (\InvalidArgumentException $e) {
$this->pass('Exception thrown if attempting to re-use comment-type from another entity type.');
}
// Delete the comment type.
$this->drupalPostForm('admin/structure/comment/manage/' . $type->id() . '/delete', [], t('Delete'));
$this->assertNull(CommentType::load($type->id()), 'Comment type deleted.');
$this->assertRaw(t('The comment type %label has been deleted.', ['%label' => $type->label()]));
}
}

View file

@ -0,0 +1,83 @@
<?php
namespace Drupal\Tests\comment\Functional;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Core\Extension\ModuleUninstallValidatorException;
use Drupal\Tests\BrowserTestBase;
/**
* Tests comment module uninstallation.
*
* @group comment
*/
class CommentUninstallTest extends BrowserTestBase {
use CommentTestTrait;
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['comment', 'node'];
protected function setUp() {
parent::setup();
// Create an article content type.
$this->drupalCreateContentType(['type' => 'article', 'name' => t('Article')]);
// Create comment field on article so that adds 'comment_body' field.
$this->addDefaultCommentField('node', 'article');
}
/**
* Tests if comment module uninstallation fails if the field exists.
*
* @throws \Drupal\Core\Extension\ModuleUninstallValidatorException
*/
public function testCommentUninstallWithField() {
// Ensure that the field exists before uninstallation.
$field_storage = FieldStorageConfig::loadByName('comment', 'comment_body');
$this->assertNotNull($field_storage, 'The comment_body field exists.');
// Uninstall the comment module which should trigger an exception.
try {
$this->container->get('module_installer')->uninstall(['comment']);
$this->fail("Expected an exception when uninstall was attempted.");
}
catch (ModuleUninstallValidatorException $e) {
$this->pass("Caught an exception when uninstall was attempted.");
}
}
/**
* Tests if uninstallation succeeds if the field has been deleted beforehand.
*/
public function testCommentUninstallWithoutField() {
// Manually delete the comment_body field before module uninstallation.
$field_storage = FieldStorageConfig::loadByName('comment', 'comment_body');
$this->assertNotNull($field_storage, 'The comment_body field exists.');
$field_storage->delete();
// Check that the field is now deleted.
$field_storage = FieldStorageConfig::loadByName('comment', 'comment_body');
$this->assertNull($field_storage, 'The comment_body field has been deleted.');
// Manually delete the comment field on the node before module uninstallation.
$field_storage = FieldStorageConfig::loadByName('node', 'comment');
$this->assertNotNull($field_storage, 'The comment field exists.');
$field_storage->delete();
// Check that the field is now deleted.
$field_storage = FieldStorageConfig::loadByName('node', 'comment');
$this->assertNull($field_storage, 'The comment field has been deleted.');
field_purge_batch(10);
// Ensure that uninstallation succeeds even if the field has already been
// deleted manually beforehand.
$this->container->get('module_installer')->uninstall(['comment']);
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\comment\Functional\Hal;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
/**
* @group hal
*/
class CommentHalJsonAnonTest extends CommentHalJsonTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*
* Anonymous users cannot edit their own comments.
*
* @see \Drupal\comment\CommentAccessControlHandler::checkAccess
*
* Therefore we grant them the 'administer comments' permission for the
* purpose of this test. Then they are able to edit their own comments, but
* some fields are still not editable, even with that permission.
*
* @see ::setUpAuthorization
*/
protected static $patchProtectedFieldNames = [
'changed' => NULL,
'thread' => NULL,
'entity_type' => NULL,
'field_name' => NULL,
'entity_id' => NULL,
];
}

View file

@ -0,0 +1,24 @@
<?php
namespace Drupal\Tests\comment\Functional\Hal;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group hal
*/
class CommentHalJsonBasicAuthTest extends CommentHalJsonTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,19 @@
<?php
namespace Drupal\Tests\comment\Functional\Hal;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group hal
*/
class CommentHalJsonCookieTest extends CommentHalJsonTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -0,0 +1,130 @@
<?php
namespace Drupal\Tests\comment\Functional\Hal;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\Tests\comment\Functional\Rest\CommentResourceTestBase;
use Drupal\Tests\hal\Functional\EntityResource\HalEntityNormalizationTrait;
use Drupal\user\Entity\User;
abstract class CommentHalJsonTestBase extends CommentResourceTestBase {
use HalEntityNormalizationTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*
* The HAL+JSON format causes different PATCH-protected fields. For some
* reason, the 'pid' and 'homepage' fields are NOT PATCH-protected, even
* though they are for non-HAL+JSON serializations.
*
* @todo fix in https://www.drupal.org/node/2824271
*/
protected static $patchProtectedFieldNames = [
'status' => "The 'administer comments' permission is required.",
'created' => "The 'administer comments' permission is required.",
'changed' => NULL,
'thread' => NULL,
'entity_type' => NULL,
'field_name' => NULL,
'entity_id' => NULL,
'uid' => "The 'administer comments' permission is required.",
];
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedEntity() {
$default_normalization = parent::getExpectedNormalizedEntity();
$normalization = $this->applyHalFieldNormalization($default_normalization);
// Because \Drupal\comment\Entity\Comment::getOwner() generates an in-memory
// User entity without a UUID, we cannot use it.
$author = User::load($this->entity->getOwnerId());
$commented_entity = EntityTest::load(1);
return $normalization + [
'_links' => [
'self' => [
'href' => $this->baseUrl . '/comment/1?_format=hal_json',
],
'type' => [
'href' => $this->baseUrl . '/rest/type/comment/comment',
],
$this->baseUrl . '/rest/relation/comment/comment/entity_id' => [
[
'href' => $this->baseUrl . '/entity_test/1?_format=hal_json',
],
],
$this->baseUrl . '/rest/relation/comment/comment/uid' => [
[
'href' => $this->baseUrl . '/user/' . $author->id() . '?_format=hal_json',
'lang' => 'en',
],
],
],
'_embedded' => [
$this->baseUrl . '/rest/relation/comment/comment/entity_id' => [
[
'_links' => [
'self' => [
'href' => $this->baseUrl . '/entity_test/1?_format=hal_json',
],
'type' => [
'href' => $this->baseUrl . '/rest/type/entity_test/bar',
],
],
'uuid' => [
['value' => $commented_entity->uuid()],
],
],
],
$this->baseUrl . '/rest/relation/comment/comment/uid' => [
[
'_links' => [
'self' => [
'href' => $this->baseUrl . '/user/' . $author->id() . '?_format=hal_json',
],
'type' => [
'href' => $this->baseUrl . '/rest/type/user/user',
],
],
'uuid' => [
['value' => $author->uuid()],
],
'lang' => 'en',
],
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPostEntity() {
return parent::getNormalizedPostEntity() + [
'_links' => [
'type' => [
'href' => $this->baseUrl . '/rest/type/comment/comment',
],
],
];
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace Drupal\Tests\comment\Functional\Hal;
use Drupal\Tests\comment\Functional\Rest\CommentTypeResourceTestBase;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
/**
* @group hal
*/
class CommentTypeHalJsonAnonTest extends CommentTypeResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\comment\Functional\Hal;
use Drupal\Tests\comment\Functional\Rest\CommentTypeResourceTestBase;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group hal
*/
class CommentTypeHalJsonBasicAuthTest extends CommentTypeResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal', 'basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\comment\Functional\Hal;
use Drupal\Tests\comment\Functional\Rest\CommentTypeResourceTestBase;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group hal
*/
class CommentTypeHalJsonCookieTest extends CommentTypeResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -0,0 +1,45 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
/**
* @group rest
*/
class CommentJsonAnonTest extends CommentResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*
* Anonymous users cannot edit their own comments.
*
* @see \Drupal\comment\CommentAccessControlHandler::checkAccess
*
* Therefore we grant them the 'administer comments' permission for the
* purpose of this test.
*
* @see ::setUpAuthorization
*/
protected static $patchProtectedFieldNames = [
'pid' => NULL,
'entity_id' => NULL,
'changed' => NULL,
'thread' => NULL,
'entity_type' => NULL,
'field_name' => NULL,
];
}

View file

@ -0,0 +1,34 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group rest
*/
class CommentJsonBasicAuthTest extends CommentResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,29 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group rest
*/
class CommentJsonCookieTest extends CommentResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -0,0 +1,387 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Entity\CommentType;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\Core\Cache\Cache;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\Tests\rest\Functional\BcTimestampNormalizerUnixTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase;
use Drupal\user\Entity\User;
use GuzzleHttp\RequestOptions;
abstract class CommentResourceTestBase extends EntityResourceTestBase {
use CommentTestTrait, BcTimestampNormalizerUnixTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['comment', 'entity_test'];
/**
* {@inheritdoc}
*/
protected static $entityTypeId = 'comment';
/**
* {@inheritdoc}
*/
protected static $patchProtectedFieldNames = [
'status' => "The 'administer comments' permission is required.",
'pid' => NULL,
'entity_id' => NULL,
'uid' => "The 'administer comments' permission is required.",
'name' => "The 'administer comments' permission is required.",
'homepage' => "The 'administer comments' permission is required.",
'created' => "The 'administer comments' permission is required.",
'changed' => NULL,
'thread' => NULL,
'entity_type' => NULL,
'field_name' => NULL,
];
/**
* @var \Drupal\comment\CommentInterface
*/
protected $entity;
/**
* {@inheritdoc}
*/
protected function setUpAuthorization($method) {
switch ($method) {
case 'GET':
$this->grantPermissionsToTestedRole(['access comments', 'view test entity']);
break;
case 'POST':
$this->grantPermissionsToTestedRole(['post comments']);
break;
case 'PATCH':
// Anonymous users are not ever allowed to edit their own comments. To
// be able to test PATCHing comments as the anonymous user, the more
// permissive 'administer comments' permission must be granted.
// @see \Drupal\comment\CommentAccessControlHandler::checkAccess
if (static::$auth) {
$this->grantPermissionsToTestedRole(['edit own comments']);
}
else {
$this->grantPermissionsToTestedRole(['administer comments']);
}
break;
case 'DELETE':
$this->grantPermissionsToTestedRole(['administer comments']);
break;
}
}
/**
* {@inheritdoc}
*/
protected function createEntity() {
// Create a "bar" bundle for the "entity_test" entity type and create.
$bundle = 'bar';
entity_test_create_bundle($bundle, NULL, 'entity_test');
// Create a comment field on this bundle.
$this->addDefaultCommentField('entity_test', 'bar', 'comment');
// Create a "Camelids" test entity that the comment will be assigned to.
$commented_entity = EntityTest::create([
'name' => 'Camelids',
'type' => 'bar',
]);
$commented_entity->save();
// Create a "Llama" comment.
$comment = Comment::create([
'comment_body' => [
'value' => 'The name "llama" was adopted by European settlers from native Peruvians.',
'format' => 'plain_text',
],
'entity_id' => $commented_entity->id(),
'entity_type' => 'entity_test',
'field_name' => 'comment',
]);
$comment->setSubject('Llama')
->setOwnerId(static::$auth ? $this->account->id() : 0)
->setPublished()
->setCreatedTime(123456789)
->setChangedTime(123456789);
$comment->save();
return $comment;
}
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedEntity() {
$author = User::load($this->entity->getOwnerId());
return [
'cid' => [
['value' => 1],
],
'uuid' => [
['value' => $this->entity->uuid()],
],
'langcode' => [
[
'value' => 'en',
],
],
'comment_type' => [
[
'target_id' => 'comment',
'target_type' => 'comment_type',
'target_uuid' => CommentType::load('comment')->uuid(),
],
],
'subject' => [
[
'value' => 'Llama',
],
],
'status' => [
[
'value' => TRUE,
],
],
'created' => [
$this->formatExpectedTimestampItemValues(123456789),
],
'changed' => [
$this->formatExpectedTimestampItemValues($this->entity->getChangedTime()),
],
'default_langcode' => [
[
'value' => TRUE,
],
],
'uid' => [
[
'target_id' => (int) $author->id(),
'target_type' => 'user',
'target_uuid' => $author->uuid(),
'url' => base_path() . 'user/' . $author->id(),
],
],
'pid' => [],
'entity_type' => [
[
'value' => 'entity_test',
],
],
'entity_id' => [
[
'target_id' => 1,
'target_type' => 'entity_test',
'target_uuid' => EntityTest::load(1)->uuid(),
'url' => base_path() . 'entity_test/1',
],
],
'field_name' => [
[
'value' => 'comment',
],
],
'name' => [],
'homepage' => [],
'thread' => [
[
'value' => '01/',
],
],
'comment_body' => [
[
'value' => 'The name "llama" was adopted by European settlers from native Peruvians.',
'format' => 'plain_text',
'processed' => '<p>The name &quot;llama&quot; was adopted by European settlers from native Peruvians.</p>' . "\n",
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPostEntity() {
return [
'comment_type' => [
[
'target_id' => 'comment',
],
],
'entity_type' => [
[
'value' => 'entity_test',
],
],
'entity_id' => [
[
'target_id' => (int) EntityTest::load(1)->id(),
],
],
'field_name' => [
[
'value' => 'comment',
],
],
'subject' => [
[
'value' => 'Dramallama',
],
],
'comment_body' => [
[
'value' => 'Llamas are awesome.',
'format' => 'plain_text',
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPatchEntity() {
return array_diff_key($this->getNormalizedPostEntity(), ['entity_type' => TRUE, 'entity_id' => TRUE, 'field_name' => TRUE]);
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheTags() {
return Cache::mergeTags(parent::getExpectedCacheTags(), ['config:filter.format.plain_text']);
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheContexts() {
return Cache::mergeContexts(['languages:language_interface', 'theme'], parent::getExpectedCacheContexts());
}
/**
* Tests POSTing a comment without critical base fields.
*
* Tests with the most minimal normalization possible: the one returned by
* ::getNormalizedPostEntity().
*
* But Comment entities have some very special edge cases:
* - base fields that are not marked as required in
* \Drupal\comment\Entity\Comment::baseFieldDefinitions() yet in fact are
* required.
* - base fields that are marked as required, but yet can still result in
* validation errors other than "missing required field".
*/
public function testPostDxWithoutCriticalBaseFields() {
$this->initAuthentication();
$this->provisionEntityResource();
$this->setUpAuthorization('POST');
$url = $this->getEntityResourcePostUrl()->setOption('query', ['_format' => static::$format]);
$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = static::$mimeType;
$request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
$request_options = array_merge_recursive($request_options, $this->getAuthenticationRequestOptions('POST'));
// DX: 422 when missing 'entity_type' field.
$request_options[RequestOptions::BODY] = $this->serializer->encode(array_diff_key($this->getNormalizedPostEntity(), ['entity_type' => TRUE]), static::$format);
$response = $this->request('POST', $url, $request_options);
// @todo Uncomment, remove next 3 lines in https://www.drupal.org/node/2820364.
$this->assertSame(500, $response->getStatusCode());
$this->assertSame(['text/plain; charset=UTF-8'], $response->getHeader('Content-Type'));
$this->assertStringStartsWith('The website encountered an unexpected error. Please try again later.</br></br><em class="placeholder">Symfony\Component\HttpKernel\Exception\HttpException</em>: Internal Server Error in <em class="placeholder">Drupal\rest\Plugin\rest\resource\EntityResource-&gt;post()</em>', (string) $response->getBody());
// $this->assertResourceErrorResponse(422, "Unprocessable Entity: validation failed.\nentity_type: This value should not be null.\n", $response);
// DX: 422 when missing 'entity_id' field.
$request_options[RequestOptions::BODY] = $this->serializer->encode(array_diff_key($this->getNormalizedPostEntity(), ['entity_id' => TRUE]), static::$format);
// @todo Remove the try/catch in favor of the two commented lines in
// https://www.drupal.org/node/2820364.
try {
$response = $this->request('POST', $url, $request_options);
// This happens on DrupalCI.
// $this->assertSame(500, $response->getStatusCode());
}
catch (\Exception $e) {
// This happens on Wim's local machine.
// $this->assertSame("Error: Call to a member function get() on null\nDrupal\\comment\\Plugin\\Validation\\Constraint\\CommentNameConstraintValidator->getAnonymousContactDetailsSetting()() (Line: 96)\n", $e->getMessage());
}
// $response = $this->request('POST', $url, $request_options);
// $this->assertResourceErrorResponse(422, "Unprocessable Entity: validation failed.\nentity_type: This value should not be null.\n", $response);
// DX: 422 when missing 'entity_type' field.
$request_options[RequestOptions::BODY] = $this->serializer->encode(array_diff_key($this->getNormalizedPostEntity(), ['field_name' => TRUE]), static::$format);
$response = $this->request('POST', $url, $request_options);
// @todo Uncomment, remove next 2 lines in https://www.drupal.org/node/2820364.
$this->assertSame(500, $response->getStatusCode());
$this->assertSame(['text/plain; charset=UTF-8'], $response->getHeader('Content-Type'));
// $this->assertResourceErrorResponse(422, "Unprocessable Entity: validation failed.\nfield_name: This value should not be null.\n", $response);
}
/**
* {@inheritdoc}
*/
protected function getExpectedUnauthorizedAccessMessage($method) {
if ($this->config('rest.settings')->get('bc_entity_resource_permissions')) {
return parent::getExpectedUnauthorizedAccessMessage($method);
}
switch ($method) {
case 'GET';
return "The 'access comments' permission is required and the comment must be published.";
case 'POST';
return "The 'post comments' permission is required.";
case 'PATCH';
return "The 'edit own comments' permission is required, the user must be the comment author, and the comment must be published.";
default:
return parent::getExpectedUnauthorizedAccessMessage($method);
}
}
/**
* Tests POSTing a comment with and without 'skip comment approval'
*/
public function testPostSkipCommentApproval() {
$this->initAuthentication();
$this->provisionEntityResource();
$this->setUpAuthorization('POST');
// Create request.
$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = static::$mimeType;
$request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
$request_options = array_merge_recursive($request_options, $this->getAuthenticationRequestOptions('POST'));
$request_options[RequestOptions::BODY] = $this->serializer->encode($this->getNormalizedPostEntity(), static::$format);
$url = $this->getEntityResourcePostUrl()->setOption('query', ['_format' => static::$format]);
// Status should be FALSE when posting as anonymous.
$response = $this->request('POST', $url, $request_options);
$unserialized = $this->serializer->deserialize((string) $response->getBody(), get_class($this->entity), static::$format);
$this->assertResourceResponse(201, FALSE, $response);
$this->assertFalse($unserialized->getStatus());
// Grant anonymous permission to skip comment approval.
$this->grantPermissionsToTestedRole(['skip comment approval']);
// Status should be TRUE when posting as anonymous and skip comment approval.
$response = $this->request('POST', $url, $request_options);
$unserialized = $this->serializer->deserialize((string) $response->getBody(), get_class($this->entity), static::$format);
$this->assertResourceResponse(201, FALSE, $response);
$this->assertTrue($unserialized->getStatus());
}
/**
* {@inheritdoc}
*/
protected function getExpectedUnauthorizedAccessCacheability() {
// @see \Drupal\comment\CommentAccessControlHandler::checkAccess()
return parent::getExpectedUnauthorizedAccessCacheability()
->addCacheTags(['comment:1']);
}
}

View file

@ -0,0 +1,24 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
/**
* @group rest
*/
class CommentTypeJsonAnonTest extends CommentTypeResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
}

View file

@ -0,0 +1,34 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group rest
*/
class CommentTypeJsonBasicAuthTest extends CommentTypeResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,29 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group rest
*/
class CommentTypeJsonCookieTest extends CommentTypeResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -0,0 +1,77 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\comment\Entity\CommentType;
use Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase;
/**
* ResourceTestBase for CommentType entity.
*/
abstract class CommentTypeResourceTestBase extends EntityResourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['node', 'comment'];
/**
* {@inheritdoc}
*/
protected static $entityTypeId = 'comment_type';
/**
* The CommentType entity.
*
* @var \Drupal\comment\CommentTypeInterface
*/
protected $entity;
/**
* {@inheritdoc}
*/
protected function setUpAuthorization($method) {
$this->grantPermissionsToTestedRole(['administer comment types']);
}
/**
* {@inheritdoc}
*/
protected function createEntity() {
// Create a "Camelids" comment type.
$camelids = CommentType::create([
'id' => 'camelids',
'label' => 'Camelids',
'description' => 'Camelids are large, strictly herbivorous animals with slender necks and long legs.',
'target_entity_type_id' => 'node',
]);
$camelids->save();
return $camelids;
}
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedEntity() {
return [
'dependencies' => [],
'description' => 'Camelids are large, strictly herbivorous animals with slender necks and long legs.',
'id' => 'camelids',
'label' => 'Camelids',
'langcode' => 'en',
'status' => TRUE,
'target_entity_type_id' => 'node',
'uuid' => $this->entity->uuid(),
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPostEntity() {
// @todo Update in https://www.drupal.org/node/2300677.
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class CommentTypeXmlAnonTest extends CommentTypeResourceTestBase {
use AnonResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
}

View file

@ -0,0 +1,36 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class CommentTypeXmlBasicAuthTest extends CommentTypeResourceTestBase {
use BasicAuthResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,31 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class CommentTypeXmlCookieTest extends CommentTypeResourceTestBase {
use CookieResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -0,0 +1,63 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class CommentXmlAnonTest extends CommentResourceTestBase {
use AnonResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*
* Anonymous users cannot edit their own comments.
*
* @see \Drupal\comment\CommentAccessControlHandler::checkAccess
*
* Therefore we grant them the 'administer comments' permission for the
* purpose of this test.
*
* @see ::setUpAuthorization
*/
protected static $patchProtectedFieldNames = [
'pid',
'entity_id',
'changed',
'thread',
'entity_type',
'field_name',
];
/**
* {@inheritdoc}
*/
public function testPostDxWithoutCriticalBaseFields() {
// Deserialization of the XML format is not supported.
$this->markTestSkipped();
}
/**
* {@inheritdoc}
*/
public function testPostSkipCommentApproval() {
// Deserialization of the XML format is not supported.
$this->markTestSkipped();
}
}

View file

@ -0,0 +1,52 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class CommentXmlBasicAuthTest extends CommentResourceTestBase {
use BasicAuthResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
/**
* {@inheritdoc}
*/
public function testPostDxWithoutCriticalBaseFields() {
// Deserialization of the XML format is not supported.
$this->markTestSkipped();
}
/**
* {@inheritdoc}
*/
public function testPostSkipCommentApproval() {
// Deserialization of the XML format is not supported.
$this->markTestSkipped();
}
}

View file

@ -0,0 +1,47 @@
<?php
namespace Drupal\Tests\comment\Functional\Rest;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class CommentXmlCookieTest extends CommentResourceTestBase {
use CookieResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
/**
* {@inheritdoc}
*/
public function testPostDxWithoutCriticalBaseFields() {
// Deserialization of the XML format is not supported.
$this->markTestSkipped();
}
/**
* {@inheritdoc}
*/
public function testPostSkipCommentApproval() {
// Deserialization of the XML format is not supported.
$this->markTestSkipped();
}
}

View file

@ -0,0 +1,52 @@
<?php
namespace Drupal\Tests\comment\Functional\Update;
use Drupal\FunctionalTests\Update\UpdatePathTestBase;
/**
* Tests that comment admin view is enabled after update.
*
* @see comment_post_update_enable_comment_admin_view()
*
* @group Update
* @group legacy
*/
class CommentAdminViewUpdateTest extends UpdatePathTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['comment', 'views'];
/**
* {@inheritdoc}
*/
public function setDatabaseDumpFiles() {
$this->databaseDumpFiles = [
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
];
}
/**
* Tests that comment admin view is enabled after update.
*/
public function testCommentAdminPostUpdateHook() {
$this->runUpdates();
// Ensure we can load the view from the storage after the update and it's
// enabled.
$entity_type_manager = \Drupal::entityTypeManager();
/** @var \Drupal\views\ViewEntityInterface $comment_admin_view */
$comment_admin_view = $entity_type_manager->getStorage('view')->load('comment');
$this->assertNotNull($comment_admin_view, 'Comment admin view exist in storage.');
$this->assertTrue($comment_admin_view->enable(), 'Comment admin view is enabled.');
$comment_delete_action = $entity_type_manager->getStorage('action')->load('comment_delete_action');
$this->assertNotNull($comment_delete_action, 'Comment delete action imported');
// Verify comment admin page is working after updates.
$account = $this->drupalCreateUser(['administer comments']);
$this->drupalLogin($account);
$this->drupalGet('admin/content/comment');
$this->assertText(t('No comments available.'));
}
}

View file

@ -0,0 +1,46 @@
<?php
namespace Drupal\Tests\comment\Functional\Update;
use Drupal\comment\Entity\Comment;
use Drupal\FunctionalTests\Update\UpdatePathTestBase;
/**
* Tests that comment hostname settings are properly updated.
*
* @group comment
* @group legacy
*/
class CommentHostnameUpdateTest extends UpdatePathTestBase {
/**
* {@inheritdoc}
*/
protected function setDatabaseDumpFiles() {
$this->databaseDumpFiles = [
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8-rc1.bare.standard.php.gz',
];
}
/**
* Tests comment_update_8600().
*
* @see comment_update_8600
*/
public function testCommentUpdate8600() {
/** @var \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface $manager */
$manager = $this->container->get('entity.definition_update_manager');
/** @var \Drupal\Core\Field\BaseFieldDefinition $definition */
$definition = $manager->getFieldStorageDefinition('hostname', 'comment');
// Check that 'hostname' base field doesn't have a default value callback.
$this->assertNull($definition->getDefaultValueCallback());
$this->runUpdates();
$definition = $manager->getFieldStorageDefinition('hostname', 'comment');
// Check that 'hostname' base field default value callback was set.
$this->assertEquals(Comment::class . '::getDefaultHostname', $definition->getDefaultValueCallback());
}
}

View file

@ -0,0 +1,75 @@
<?php
namespace Drupal\Tests\comment\Functional\Update;
use Drupal\FunctionalTests\Update\UpdatePathTestBase;
/**
* Tests that comment settings are properly updated during database updates.
*
* @group comment
* @group legacy
*/
class CommentUpdateTest extends UpdatePathTestBase {
/**
* {@inheritdoc}
*/
protected function setDatabaseDumpFiles() {
$this->databaseDumpFiles = [
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8-rc1.filled.standard.php.gz',
];
}
/**
* Tests comment_update_8200().
*
* @see comment_update_8200()
*/
public function testCommentUpdate8101() {
// Load the 'node.article.default' entity view display config, and check
// that component 'comment' does not contain the 'view_mode' setting.
$config = $this->config('core.entity_view_display.node.article.default');
$this->assertNull($config->get('content.comment.settings.view_mode'));
// Load the 'node.forum.default' entity view display config, and check that
// component 'comment_forum' does not contain the 'view_mode' setting.
$config = $this->config('core.entity_view_display.node.forum.default');
$this->assertNull($config->get('content.comment_forum.settings.view_mode'));
// Run updates.
$this->runUpdates();
// Check that 'node.article.default' entity view display setting 'view_mode'
// has the value 'default'.
$config = $this->config('core.entity_view_display.node.article.default');
$this->assertIdentical($config->get('content.comment.settings.view_mode'), 'default');
// Check that 'node.forum.default' entity view display setting 'view_mode'
// has the value 'default'.
$config = $this->config('core.entity_view_display.node.forum.default');
$this->assertIdentical($config->get('content.comment_forum.settings.view_mode'), 'default');
}
/**
* Tests that the comment entity type has a 'published' entity key.
*
* @see comment_update_8301()
*/
public function testPublishedEntityKey() {
// Check that the 'published' entity key does not exist prior to the update.
$entity_type = \Drupal::entityDefinitionUpdateManager()->getEntityType('comment');
$this->assertFalse($entity_type->getKey('published'));
// Run updates.
$this->runUpdates();
// Check that the entity key exists and it has the correct value.
$entity_type = \Drupal::entityDefinitionUpdateManager()->getEntityType('comment');
$this->assertEqual('status', $entity_type->getKey('published'));
// Check that the {comment_field_data} table status index has been created.
$this->assertTrue(\Drupal::database()->schema()->indexExists('comment_field_data', 'comment__status_comment_type'));
}
}

View file

@ -0,0 +1,51 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
use Drupal\comment\Entity\Comment;
use Drupal\user\Entity\User;
use Drupal\views\Views;
/**
* Tests the user posted or commented argument handler.
*
* @group comment
*/
class ArgumentUserUIDTest extends CommentTestBase {
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_comment_user_uid'];
public function testCommentUserUIDTest() {
// Add an additional comment which is not created by the user.
$new_user = User::create(['name' => 'new user']);
$new_user->save();
$comment = Comment::create([
'uid' => $new_user->uid->value,
'entity_id' => $this->nodeUserCommented->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'subject' => 'if a woodchuck could chuck wood.',
]);
$comment->save();
$view = Views::getView('test_comment_user_uid');
$this->executeView($view, [$this->account->id()]);
$result_set = [
[
'nid' => $this->nodeUserPosted->id(),
],
[
'nid' => $this->nodeUserCommented->id(),
],
];
$column_map = ['nid' => 'nid'];
$this->assertIdenticalResultset($view, $result_set, $column_map);
}
}

View file

@ -0,0 +1,222 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
use Drupal\block_content\Entity\BlockContent;
use Drupal\block_content\Entity\BlockContentType;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Tests\comment\Functional\CommentTestBase as CommentBrowserTestBase;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Unicode;
use Drupal\user\RoleInterface;
use Drupal\views\Views;
/**
* Tests comment approval functionality.
*
* @group comment
*/
class CommentAdminTest extends CommentBrowserTestBase {
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
\Drupal::service('module_installer')->install(['views']);
$view = Views::getView('comment');
$view->storage->enable()->save();
\Drupal::service('router.builder')->rebuildIfNeeded();
}
/**
* Test comment approval functionality through admin/content/comment.
*/
public function testApprovalAdminInterface() {
// Set anonymous comments to require approval.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => TRUE,
'skip comment approval' => FALSE,
]);
$this->drupalPlaceBlock('page_title_block');
$this->drupalLogin($this->adminUser);
// Ensure that doesn't require contact info.
$this->setCommentAnonymous('0');
// Test that the comments page loads correctly when there are no comments.
$this->drupalGet('admin/content/comment');
$this->assertText(t('No comments available.'));
// Assert the expose filters on the admin page.
$this->assertField('subject');
$this->assertField('author_name');
$this->assertField('langcode');
$this->drupalLogout();
// Post anonymous comment without contact info.
$body = $this->getRandomGenerator()->sentences(4);
$subject = Unicode::truncate(trim(Html::decodeEntities(strip_tags($body))), 29, TRUE, TRUE);
$author_name = $this->randomMachineName();
$this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', [
'name' => $author_name,
'comment_body[0][value]' => $body,
], t('Save'));
$this->assertText(t('Your comment has been queued for review by site administrators and will be published after approval.'), 'Comment requires approval.');
// Get unapproved comment id.
$this->drupalLogin($this->adminUser);
$anonymous_comment4 = $this->getUnapprovedComment($subject);
$anonymous_comment4 = Comment::create([
'cid' => $anonymous_comment4,
'subject' => $subject,
'comment_body' => $body,
'entity_id' => $this->node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
]);
$this->drupalLogout();
$this->assertFalse($this->commentExists($anonymous_comment4), 'Anonymous comment was not published.');
// Approve comment.
$this->drupalLogin($this->adminUser);
$edit = [];
$edit['action'] = 'comment_publish_action';
$edit['comment_bulk_form[0]'] = $anonymous_comment4->id();
$this->drupalPostForm('admin/content/comment/approval', $edit, t('Apply to selected items'));
$this->assertText('Publish comment was applied to 1 item.', new FormattableMarkup('Operation "@operation" was performed on comment.', ['@operation' => 'publish']));
$this->drupalLogout();
$this->drupalGet('node/' . $this->node->id());
$this->assertTrue($this->commentExists($anonymous_comment4), 'Anonymous comment visible.');
// Post 2 anonymous comments without contact info.
$comments[] = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Publish multiple comments in one operation.
$this->drupalLogin($this->adminUser);
$this->drupalGet('admin/content/comment/approval');
$this->assertText(t('Unapproved comments (@count)', ['@count' => 2]), 'Two unapproved comments waiting for approval.');
// Assert the expose filters on the admin page.
$this->assertField('subject');
$this->assertField('author_name');
$this->assertField('langcode');
$edit = [
"action" => 'comment_publish_action',
"comment_bulk_form[1]" => $comments[0]->id(),
"comment_bulk_form[0]" => $comments[1]->id(),
];
$this->drupalPostForm(NULL, $edit, t('Apply to selected items'));
$this->assertText(t('Unapproved comments (@count)', ['@count' => 0]), 'All comments were approved.');
// Test message when no comments selected.
$this->drupalPostForm('admin/content/comment', [], t('Apply to selected items'));
$this->assertText(t('Select one or more comments to perform the update on.'));
$subject_link = $this->xpath('//table/tbody/tr/td/a[contains(@href, :href) and contains(@title, :title) and text()=:text]', [
':href' => $comments[0]->permalink()->toString(),
':title' => Unicode::truncate($comments[0]->get('comment_body')->value, 128),
':text' => $comments[0]->getSubject(),
]);
$this->assertTrue(!empty($subject_link), 'Comment listing shows the correct subject link.');
$this->assertText($author_name . ' (not verified)', 'Anonymous author name is displayed correctly.');
$subject_link = $this->xpath('//table/tbody/tr/td/a[contains(@href, :href) and contains(@title, :title) and text()=:text]', [
':href' => $anonymous_comment4->permalink()->toString(),
':title' => Unicode::truncate($body, 128),
':text' => $subject,
]);
$this->assertTrue(!empty($subject_link), 'Comment listing shows the correct subject link.');
$this->assertText($author_name . ' (not verified)', 'Anonymous author name is displayed correctly.');
// Delete multiple comments in one operation.
$edit = [
'action' => 'comment_delete_action',
"comment_bulk_form[1]" => $comments[0]->id(),
"comment_bulk_form[0]" => $comments[1]->id(),
"comment_bulk_form[2]" => $anonymous_comment4->id(),
];
$this->drupalPostForm(NULL, $edit, t('Apply to selected items'));
$this->assertText(t('Are you sure you want to delete these comments and all their children?'), 'Confirmation required.');
$this->drupalPostForm(NULL, [], t('Delete'));
$this->assertText(t('No comments available.'), 'All comments were deleted.');
// Make sure the label of unpublished node is not visible on listing page.
$this->drupalGet('admin/content/comment');
$this->postComment($this->node, $this->randomMachineName());
$this->drupalLogout();
$this->drupalLogin($this->adminUser);
$this->drupalGet('admin/content/comment');
$this->assertText(Html::escape($this->node->label()), 'Comment admin can see the title of a published node');
$this->node->setUnpublished()->save();
$this->assertFalse($this->node->isPublished(), 'Node is unpublished now.');
$this->drupalGet('admin/content/comment');
$this->assertNoText(Html::escape($this->node->label()), 'Comment admin cannot see the title of an unpublished node');
$this->drupalLogout();
$node_access_user = $this->drupalCreateUser([
'administer comments',
'bypass node access',
]);
$this->drupalLogin($node_access_user);
$this->drupalGet('admin/content/comment');
$this->assertText(Html::escape($this->node->label()), 'Comment admin with bypass node access permissions can still see the title of a published node');
}
/**
* Tests commented entity label of admin view.
*/
public function testCommentedEntityLabel() {
\Drupal::service('module_installer')->install(['block_content']);
\Drupal::service('router.builder')->rebuildIfNeeded();
$bundle = BlockContentType::create([
'id' => 'basic',
'label' => 'basic',
'revision' => FALSE,
]);
$bundle->save();
$block_content = BlockContent::create([
'type' => 'basic',
'label' => 'Some block title',
'info' => 'Test block',
]);
$block_content->save();
// Create comment field on block_content.
$this->addDefaultCommentField('block_content', 'basic', 'block_comment', CommentItemInterface::OPEN, 'block_comment');
$this->drupalLogin($this->webUser);
// Post a comment to node.
$node_comment = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
// Post a comment to block content.
$block_content_comment = $this->postComment($block_content, $this->randomMachineName(), $this->randomMachineName(), TRUE, 'block_comment');
$this->drupalLogout();
// Login as admin to test the admin comment page.
$this->drupalLogin($this->adminUser);
$this->drupalGet('admin/content/comment');
$comment_author_link = $this->xpath('//table/tbody/tr[1]/td/a[contains(@href, :href) and text()=:text]', [
':href' => $this->webUser->toUrl()->toString(),
':text' => $this->webUser->label(),
]);
$this->assertTrue(!empty($comment_author_link), 'Comment listing links to comment author.');
$comment_author_link = $this->xpath('//table/tbody/tr[2]/td/a[contains(@href, :href) and text()=:text]', [
':href' => $this->webUser->toUrl()->toString(),
':text' => $this->webUser->label(),
]);
$this->assertTrue(!empty($comment_author_link), 'Comment listing links to comment author.');
// Admin page contains label of both entities.
$this->assertText(Html::escape($this->node->label()), 'Node title is visible.');
$this->assertText(Html::escape($block_content->label()), 'Block content label is visible.');
// Admin page contains subject of both entities.
$this->assertText(Html::escape($node_comment->label()), 'Node comment is visible.');
$this->assertText(Html::escape($block_content_comment->label()), 'Block content comment is visible.');
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
use Drupal\Tests\comment\Functional\CommentTestBase as CommentBrowserTestBase;
/**
* Tests comment edit functionality.
*
* @group comment
*/
class CommentEditTest extends CommentBrowserTestBase {
/**
* {@inheritdoc}
*/
protected $profile = 'standard';
/**
* Tests comment label in admin view.
*/
public function testCommentEdit() {
$this->drupalLogin($this->adminUser);
// Post a comment to node.
$node_comment = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$this->drupalGet('admin/content/comment');
$this->assertText($this->adminUser->label());
$this->drupalGet($node_comment->toUrl('edit-form'));
$edit = [
'comment_body[0][value]' => $this->randomMachineName(),
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->drupalGet('admin/content/comment');
$this->assertText($this->adminUser->label());
}
}

View file

@ -0,0 +1,120 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\comment\Entity\Comment;
/**
* Tests comment field filters with translations.
*
* @group comment
*/
class CommentFieldFilterTest extends CommentTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['language'];
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_field_filters'];
/**
* List of comment titles by language.
*
* @var array
*/
public $commentTitles = [];
protected function setUp($import_test_views = TRUE) {
parent::setUp($import_test_views);
$this->drupalLogin($this->drupalCreateUser(['access comments']));
// Add two new languages.
ConfigurableLanguage::createFromLangcode('fr')->save();
ConfigurableLanguage::createFromLangcode('es')->save();
// Set up comment titles.
$this->commentTitles = [
'en' => 'Food in Paris',
'es' => 'Comida en Paris',
'fr' => 'Nouriture en Paris',
];
// Create a new comment. Using the one created earlier will not work,
// as it predates the language set-up.
$comment = [
'uid' => $this->loggedInUser->id(),
'entity_id' => $this->nodeUserCommented->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'cid' => '',
'pid' => '',
'node_type' => '',
];
$this->comment = Comment::create($comment);
// Add field values and translate the comment.
$this->comment->subject->value = $this->commentTitles['en'];
$this->comment->comment_body->value = $this->commentTitles['en'];
$this->comment->langcode = 'en';
$this->comment->save();
foreach (['es', 'fr'] as $langcode) {
$translation = $this->comment->addTranslation($langcode, []);
$translation->comment_body->value = $this->commentTitles[$langcode];
$translation->subject->value = $this->commentTitles[$langcode];
}
$this->comment->save();
}
/**
* Tests body and title filters.
*/
public function testFilters() {
// Test the title filter page, which filters for title contains 'Comida'.
// Should show just the Spanish translation, once.
$this->assertPageCounts('test-title-filter', ['es' => 1, 'fr' => 0, 'en' => 0], 'Comida title filter');
// Test the body filter page, which filters for body contains 'Comida'.
// Should show just the Spanish translation, once.
$this->assertPageCounts('test-body-filter', ['es' => 1, 'fr' => 0, 'en' => 0], 'Comida body filter');
// Test the title Paris filter page, which filters for title contains
// 'Paris'. Should show each translation once.
$this->assertPageCounts('test-title-paris', ['es' => 1, 'fr' => 1, 'en' => 1], 'Paris title filter');
// Test the body Paris filter page, which filters for body contains
// 'Paris'. Should show each translation once.
$this->assertPageCounts('test-body-paris', ['es' => 1, 'fr' => 1, 'en' => 1], 'Paris body filter');
}
/**
* Asserts that the given comment translation counts are correct.
*
* @param string $path
* Path of the page to test.
* @param array $counts
* Array whose keys are languages, and values are the number of times
* that translation should be shown on the given page.
* @param string $message
* Message suffix to display.
*/
protected function assertPageCounts($path, $counts, $message) {
// Get the text of the page.
$this->drupalGet($path);
$text = $this->getTextContent();
// Check the counts. Note that the title and body are both shown on the
// page, and they are the same. So the title/body string should appear on
// the page twice as many times as the input count.
foreach ($counts as $langcode => $count) {
$this->assertEqual(substr_count($text, $this->commentTitles[$langcode]), 2 * $count, 'Translation ' . $langcode . ' has count ' . $count . ' with ' . $message);
}
}
}

View file

@ -0,0 +1,92 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
use Drupal\comment\Entity\Comment;
use Drupal\Core\Render\RenderContext;
use Drupal\Core\Session\AnonymousUserSession;
use Drupal\user\RoleInterface;
use Drupal\views\Views;
/**
* Tests the comment field name field.
*
* @group comment
*/
class CommentFieldNameTest extends CommentTestBase {
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_comment_field_name'];
/**
* The second comment entity used by this test.
*
* @var \Drupal\comment\CommentInterface
*/
protected $customComment;
/**
* The comment field name used by this test.
*
* @var string
*/
protected $fieldName = 'comment_custom';
/**
* {@inheritdoc}
*/
protected function setUp($import_test_views = TRUE) {
parent::setUp($import_test_views);
$this->addDefaultCommentField('node', 'page', $this->fieldName);
$this->customComment = Comment::create([
'entity_id' => $this->nodeUserCommented->id(),
'entity_type' => 'node',
'field_name' => $this->fieldName,
]);
$this->customComment->save();
}
/**
* Test comment field name.
*/
public function testCommentFieldName() {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = \Drupal::service('renderer');
// Grant permission to properly check view access on render.
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']);
$this->container->get('account_switcher')->switchTo(new AnonymousUserSession());
$view = Views::getView('test_comment_field_name');
$this->executeView($view);
$expected_result = [
[
'cid' => $this->comment->id(),
'field_name' => $this->comment->getFieldName(),
],
[
'cid' => $this->customComment->id(),
'field_name' => $this->customComment->getFieldName(),
],
];
$column_map = [
'cid' => 'cid',
'comment_field_data_field_name' => 'field_name',
];
$this->assertIdenticalResultset($view, $expected_result, $column_map);
// Test that data rendered.
$output = $renderer->executeInRenderContext(new RenderContext(), function () use ($view) {
return $view->field['field_name']->advancedRender($view->result[0]);
});
$this->assertEqual($this->comment->getFieldName(), $output);
$output = $renderer->executeInRenderContext(new RenderContext(), function () use ($view) {
return $view->field['field_name']->advancedRender($view->result[1]);
});
$this->assertEqual($this->customComment->getFieldName(), $output);
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
/**
* Tests comment operations.
*
* @group comment
*/
class CommentOperationsTest extends CommentTestBase {
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_comment_operations'];
/**
* Test the operations field plugin.
*/
public function testCommentOperations() {
$admin_account = $this->drupalCreateUser(['administer comments']);
$this->drupalLogin($admin_account);
$this->drupalGet('test-comment-operations');
$this->assertResponse(200);
$operation = $this->cssSelect('.views-field-operations li.edit a');
$this->assertEqual(count($operation), 1, 'Found edit operation for comment.');
$operation = $this->cssSelect('.views-field-operations li.delete a');
$this->assertEqual(count($operation), 1, 'Found delete operation for comment.');
}
}

View file

@ -0,0 +1,66 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
use Drupal\Component\Serialization\Json;
use Drupal\comment\Entity\Comment;
/**
* Tests a comment rest export view.
*
* @group comment
*/
class CommentRestExportTest extends CommentTestBase {
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_comment_rest'];
/**
* {@inheritdoc}
*/
public static $modules = ['node', 'comment', 'comment_test_views', 'rest', 'hal'];
protected function setUp($import_test_views = TRUE) {
parent::setUp($import_test_views);
// Add another anonymous comment.
$comment = [
'uid' => 0,
'entity_id' => $this->nodeUserCommented->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'subject' => 'A lot, apparently',
'cid' => '',
'pid' => $this->comment->id(),
'mail' => 'someone@example.com',
'name' => 'bobby tables',
'hostname' => 'public.example.com',
];
$this->comment = Comment::create($comment);
$this->comment->save();
$user = $this->drupalCreateUser(['access comments']);
$this->drupalLogin($user);
}
/**
* Test comment row.
*/
public function testCommentRestExport() {
$this->drupalGet(sprintf('node/%d/comments', $this->nodeUserCommented->id()), ['query' => ['_format' => 'hal_json']]);
$this->assertResponse(200);
$contents = Json::decode($this->getSession()->getPage()->getContent());
$this->assertEqual($contents[0]['subject'], 'How much wood would a woodchuck chuck');
$this->assertEqual($contents[1]['subject'], 'A lot, apparently');
$this->assertEqual(count($contents), 2);
// Ensure field-level access is respected - user shouldn't be able to see
// mail or hostname fields.
$this->assertNoText('someone@example.com');
$this->assertNoText('public.example.com');
}
}

View file

@ -0,0 +1,29 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
/**
* Tests the comment row plugin.
*
* @group comment
*/
class CommentRowTest extends CommentTestBase {
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_comment_row'];
/**
* Test comment row.
*/
public function testCommentRow() {
$this->drupalGet('test-comment-row');
$result = $this->xpath('//article[contains(@class, "comment")]');
$this->assertEqual(1, count($result), 'One rendered comment found.');
}
}

View file

@ -0,0 +1,90 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\Tests\views\Functional\ViewTestBase;
use Drupal\views\Tests\ViewTestData;
use Drupal\comment\Entity\Comment;
/**
* Provides setup and helper methods for comment views tests.
*/
abstract class CommentTestBase extends ViewTestBase {
use CommentTestTrait;
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['node', 'comment', 'comment_test_views'];
/**
* A normal user with permission to post comments (without approval).
*
* @var \Drupal\user\UserInterface
*/
protected $account;
/**
* A second normal user that will author a node for $account to comment on.
*
* @var \Drupal\user\UserInterface
*/
protected $account2;
/**
* Stores a node posted by the user created as $account.
*
* @var \Drupal\node\NodeInterface
*/
protected $nodeUserPosted;
/**
* Stores a node posted by the user created as $account2.
*
* @var \Drupal\node\NodeInterface
*/
protected $nodeUserCommented;
/**
* Stores a comment used by the tests.
*
* @var \Drupal\comment\Entity\Comment
*/
protected $comment;
protected function setUp($import_test_views = TRUE) {
parent::setUp($import_test_views);
ViewTestData::createTestViews(get_class($this), ['comment_test_views']);
// Add two users, create a node with the user1 as author and another node
// with user2 as author. For the second node add a comment from user1.
$this->account = $this->drupalCreateUser(['skip comment approval']);
$this->account2 = $this->drupalCreateUser();
$this->drupalLogin($this->account);
$this->drupalCreateContentType(['type' => 'page', 'name' => t('Basic page')]);
$this->addDefaultCommentField('node', 'page');
$this->nodeUserPosted = $this->drupalCreateNode();
$this->nodeUserCommented = $this->drupalCreateNode(['uid' => $this->account2->id()]);
$comment = [
'uid' => $this->loggedInUser->id(),
'entity_id' => $this->nodeUserCommented->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'subject' => 'How much wood would a woodchuck chuck',
'cid' => '',
'pid' => '',
'mail' => 'someone@example.com',
];
$this->comment = Comment::create($comment);
$this->comment->save();
}
}

View file

@ -0,0 +1,140 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
use Drupal\comment\CommentInterface;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\views\Views;
use Drupal\Tests\views\Functional\ViewTestBase;
/**
* Tests results for the Recent Comments view shipped with the module.
*
* @group comment
*/
class DefaultViewRecentCommentsTest extends ViewTestBase {
use CommentTestTrait;
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['node', 'comment', 'block'];
/**
* Number of results for the Master display.
*
* @var int
*/
protected $masterDisplayResults = 5;
/**
* Number of results for the Block display.
*
* @var int
*/
protected $blockDisplayResults = 5;
/**
* Number of results for the Page display.
*
* @var int
*/
protected $pageDisplayResults = 5;
/**
* Will hold the comments created for testing.
*
* @var array
*/
protected $commentsCreated = [];
/**
* Contains the node object used for comments of this test.
*
* @var \Drupal\node\Node
*/
public $node;
protected function setUp($import_test_views = TRUE) {
parent::setUp($import_test_views);
// Create a new content type
$content_type = $this->drupalCreateContentType();
// Add a node of the new content type.
$node_data = [
'type' => $content_type->id(),
];
$this->addDefaultCommentField('node', $content_type->id());
$this->node = $this->drupalCreateNode($node_data);
// Force a flush of the in-memory storage.
$this->container->get('views.views_data')->clear();
// Create some comments and attach them to the created node.
for ($i = 0; $i < $this->masterDisplayResults; $i++) {
/** @var \Drupal\comment\CommentInterface $comment */
$comment = Comment::create([
'status' => CommentInterface::PUBLISHED,
'field_name' => 'comment',
'entity_type' => 'node',
'entity_id' => $this->node->id(),
]);
$comment->setOwnerId(0);
$comment->setSubject('Test comment ' . $i);
$comment->comment_body->value = 'Test body ' . $i;
$comment->comment_body->format = 'full_html';
// Ensure comments are sorted in ascending order.
$time = REQUEST_TIME + ($this->masterDisplayResults - $i);
$comment->setCreatedTime($time);
$comment->changed->value = $time;
$comment->save();
}
// Store all the nodes just created to access their properties on the tests.
$this->commentsCreated = Comment::loadMultiple();
// Sort created comments in descending order.
ksort($this->commentsCreated, SORT_NUMERIC);
}
/**
* Tests the block defined by the comments_recent view.
*/
public function testBlockDisplay() {
$user = $this->drupalCreateUser(['access comments']);
$this->drupalLogin($user);
$view = Views::getView('comments_recent');
$view->setDisplay('block_1');
$this->executeView($view);
$map = [
'subject' => 'subject',
'cid' => 'cid',
'comment_field_data_created' => 'created',
];
$expected_result = [];
foreach (array_values($this->commentsCreated) as $key => $comment) {
$expected_result[$key]['subject'] = $comment->getSubject();
$expected_result[$key]['cid'] = $comment->id();
$expected_result[$key]['created'] = $comment->getCreatedTime();
}
$this->assertIdenticalResultset($view, $expected_result, $map);
// Check the number of results given by the display is the expected.
$this->assertEqual(count($view->result), $this->blockDisplayResults,
format_string('There are exactly @results comments. Expected @expected',
['@results' => count($view->result), '@expected' => $this->blockDisplayResults]
)
);
}
}

View file

@ -0,0 +1,63 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
use Drupal\comment\Entity\Comment;
use Drupal\user\Entity\User;
use Drupal\views\Views;
/**
* Tests the user posted or commented filter handler.
*
* The actual stuff is done in the parent class.
*
* @group comment
*/
class FilterUserUIDTest extends CommentTestBase {
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_comment_user_uid'];
public function testCommentUserUIDTest() {
$view = Views::getView('test_comment_user_uid');
$view->setDisplay();
$view->removeHandler('default', 'argument', 'uid_touch');
// Add an additional comment which is not created by the user.
$new_user = User::create(['name' => 'new user']);
$new_user->save();
$comment = Comment::create([
'uid' => $new_user->uid->value,
'entity_id' => $this->nodeUserCommented->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'subject' => 'if a woodchuck could chuck wood.',
]);
$comment->save();
$options = [
'id' => 'uid_touch',
'table' => 'node_field_data',
'field' => 'uid_touch',
'value' => [$this->loggedInUser->id()],
];
$view->addHandler('default', 'filter', 'node_field_data', 'uid_touch', $options);
$this->executeView($view, [$this->account->id()]);
$result_set = [
[
'nid' => $this->nodeUserPosted->id(),
],
[
'nid' => $this->nodeUserCommented->id(),
],
];
$column_map = ['nid' => 'nid'];
$this->assertIdenticalResultset($view, $result_set, $column_map);
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
/**
* Tests comments on nodes.
*
* @group comment
*/
class NodeCommentsTest extends CommentTestBase {
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['history'];
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_new_comments'];
/**
* Test the new comments field plugin.
*/
public function testNewComments() {
$this->drupalGet('test-new-comments');
$this->assertResponse(200);
$new_comments = $this->cssSelect(".views-field-new-comments a:contains('1')");
$this->assertEqual(count($new_comments), 1, 'Found the number of new comments for a certain node.');
}
}

View file

@ -0,0 +1,34 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
/**
* Tests the comment rss row plugin.
*
* @group comment
* @see \Drupal\comment\Plugin\views\row\Rss
*/
class RowRssTest extends CommentTestBase {
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_comment_rss'];
/**
* Test comment rss output.
*/
public function testRssRow() {
$this->drupalGet('test-comment-rss');
// Because the response is XML we can't use the page which depends on an
// HTML tag being present.
$result = $this->getSession()->getDriver()->find('//item');
$this->assertEqual(count($result), 1, 'Just one comment was found in the rss output.');
$this->assertEqual($result[0]->find('xpath', '//pubDate')->getHtml(), gmdate('r', $this->comment->getCreatedTime()), 'The right pubDate appears in the rss output.');
}
}

View file

@ -0,0 +1,96 @@
<?php
namespace Drupal\Tests\comment\Functional\Views;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\views\Views;
use Drupal\Tests\views\Functional\Wizard\WizardTestBase;
/**
* Tests the comment module integration into the wizard.
*
* @group comment
* @see \Drupal\comment\Plugin\views\wizard\Comment
*/
class WizardTest extends WizardTestBase {
use CommentTestTrait;
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['node', 'comment'];
/**
* {@inheritdoc}
*/
protected function setUp($import_test_views = TRUE) {
parent::setUp($import_test_views);
$this->drupalCreateContentType(['type' => 'page', 'name' => t('Basic page')]);
// Add comment field to page node type.
$this->addDefaultCommentField('node', 'page');
}
/**
* Tests adding a view of comments.
*/
public function testCommentWizard() {
$view = [];
$view['label'] = $this->randomMachineName(16);
$view['id'] = strtolower($this->randomMachineName(16));
$view['show[wizard_key]'] = 'comment';
$view['page[create]'] = TRUE;
$view['page[path]'] = $this->randomMachineName(16);
// Just triggering the saving should automatically choose a proper row
// plugin.
$this->drupalPostForm('admin/structure/views/add', $view, t('Save and edit'));
$this->assertUrl('admin/structure/views/view/' . $view['id'], [], 'Make sure the view saving was successful and the browser got redirected to the edit page.');
// If we update the type first we should get a selection of comment valid
// row plugins as the select field.
$this->drupalGet('admin/structure/views/add');
$this->drupalPostForm('admin/structure/views/add', $view, t('Update "of type" choice'));
// Check for available options of the row plugin.
$xpath = $this->constructFieldXpath('name', 'page[style][row_plugin]');
$fields = $this->xpath($xpath);
$options = [];
foreach ($fields as $field) {
$items = $this->getAllOptions($field);
foreach ($items as $item) {
$options[] = $item->getValue();
}
}
$expected_options = ['entity:comment', 'fields'];
$this->assertEqual($options, $expected_options);
$view['id'] = strtolower($this->randomMachineName(16));
$this->drupalPostForm(NULL, $view, t('Save and edit'));
$this->assertUrl('admin/structure/views/view/' . $view['id'], [], 'Make sure the view saving was successful and the browser got redirected to the edit page.');
$user = $this->drupalCreateUser(['access comments']);
$this->drupalLogin($user);
$view = Views::getView($view['id']);
$view->initHandlers();
$row = $view->display_handler->getOption('row');
$this->assertEqual($row['type'], 'entity:comment');
// Check for the default filters.
$this->assertEqual($view->filter['status']->table, 'comment_field_data');
$this->assertEqual($view->filter['status']->field, 'status');
$this->assertTrue($view->filter['status']->value);
$this->assertEqual($view->filter['status_node']->table, 'node_field_data');
$this->assertEqual($view->filter['status_node']->field, 'status');
$this->assertTrue($view->filter['status_node']->value);
// Check for the default fields.
$this->assertEqual($view->field['subject']->table, 'comment_field_data');
$this->assertEqual($view->field['subject']->field, 'subject');
}
}

View file

@ -0,0 +1,83 @@
<?php
namespace Drupal\Tests\comment\Kernel;
use Drupal\comment\Entity\CommentType;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests that comment bundles behave as expected.
*
* @group comment
*/
class CommentBundlesTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['comment', 'node', 'taxonomy', 'user'];
/**
* Entity type ids to use for target_entity_type_id on comment bundles.
*
* @var array
*/
protected $targetEntityTypes;
/**
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->entityFieldManager = $this->container->get('entity_field.manager');
$this->installEntitySchema('comment');
// Create multiple comment bundles,
// each of which has a different target entity type.
$this->targetEntityTypes = [
'comment' => 'Comment',
'node' => 'Node',
'taxonomy_term' => 'Taxonomy Term',
];
foreach ($this->targetEntityTypes as $id => $label) {
CommentType::create([
'id' => 'comment_on_' . $id,
'label' => 'Comment on ' . $label,
'target_entity_type_id' => $id,
])->save();
}
}
/**
* Test that the entity_id field is set correctly for each comment bundle.
*/
public function testEntityIdField() {
$field_definitions = [];
foreach (array_keys($this->targetEntityTypes) as $id) {
$bundle = 'comment_on_' . $id;
$field_definitions[$bundle] = $this->entityFieldManager
->getFieldDefinitions('comment', $bundle);
}
// Test that the value of the entity_id field for each bundle is correct.
foreach ($field_definitions as $bundle => $definition) {
$entity_type_id = str_replace('comment_on_', '', $bundle);
$target_type = $definition['entity_id']->getSetting('target_type');
$this->assertEquals($entity_type_id, $target_type);
// Verify that the target type remains correct
// in the deeply-nested object properties.
$nested_target_type = $definition['entity_id']->getItemDefinition()->getFieldDefinition()->getSetting('target_type');
$this->assertEquals($entity_type_id, $nested_target_type);
}
}
}

View file

@ -5,7 +5,7 @@ namespace Drupal\Tests\comment\Kernel;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Entity\CommentType;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Session\AnonymousUserSession;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
@ -202,7 +202,7 @@ class CommentFieldAccessTest extends EntityKernelTestBase {
// Generate permutations.
$combinations = [
'comment' => [$comment1, $comment2, $comment3, $comment4],
'user' => [$comment_admin_user, $comment_enabled_user, $comment_no_edit_user, $comment_disabled_user, $anonymous_user]
'user' => [$comment_admin_user, $comment_enabled_user, $comment_no_edit_user, $comment_disabled_user, $anonymous_user],
];
$permutations = $this->generatePermutations($combinations);
@ -211,12 +211,12 @@ class CommentFieldAccessTest extends EntityKernelTestBase {
foreach ($permutations as $set) {
$may_view = $set['comment']->{$field}->access('view', $set['user']);
$may_update = $set['comment']->{$field}->access('edit', $set['user']);
$this->assertTrue($may_view, SafeMarkup::format('User @user can view field @field on comment @comment', [
$this->assertTrue($may_view, new FormattableMarkup('User @user can view field @field on comment @comment', [
'@user' => $set['user']->getUsername(),
'@comment' => $set['comment']->getSubject(),
'@field' => $field,
]));
$this->assertEqual($may_update, $set['user']->hasPermission('administer comments'), SafeMarkup::format('User @user @state update field @field on comment @comment', [
$this->assertEqual($may_update, $set['user']->hasPermission('administer comments'), new FormattableMarkup('User @user @state update field @field on comment @comment', [
'@user' => $set['user']->getUsername(),
'@state' => $may_update ? 'can' : 'cannot',
'@comment' => $set['comment']->getSubject(),
@ -228,7 +228,7 @@ class CommentFieldAccessTest extends EntityKernelTestBase {
// Check access to normal field.
foreach ($permutations as $set) {
$may_update = $set['comment']->access('update', $set['user']) && $set['comment']->subject->access('edit', $set['user']);
$this->assertEqual($may_update, $set['user']->hasPermission('administer comments') || ($set['user']->hasPermission('edit own comments') && $set['user']->id() == $set['comment']->getOwnerId()), SafeMarkup::format('User @user @state update field subject on comment @comment', [
$this->assertEqual($may_update, $set['user']->hasPermission('administer comments') || ($set['user']->hasPermission('edit own comments') && $set['user']->id() == $set['comment']->getOwnerId()), new FormattableMarkup('User @user @state update field subject on comment @comment', [
'@user' => $set['user']->getUsername(),
'@state' => $may_update ? 'can' : 'cannot',
'@comment' => $set['comment']->getSubject(),
@ -250,13 +250,13 @@ class CommentFieldAccessTest extends EntityKernelTestBase {
$view_access = TRUE;
$state = 'can';
}
$this->assertEqual($may_view, $view_access, SafeMarkup::format('User @user @state view field @field on comment @comment', [
$this->assertEqual($may_view, $view_access, new FormattableMarkup('User @user @state view field @field on comment @comment', [
'@user' => $set['user']->getUsername(),
'@comment' => $set['comment']->getSubject(),
'@field' => $field,
'@state' => $state,
]));
$this->assertFalse($may_update, SafeMarkup::format('User @user @state update field @field on comment @comment', [
$this->assertFalse($may_update, new FormattableMarkup('User @user @state update field @field on comment @comment', [
'@user' => $set['user']->getUsername(),
'@state' => $may_update ? 'can' : 'cannot',
'@comment' => $set['comment']->getSubject(),
@ -271,12 +271,12 @@ class CommentFieldAccessTest extends EntityKernelTestBase {
foreach ($permutations as $set) {
$may_view = $set['comment']->{$field}->access('view', $set['user']);
$may_update = $set['comment']->{$field}->access('edit', $set['user']);
$this->assertEqual($may_view, TRUE, SafeMarkup::format('User @user can view field @field on comment @comment', [
$this->assertEqual($may_view, TRUE, new FormattableMarkup('User @user can view field @field on comment @comment', [
'@user' => $set['user']->getUsername(),
'@comment' => $set['comment']->getSubject(),
'@field' => $field,
]));
$this->assertEqual($may_update, $set['user']->hasPermission('post comments') && $set['comment']->isNew(), SafeMarkup::format('User @user @state update field @field on comment @comment', [
$this->assertEqual($may_update, $set['user']->hasPermission('post comments') && $set['comment']->isNew(), new FormattableMarkup('User @user @state update field @field on comment @comment', [
'@user' => $set['user']->getUsername(),
'@state' => $may_update ? 'can' : 'cannot',
'@comment' => $set['comment']->getSubject(),
@ -298,7 +298,7 @@ class CommentFieldAccessTest extends EntityKernelTestBase {
$set['comment']->isNew() &&
$set['user']->hasPermission('post comments') &&
$set['comment']->getFieldName() == 'comment_other'
), SafeMarkup::format('User @user @state update field @field on comment @comment', [
), new FormattableMarkup('User @user @state update field @field on comment @comment', [
'@user' => $set['user']->getUsername(),
'@state' => $may_update ? 'can' : 'cannot',
'@comment' => $set['comment']->getSubject(),

View file

@ -0,0 +1,46 @@
<?php
namespace Drupal\Tests\comment\Kernel;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Entity\CommentType;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Component\HttpFoundation\Request;
/**
* Tests the hostname base field.
*
* @coversDefaultClass \Drupal\comment\Entity\Comment
*
* @group comment
*/
class CommentHostnameTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['comment', 'entity_test', 'user'];
/**
* Tests hostname default value callback.
*
* @covers ::getDefaultHostname
*/
public function testGetDefaultHostname() {
// Create a fake request to be used for testing.
$request = Request::create('/', 'GET', [], [], [], ['REMOTE_ADDR' => '203.0.113.1']);
/** @var \Symfony\Component\HttpFoundation\RequestStack $stack */
$stack = $this->container->get('request_stack');
$stack->push($request);
CommentType::create([
'id' => 'foo',
'target_entity_type_id' => 'entity_test',
])->save();
$comment = Comment::create(['comment_type' => 'foo']);
// Check that the hostname was set correctly.
$this->assertEquals('203.0.113.1', $comment->getHostname());
}
}

View file

@ -3,7 +3,6 @@
namespace Drupal\Tests\comment\Kernel;
use Drupal\comment\Entity\CommentType;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Database\Database;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\Entity\Entity\EntityViewMode;
@ -47,7 +46,7 @@ class CommentIntegrationTest extends KernelTestBase {
* @see CommentDefaultFormatter::calculateDependencies()
*/
public function testViewMode() {
$mode = Unicode::strtolower($this->randomMachineName());
$mode = mb_strtolower($this->randomMachineName());
// Create a new comment view mode and a view display entity.
EntityViewMode::create([
'id' => "comment.$mode",
@ -64,7 +63,7 @@ class CommentIntegrationTest extends KernelTestBase {
FieldStorageConfig::create([
'entity_type' => 'entity_test',
'type' => 'comment',
'field_name' => $field_name = Unicode::strtolower($this->randomMachineName()),
'field_name' => $field_name = mb_strtolower($this->randomMachineName()),
'settings' => [
'comment_type' => 'comment',
],

View file

@ -2,6 +2,7 @@
namespace Drupal\Tests\comment\Kernel;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\Core\Field\FieldItemListInterface;
@ -64,4 +65,57 @@ class CommentItemTest extends FieldKernelTestBase {
$this->assertEqual('status', $mainProperty);
}
/**
* Tests comment author name.
*/
public function testCommentAuthorName() {
$this->installEntitySchema('comment');
$host = EntityTest::create(['name' => $this->randomString()]);
$host->save();
// Create some comments.
$comment = Comment::create([
'subject' => 'My comment title',
'uid' => 1,
'name' => 'entity-test',
'mail' => 'entity@localhost',
'entity_type' => 'entity_test',
'entity_id' => $host->id(),
'comment_type' => 'entity_test',
'status' => 1,
]);
$comment->save();
// The entity fields for name and mail have no meaning if the user is not
// Anonymous.
$this->assertNull($comment->name->value);
$this->assertNull($comment->mail->value);
$comment_anonymous = Comment::create([
'subject' => 'Anonymous comment title',
'uid' => 0,
'name' => 'barry',
'mail' => 'test@example.com',
'homepage' => 'https://example.com',
'entity_type' => 'entity_test',
'entity_id' => $host->id(),
'comment_type' => 'entity_test',
'status' => 1,
]);
$comment_anonymous->save();
// The entity fields for name and mail have retained their values when
// comment belongs to an anonymous user.
$this->assertNotNull($comment_anonymous->name->value);
$this->assertNotNull($comment_anonymous->mail->value);
$comment_anonymous->setOwnerId(1)
->save();
// The entity fields for name and mail have no meaning if the user is not
// Anonymous.
$this->assertNull($comment_anonymous->name->value);
$this->assertNull($comment_anonymous->mail->value);
}
}

View file

@ -51,7 +51,7 @@ class CommentValidationTest extends EntityKernelTestBase {
'type' => 'comment',
'settings' => [
'comment_type' => 'comment',
]
],
])->save();
// Create a page node type.

View file

@ -3,7 +3,6 @@
namespace Drupal\Tests\comment\Kernel\Migrate;
use Drupal\comment\Entity\CommentType;
use Drupal\migrate\MigrateException;
use Drupal\Tests\migrate_drupal\Kernel\MigrateDrupalTestBase;
use Drupal\migrate_drupal\Tests\StubTestTrait;
use Drupal\node\Entity\NodeType;
@ -29,6 +28,8 @@ class MigrateCommentStubTest extends MigrateDrupalTestBase {
parent::setUp();
$this->installEntitySchema('comment');
$this->installEntitySchema('node');
$this->installSchema('system', ['sequences']);
// Make sure uid 0 is created (default uid for comments is 0).
$storage = \Drupal::entityManager()->getStorage('user');
// Insert a row for the anonymous user.
@ -55,18 +56,6 @@ class MigrateCommentStubTest extends MigrateDrupalTestBase {
* Tests creation of comment stubs.
*/
public function testStub() {
try {
// We expect an exception, because there's no node to reference.
$this->performStubTest('comment');
$this->fail('Expected exception has not been thrown.');
}
catch (MigrateException $e) {
$this->assertIdentical($e->getMessage(),
'Stubbing failed, unable to generate value for field entity_id');
}
// The stub should pass when there's a node to point to.
$this->createStub('node');
$this->performStubTest('comment');
}

View file

@ -0,0 +1,71 @@
<?php
namespace Drupal\Tests\comment\Kernel\Migrate\d6;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* Tests the migration of comment entity displays from Drupal 6.
*
* @group comment
* @group migrate_drupal_6
*/
class MigrateCommentEntityDisplayTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['comment', 'menu_ui'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(['comment']);
$this->migrateContentTypes();
$this->executeMigrations([
'd6_node_type',
'd6_comment_type',
'd6_comment_field',
'd6_comment_field_instance',
'd6_comment_entity_display',
]);
}
/**
* Asserts various aspects of a comment component in an entity view display.
*
* @param string $id
* The entity ID.
* @param string $component_id
* The ID of the display component.
*/
protected function assertDisplay($id, $component_id) {
$component = EntityViewDisplay::load($id)->getComponent($component_id);
$this->assertInternalType('array', $component);
$this->assertSame('hidden', $component['label']);
$this->assertSame('comment_default', $component['type']);
$this->assertSame(20, $component['weight']);
}
/**
* Tests the migrated display configuration.
*/
public function testMigration() {
$this->assertDisplay('node.article.default', 'comment_node_article');
$this->assertDisplay('node.company.default', 'comment_node_company');
$this->assertDisplay('node.employee.default', 'comment_node_employee');
$this->assertDisplay('node.event.default', 'comment_node_event');
$this->assertDisplay('node.forum.default', 'comment_forum');
$this->assertDisplay('node.page.default', 'comment_node_page');
$this->assertDisplay('node.sponsor.default', 'comment_node_sponsor');
$this->assertDisplay('node.story.default', 'comment_node_story');
$this->assertDisplay('node.test_event.default', 'comment_node_test_event');
$this->assertDisplay('node.test_page.default', 'comment_node_test_page');
$this->assertDisplay('node.test_planet.default', 'comment_node_test_planet');
$this->assertDisplay('node.test_story.default', 'comment_node_test_story');
}
}

View file

@ -0,0 +1,73 @@
<?php
namespace Drupal\Tests\comment\Kernel\Migrate\d6;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* Tests the migration of comment form's subject display from Drupal 6.
*
* @group comment
* @group migrate_drupal_6
*/
class MigrateCommentEntityFormDisplaySubjectTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['comment'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(['comment']);
$this->executeMigrations([
'd6_comment_type',
'd6_comment_entity_form_display_subject',
]);
}
/**
* Asserts that the comment subject field is visible for a node type.
*
* @param string $id
* The entity form display ID.
*/
protected function assertSubjectVisible($id) {
$component = EntityFormDisplay::load($id)->getComponent('subject');
$this->assertInternalType('array', $component);
$this->assertSame('string_textfield', $component['type']);
$this->assertSame(10, $component['weight']);
}
/**
* Asserts that the comment subject field is not visible for a node type.
*
* @param string $id
* The entity form display ID.
*/
protected function assertSubjectNotVisible($id) {
$component = EntityFormDisplay::load($id)->getComponent('subject');
$this->assertNull($component);
}
/**
* Tests the migrated display configuration.
*/
public function testMigration() {
$this->assertSubjectVisible('comment.comment_node_article.default');
$this->assertSubjectVisible('comment.comment_node_company.default');
$this->assertSubjectVisible('comment.comment_node_employee.default');
$this->assertSubjectVisible('comment.comment_node_page.default');
$this->assertSubjectVisible('comment.comment_node_sponsor.default');
$this->assertSubjectNotVisible('comment.comment_node_story.default');
$this->assertSubjectVisible('comment.comment_node_test_event.default');
$this->assertSubjectVisible('comment.comment_node_test_page.default');
$this->assertSubjectVisible('comment.comment_node_test_planet.default');
$this->assertSubjectVisible('comment.comment_node_test_story.default');
}
}

View file

@ -0,0 +1,69 @@
<?php
namespace Drupal\Tests\comment\Kernel\Migrate\d6;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* Tests the migration of comment form display from Drupal 6.
*
* @group comment
* @group migrate_drupal_6
*/
class MigrateCommentEntityFormDisplayTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['comment', 'menu_ui'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(['comment']);
$this->migrateContentTypes();
$this->executeMigrations([
'd6_comment_type',
'd6_comment_field',
'd6_comment_field_instance',
'd6_comment_entity_form_display',
]);
}
/**
* Asserts various aspects of a comment component in an entity form display.
*
* @param string $id
* The entity ID.
* @param string $component_id
* The ID of the form component.
*/
protected function assertDisplay($id, $component_id) {
$component = EntityFormDisplay::load($id)->getComponent($component_id);
$this->assertInternalType('array', $component);
$this->assertSame('comment_default', $component['type']);
$this->assertSame(20, $component['weight']);
}
/**
* Tests the migrated display configuration.
*/
public function testMigration() {
$this->assertDisplay('node.article.default', 'comment_node_article');
$this->assertDisplay('node.company.default', 'comment_node_company');
$this->assertDisplay('node.employee.default', 'comment_node_employee');
$this->assertDisplay('node.event.default', 'comment_node_event');
$this->assertDisplay('node.forum.default', 'comment_forum');
$this->assertDisplay('node.page.default', 'comment_node_page');
$this->assertDisplay('node.sponsor.default', 'comment_node_sponsor');
$this->assertDisplay('node.story.default', 'comment_node_story');
$this->assertDisplay('node.test_event.default', 'comment_node_test_event');
$this->assertDisplay('node.test_page.default', 'comment_node_test_page');
$this->assertDisplay('node.test_planet.default', 'comment_node_test_planet');
$this->assertDisplay('node.test_story.default', 'comment_node_test_story');
}
}

View file

@ -0,0 +1,89 @@
<?php
namespace Drupal\Tests\comment\Kernel\Migrate\d6;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* Tests the migration of comment field instances from Drupal 6.
*
* @group comment
* @group migrate_drupal_6
*/
class MigrateCommentFieldInstanceTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['comment', 'menu_ui'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(['comment']);
$this->migrateContentTypes();
$this->executeMigrations([
'd6_comment_type',
'd6_comment_field',
'd6_comment_field_instance',
]);
}
/**
* Asserts a comment field instance entity.
*
* @param string $bundle
* The bundle ID.
* @param string $field_name
* The field name.
* @param int $default_value
* The field's default_value setting.
* @param int $default_mode
* The field's default_mode setting.
* @param int $per_page
* The field's per_page setting.
* @param bool $anonymous
* The field's anonymous setting.
* @param int $form_location
* The field's form_location setting.
* @param bool $preview
* The field's preview setting.
*/
protected function assertEntity($bundle, $field_name, $default_value, $default_mode, $per_page, $anonymous, $form_location, $preview) {
$entity = FieldConfig::load("node.$bundle.$field_name");
$this->assertInstanceOf(FieldConfig::class, $entity);
$this->assertSame('node', $entity->getTargetEntityTypeId());
$this->assertSame('Comments', $entity->label());
$this->assertTrue($entity->isRequired());
$this->assertSame($bundle, $entity->getTargetBundle());
$this->assertSame($field_name, $entity->getFieldStorageDefinition()->getName());
$this->assertSame($default_value, $entity->get('default_value')[0]['status']);
$this->assertSame($default_mode, $entity->getSetting('default_mode'));
$this->assertSame($per_page, $entity->getSetting('per_page'));
$this->assertSame($anonymous, $entity->getSetting('anonymous'));
$this->assertSame($form_location, $entity->getSetting('form_location'));
$this->assertSame($preview, $entity->getSetting('preview'));
}
/**
* Test the migrated field instance values.
*/
public function testMigration() {
$this->assertEntity('article', 'comment_node_article', 2, 1, 50, 0, FALSE, 1);
$this->assertEntity('company', 'comment_node_company', 2, 1, 50, 0, FALSE, 1);
$this->assertEntity('employee', 'comment_node_employee', 2, 1, 50, 0, FALSE, 1);
$this->assertEntity('event', 'comment_node_event', 2, 1, 50, 0, FALSE, 1);
$this->assertEntity('forum', 'comment_forum', 2, 1, 50, 0, FALSE, 1);
$this->assertEntity('page', 'comment_node_page', 0, 1, 50, 0, FALSE, 1);
$this->assertEntity('sponsor', 'comment_node_sponsor', 2, 1, 50, 0, FALSE, 1);
$this->assertEntity('story', 'comment_node_story', 2, 0, 70, 1, FALSE, 0);
$this->assertEntity('test_event', 'comment_node_test_event', 2, 1, 50, 0, FALSE, 1);
$this->assertEntity('test_page', 'comment_node_test_page', 2, 1, 50, 0, FALSE, 1);
$this->assertEntity('test_planet', 'comment_node_test_planet', 2, 1, 50, 0, FALSE, 1);
$this->assertEntity('test_story', 'comment_node_test_story', 2, 1, 50, 0, FALSE, 1);
}
}

View file

@ -0,0 +1,65 @@
<?php
namespace Drupal\Tests\comment\Kernel\Migrate\d6;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* Tests the migration of comment fields from Drupal 6.
*
* @group comment
* @group migrate_drupal_6
*/
class MigrateCommentFieldTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['comment', 'menu_ui'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(['comment']);
$this->executeMigrations([
'd6_comment_type',
'd6_comment_field',
]);
}
/**
* Asserts a comment field entity.
*
* @param string $comment_type
* The comment type.
*/
protected function assertEntity($comment_type) {
$entity = FieldStorageConfig::load('node.' . $comment_type);
$this->assertInstanceOf(FieldStorageConfig::class, $entity);
$this->assertSame('node', $entity->getTargetEntityTypeId());
$this->assertSame('comment', $entity->getType());
$this->assertSame($comment_type, $entity->getSetting('comment_type'));
}
/**
* Tests the migrated comment fields.
*/
public function testMigration() {
$this->assertEntity('comment_node_article');
$this->assertEntity('comment_node_company');
$this->assertEntity('comment_node_employee');
$this->assertEntity('comment_node_event');
$this->assertEntity('comment_forum');
$this->assertEntity('comment_node_page');
$this->assertEntity('comment_node_sponsor');
$this->assertEntity('comment_node_story');
$this->assertEntity('comment_node_test_event');
$this->assertEntity('comment_node_test_page');
$this->assertEntity('comment_node_test_planet');
$this->assertEntity('comment_node_test_story');
}
}

View file

@ -2,12 +2,15 @@
namespace Drupal\Tests\comment\Kernel\Migrate\d6;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
use Drupal\node\NodeInterface;
/**
* Upgrade comments.
* Tests the migration of comments from Drupal 6.
*
* @group comment
* @group migrate_drupal_6
*/
class MigrateCommentTest extends MigrateDrupal6TestBase {
@ -17,7 +20,12 @@ class MigrateCommentTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['comment', 'menu_ui'];
public static $modules = [
'comment',
'content_translation',
'language',
'menu_ui',
];
/**
* {@inheritdoc}
@ -28,6 +36,7 @@ class MigrateCommentTest extends MigrateDrupal6TestBase {
$this->installEntitySchema('node');
$this->installEntitySchema('comment');
$this->installSchema('comment', ['comment_entity_statistics']);
$this->installSchema('node', ['node_access']);
$this->installConfig(['comment']);
// The entity.node.canonical route must exist when the RDF hook is called.
@ -35,7 +44,10 @@ class MigrateCommentTest extends MigrateDrupal6TestBase {
$this->migrateContent();
$this->executeMigrations([
'language',
'd6_language_content_settings',
'd6_node',
'd6_node_translation',
'd6_comment_type',
'd6_comment_field',
'd6_comment_field_instance',
@ -46,32 +58,66 @@ class MigrateCommentTest extends MigrateDrupal6TestBase {
}
/**
* Tests the Drupal 6 to Drupal 8 comment migration.
* Tests the migrated comments.
*/
public function testComments() {
/** @var \Drupal\Core\Entity\EntityStorageInterface $comment_storage */
$comment_storage = $this->container->get('entity.manager')->getStorage('comment');
/** @var \Drupal\comment\CommentInterface $comment */
$comment = $comment_storage->load(1);
$this->assertIdentical('The first comment.', $comment->getSubject());
$this->assertIdentical('The first comment body.', $comment->comment_body->value);
$this->assertIdentical('filtered_html', $comment->comment_body->format);
$this->assertIdentical(NULL, $comment->pid->target_id);
$this->assertIdentical('1', $comment->getCommentedEntityId());
$this->assertIdentical('node', $comment->getCommentedEntityTypeId());
$this->assertIdentical('en', $comment->language()->getId());
$this->assertIdentical('comment_no_subject', $comment->getTypeId());
$this->assertEquals('203.0.113.1', $comment->getHostname());
public function testMigration() {
$comment = Comment::load(1);
$this->assertSame('The first comment.', $comment->getSubject());
$this->assertSame('The first comment body.', $comment->comment_body->value);
$this->assertSame('filtered_html', $comment->comment_body->format);
$this->assertSame(NULL, $comment->pid->target_id);
$this->assertSame('1', $comment->getCommentedEntityId());
$this->assertSame('node', $comment->getCommentedEntityTypeId());
$this->assertSame('en', $comment->language()->getId());
$this->assertSame('comment_node_story', $comment->getTypeId());
$this->assertSame('203.0.113.1', $comment->getHostname());
$comment = $comment_storage->load(2);
$this->assertIdentical('The response to the second comment.', $comment->subject->value);
$this->assertIdentical('3', $comment->pid->target_id);
$this->assertEquals('203.0.113.2', $comment->getHostname());
$node = $comment->getCommentedEntity();
$this->assertInstanceOf(NodeInterface::class, $node);
$this->assertSame('1', $node->id());
$comment = $comment_storage->load(3);
$this->assertIdentical('The second comment.', $comment->subject->value);
$this->assertIdentical(NULL, $comment->pid->target_id);
$this->assertEquals('203.0.113.3', $comment->getHostname());
$comment = Comment::load(2);
$this->assertSame('The response to the second comment.', $comment->subject->value);
$this->assertSame('3', $comment->pid->target_id);
$this->assertSame('203.0.113.2', $comment->getHostname());
$node = $comment->getCommentedEntity();
$this->assertInstanceOf(NodeInterface::class, $node);
$this->assertSame('1', $node->id());
$comment = Comment::load(3);
$this->assertSame('The second comment.', $comment->subject->value);
$this->assertSame(NULL, $comment->pid->target_id);
$this->assertSame('203.0.113.3', $comment->getHostname());
$node = $comment->getCommentedEntity();
$this->assertInstanceOf(NodeInterface::class, $node);
$this->assertSame('1', $node->id());
// Tests that the language of the comment is migrated from the node.
$comment = Comment::load(7);
$this->assertSame('Comment to John Smith - EN', $comment->subject->value);
$this->assertSame('This is an English comment.', $comment->comment_body->value);
$this->assertSame('21', $comment->getCommentedEntityId());
$this->assertSame('node', $comment->getCommentedEntityTypeId());
$this->assertSame('en', $comment->language()->getId());
$node = $comment->getCommentedEntity();
$this->assertInstanceOf(NodeInterface::class, $node);
$this->assertSame('21', $node->id());
// Tests that the comment language is correct and that the commented entity
// is correctly migrated when the comment was posted to a node translation.
$comment = Comment::load(8);
$this->assertSame('Comment to John Smith - FR', $comment->subject->value);
$this->assertSame('This is a French comment.', $comment->comment_body->value);
$this->assertSame('21', $comment->getCommentedEntityId());
$this->assertSame('node', $comment->getCommentedEntityTypeId());
$this->assertSame('fr', $comment->language()->getId());
$node = $comment->getCommentedEntity();
$this->assertInstanceOf(NodeInterface::class, $node);
$this->assertSame('21', $node->id());
}
}

View file

@ -6,8 +6,9 @@ use Drupal\comment\Entity\CommentType;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* Upgrade comment type.
* Tests the migration of comment types from Drupal 6.
*
* @group comment
* @group migrate_drupal_6
*/
class MigrateCommentTypeTest extends MigrateDrupal6TestBase {
@ -22,20 +23,41 @@ class MigrateCommentTypeTest extends MigrateDrupal6TestBase {
*/
protected function setUp() {
parent::setUp();
$this->installEntitySchema('node');
$this->installEntitySchema('comment');
$this->installConfig(['node', 'comment']);
$this->installConfig(['comment']);
$this->executeMigration('d6_comment_type');
}
/**
* Tests the Drupal 6 to Drupal 8 comment type migration.
* Asserts a comment type entity.
*
* @param string $id
* The entity ID.
* @param string $label
* The entity label.
*/
public function testCommentType() {
$comment_type = CommentType::load('comment');
$this->assertIdentical('node', $comment_type->getTargetEntityTypeId());
$comment_type = CommentType::load('comment_no_subject');
$this->assertIdentical('node', $comment_type->getTargetEntityTypeId());
protected function assertEntity($id, $label) {
$entity = CommentType::load($id);
$this->assertInstanceOf(CommentType::class, $entity);
$this->assertSame($label, $entity->label());
$this->assertSame('node', $entity->getTargetEntityTypeId());
}
/**
* Tests the migrated comment types.
*/
public function testMigration() {
$this->assertEntity('comment_node_article', 'Article comment');
$this->assertEntity('comment_node_company', 'Company comment');
$this->assertEntity('comment_node_employee', 'Employee comment');
$this->assertEntity('comment_node_event', 'Event comment');
$this->assertEntity('comment_forum', 'Forum topic comment');
$this->assertEntity('comment_node_page', 'Page comment');
$this->assertEntity('comment_node_sponsor', 'Sponsor comment');
$this->assertEntity('comment_node_story', 'Story comment');
$this->assertEntity('comment_node_test_event', 'Migrate test event comment');
$this->assertEntity('comment_node_test_page', 'Migrate test page comment');
$this->assertEntity('comment_node_test_planet', 'Migrate test planet comment');
$this->assertEntity('comment_node_test_story', 'Migrate test story comment');
}
}

View file

@ -1,31 +0,0 @@
<?php
namespace Drupal\Tests\comment\Kernel\Migrate\d6;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* Base class for Drupal 6 comment variables to Drupal 8 entity display tests.
*/
abstract class MigrateCommentVariableDisplayBase extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['comment'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(['comment']);
$this->migrateContentTypes();
$this->executeMigrations([
'd6_comment_type',
'd6_comment_field',
'd6_comment_field_instance',
]);
}
}

View file

@ -1,39 +0,0 @@
<?php
namespace Drupal\Tests\comment\Kernel\Migrate\d6;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
/**
* Upgrade comment variables to entity.display.node.*.default.yml.
*
* @group migrate_drupal_6
*/
class MigrateCommentVariableEntityDisplayTest extends MigrateCommentVariableDisplayBase {
/**
* {@inheritdoc}
*/
public static $modules = ['menu_ui'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->executeMigration('d6_comment_entity_display');
}
/**
* Tests comment variables migrated into an entity display.
*/
public function testCommentEntityDisplay() {
foreach (['page', 'story', 'article'] as $type) {
$component = EntityViewDisplay::load('node.' . $type . '.default')->getComponent('comment');
$this->assertIdentical('hidden', $component['label']);
$this->assertIdentical('comment_default', $component['type']);
$this->assertIdentical(20, $component['weight']);
}
}
}

View file

@ -1,45 +0,0 @@
<?php
namespace Drupal\Tests\comment\Kernel\Migrate\d6;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* Upgrade comment subject variable to core.entity_form_display.comment.*.default.yml
*
* @group migrate_drupal_6
*/
class MigrateCommentVariableEntityFormDisplaySubjectTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['comment'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(['comment']);
$this->executeMigrations([
'd6_comment_type',
'd6_comment_entity_form_display_subject',
]);
}
/**
* Tests comment subject variable migrated into an entity display.
*/
public function testCommentEntityFormDisplay() {
$component = EntityFormDisplay::load('comment.comment.default')
->getComponent('subject');
$this->assertIdentical('string_textfield', $component['type']);
$this->assertIdentical(10, $component['weight']);
$component = EntityFormDisplay::load('comment.comment_no_subject.default')
->getComponent('subject');
$this->assertNull($component);
}
}

View file

@ -1,39 +0,0 @@
<?php
namespace Drupal\Tests\comment\Kernel\Migrate\d6;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
/**
* Upgrade comment variables to core.entity_form_display.node.*.default.yml.
*
* @group migrate_drupal_6
*/
class MigrateCommentVariableEntityFormDisplayTest extends MigrateCommentVariableDisplayBase {
/**
* {@inheritdoc}
*/
public static $modules = ['menu_ui'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->executeMigration('d6_comment_entity_form_display');
}
/**
* Tests comment variables migrated into an entity display.
*/
public function testCommentEntityFormDisplay() {
foreach (['page', 'article', 'story'] as $type) {
$component = EntityFormDisplay::load('node.' . $type . '.default')
->getComponent('comment');
$this->assertIdentical('comment_default', $component['type']);
$this->assertIdentical(20, $component['weight']);
}
}
}

View file

@ -1,37 +0,0 @@
<?php
namespace Drupal\Tests\comment\Kernel\Migrate\d6;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* Upgrade comment variables to field.storage.node.comment.yml.
*
* @group migrate_drupal_6
*/
class MigrateCommentVariableFieldTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['comment', 'menu_ui'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(['comment']);
$this->migrateContentTypes();
$this->executeMigrations(['d6_comment_type', 'd6_comment_field']);
}
/**
* Tests comment variables migrated into a field entity.
*/
public function testCommentField() {
$this->assertTrue(is_object(FieldStorageConfig::load('node.comment')));
}
}

View file

@ -1,60 +0,0 @@
<?php
namespace Drupal\Tests\comment\Kernel\Migrate\d6;
use Drupal\comment\CommentManagerInterface;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
use Drupal\node\Entity\Node;
/**
* Upgrade comment variables to field.instance.node.*.comment.yml.
*
* @group migrate_drupal_6
*/
class MigrateCommentVariableInstanceTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['comment', 'menu_ui'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(['comment']);
$this->migrateContentTypes();
$this->executeMigrations([
'd6_comment_type',
'd6_comment_field',
'd6_comment_field_instance',
]);
}
/**
* Test the migrated field instance values.
*/
public function testCommentFieldInstance() {
$node = Node::create(['type' => 'page']);
$this->assertIdentical(0, $node->comment->status);
$this->assertIdentical('comment', $node->comment->getFieldDefinition()->getName());
$settings = $node->comment->getFieldDefinition()->getSettings();
$this->assertIdentical(CommentManagerInterface::COMMENT_MODE_THREADED, $settings['default_mode']);
$this->assertIdentical(50, $settings['per_page']);
$this->assertFalse($settings['anonymous']);
$this->assertFalse($settings['form_location']);
$this->assertTrue($settings['preview']);
$node = Node::create(['type' => 'story']);
$this->assertIdentical(2, $node->comment_no_subject->status);
$this->assertIdentical('comment_no_subject', $node->comment_no_subject->getFieldDefinition()->getName());
$settings = $node->comment_no_subject->getFieldDefinition()->getSettings();
$this->assertIdentical(CommentManagerInterface::COMMENT_MODE_FLAT, $settings['default_mode']);
$this->assertIdentical(70, $settings['per_page']);
$this->assertTrue($settings['anonymous']);
$this->assertFalse($settings['form_location']);
$this->assertFalse($settings['preview']);
}
}

View file

@ -6,12 +6,16 @@ use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Tests migration of comment display configuration.
* Tests the migration of comment entity displays from Drupal 7.
*
* @group comment
* @group migrate_drupal_7
*/
class MigrateCommentEntityDisplayTest extends MigrateDrupal7TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['node', 'comment', 'text', 'menu_ui'];
/**
@ -19,7 +23,7 @@ class MigrateCommentEntityDisplayTest extends MigrateDrupal7TestBase {
*/
protected function setUp() {
parent::setUp();
$this->installConfig(static::$modules);
$this->installConfig(['comment', 'node']);
$this->executeMigrations([
'd7_node_type',
'd7_comment_type',
@ -30,7 +34,7 @@ class MigrateCommentEntityDisplayTest extends MigrateDrupal7TestBase {
}
/**
* Asserts a display entity.
* Asserts various aspects of a comment component in an entity view display.
*
* @param string $id
* The entity ID.
@ -39,10 +43,10 @@ class MigrateCommentEntityDisplayTest extends MigrateDrupal7TestBase {
*/
protected function assertDisplay($id, $component_id) {
$component = EntityViewDisplay::load($id)->getComponent($component_id);
$this->assertTrue(is_array($component));
$this->assertIdentical('hidden', $component['label']);
$this->assertIdentical('comment_default', $component['type']);
$this->assertIdentical(20, $component['weight']);
$this->assertInternalType('array', $component);
$this->assertSame('hidden', $component['label']);
$this->assertSame('comment_default', $component['type']);
$this->assertSame(20, $component['weight']);
}
/**
@ -53,7 +57,7 @@ class MigrateCommentEntityDisplayTest extends MigrateDrupal7TestBase {
$this->assertDisplay('node.article.default', 'comment_node_article');
$this->assertDisplay('node.book.default', 'comment_node_book');
$this->assertDisplay('node.blog.default', 'comment_node_blog');
$this->assertDisplay('node.forum.default', 'comment_node_forum');
$this->assertDisplay('node.forum.default', 'comment_forum');
$this->assertDisplay('node.test_content_type.default', 'comment_node_test_content_type');
}

View file

@ -6,12 +6,16 @@ use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Tests migration of comment form's subject display configuration.
* Tests the migration of comment form's subject display from Drupal 7.
*
* @group comment
* @group migrate_drupal_7
*/
class MigrateCommentEntityFormDisplaySubjectTest extends MigrateDrupal7TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['node', 'comment', 'text', 'menu_ui'];
/**
@ -19,37 +23,47 @@ class MigrateCommentEntityFormDisplaySubjectTest extends MigrateDrupal7TestBase
*/
protected function setUp() {
parent::setUp();
$this->installConfig(static::$modules);
$this->installConfig(['comment']);
$this->executeMigrations([
'd7_node_type',
'd7_comment_type',
'd7_comment_entity_form_display_subject',
]);
}
/**
* Asserts a display entity.
* Asserts that the comment subject field is visible for a node type.
*
* @param string $id
* The entity ID.
* The entity form display ID.
*/
protected function assertDisplay($id) {
protected function assertSubjectVisible($id) {
$component = EntityFormDisplay::load($id)->getComponent('subject');
$this->assertTrue(is_array($component));
$this->assertIdentical('string_textfield', $component['type']);
$this->assertIdentical(10, $component['weight']);
$this->assertInternalType('array', $component);
$this->assertSame('string_textfield', $component['type']);
$this->assertSame(10, $component['weight']);
}
/**
* Asserts that the comment subject field is not visible for a node type.
*
* @param string $id
* The entity form display ID.
*/
protected function assertSubjectNotVisible($id) {
$component = EntityFormDisplay::load($id)->getComponent('subject');
$this->assertNull($component);
}
/**
* Tests the migrated display configuration.
*/
public function testMigration() {
$this->assertDisplay('comment.comment_node_page.default');
$this->assertDisplay('comment.comment_node_article.default');
$this->assertDisplay('comment.comment_node_book.default');
$this->assertDisplay('comment.comment_node_blog.default');
$this->assertDisplay('comment.comment_node_forum.default');
$this->assertDisplay('comment.comment_node_test_content_type.default');
$this->assertSubjectVisible('comment.comment_node_page.default');
$this->assertSubjectVisible('comment.comment_node_article.default');
$this->assertSubjectVisible('comment.comment_node_book.default');
$this->assertSubjectVisible('comment.comment_node_blog.default');
$this->assertSubjectVisible('comment.comment_forum.default');
$this->assertSubjectNotVisible('comment.comment_node_test_content_type.default');
}
}

View file

@ -6,12 +6,16 @@ use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Tests migration of comment form display configuration.
* Tests the migration of comment form display from Drupal 7.
*
* @group comment
* @group migrate_drupal_7
*/
class MigrateCommentEntityFormDisplayTest extends MigrateDrupal7TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['node', 'comment', 'text', 'menu_ui'];
/**
@ -19,7 +23,7 @@ class MigrateCommentEntityFormDisplayTest extends MigrateDrupal7TestBase {
*/
protected function setUp() {
parent::setUp();
$this->installConfig(static::$modules);
$this->installConfig(['comment', 'node']);
$this->executeMigrations([
'd7_node_type',
'd7_comment_type',
@ -30,30 +34,30 @@ class MigrateCommentEntityFormDisplayTest extends MigrateDrupal7TestBase {
}
/**
* Asserts a display entity.
* Asserts various aspects of a comment component in an entity form display.
*
* @param string $id
* The entity ID.
* @param string $component
* @param string $component_id
* The ID of the form component.
*/
protected function assertDisplay($id, $component_id) {
$component = EntityFormDisplay::load($id)->getComponent($component_id);
$this->assertTrue(is_array($component));
$this->assertIdentical('comment_default', $component['type']);
$this->assertIdentical(20, $component['weight']);
$this->assertInternalType('array', $component);
$this->assertSame('comment_default', $component['type']);
$this->assertSame(20, $component['weight']);
}
/**
* Tests the migrated display configuration.
*/
public function testMigration() {
$this->assertDisplay('node.page.default', 'comment');
$this->assertDisplay('node.article.default', 'comment');
$this->assertDisplay('node.book.default', 'comment');
$this->assertDisplay('node.blog.default', 'comment');
$this->assertDisplay('node.forum.default', 'comment');
$this->assertDisplay('node.test_content_type.default', 'comment');
$this->assertDisplay('node.page.default', 'comment_node_page');
$this->assertDisplay('node.article.default', 'comment_node_article');
$this->assertDisplay('node.book.default', 'comment_node_book');
$this->assertDisplay('node.blog.default', 'comment_node_blog');
$this->assertDisplay('node.forum.default', 'comment_forum');
$this->assertDisplay('node.test_content_type.default', 'comment_node_test_content_type');
}
}

View file

@ -2,19 +2,20 @@
namespace Drupal\Tests\comment\Kernel\Migrate\d7;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\Core\Field\FieldConfigInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Tests creation of comment reference fields for each comment type defined
* in Drupal 7.
* Tests the migration of comment field instances from Drupal 7.
*
* @group comment
* @group migrate_drupal_7
*/
class MigrateCommentFieldInstanceTest extends MigrateDrupal7TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['node', 'comment', 'text', 'menu_ui'];
/**
@ -22,7 +23,7 @@ class MigrateCommentFieldInstanceTest extends MigrateDrupal7TestBase {
*/
protected function setUp() {
parent::setUp();
$this->installConfig(static::$modules);
$this->installConfig(['comment', 'node']);
$this->executeMigrations([
'd7_node_type',
'd7_comment_type',
@ -32,14 +33,14 @@ class MigrateCommentFieldInstanceTest extends MigrateDrupal7TestBase {
}
/**
* Asserts a comment field entity.
* Asserts a comment field instance entity.
*
* @param string $id
* The entity ID.
* @param string $field_name
* The field name.
* @param string $bundle
* The bundle ID.
* @param string $field_name
* The field name.
* @param int $default_value
* The field's default_value setting.
* @param int $default_mode
* The field's default_mode setting.
* @param int $per_page
@ -51,36 +52,32 @@ class MigrateCommentFieldInstanceTest extends MigrateDrupal7TestBase {
* @param bool $preview
* The field's preview setting.
*/
protected function assertEntity($id, $field_name, $bundle, $default_mode, $per_page, $anonymous, $form_location, $preview) {
$entity = FieldConfig::load($id);
$this->assertTrue($entity instanceof FieldConfigInterface);
/** @var \Drupal\field\FieldConfigInterface $entity */
$this->assertIdentical('node', $entity->getTargetEntityTypeId());
$this->assertIdentical('Comments', $entity->label());
protected function assertEntity($bundle, $field_name, $default_value, $default_mode, $per_page, $anonymous, $form_location, $preview) {
$entity = FieldConfig::load("node.$bundle.$field_name");
$this->assertInstanceOf(FieldConfig::class, $entity);
$this->assertSame('node', $entity->getTargetEntityTypeId());
$this->assertSame('Comments', $entity->label());
$this->assertTrue($entity->isRequired());
$this->assertIdentical($field_name, $entity->getFieldStorageDefinition()->getName());
$this->assertIdentical($bundle, $entity->getTargetBundle());
$this->assertTrue($entity->get('default_value')[0]['status']);
$this->assertEqual($default_mode, $entity->getSetting('default_mode'));
$this->assertIdentical($per_page, $entity->getSetting('per_page'));
$this->assertEqual($anonymous, $entity->getSetting('anonymous'));
// This assertion fails because 1 !== TRUE. It's extremely strange that
// the form_location setting is returning a boolean, but this appears to
// be a problem with the entity, not with the migration.
// $this->asserIdentical($form_location, $entity->getSetting('form_location'));
$this->assertEqual($preview, $entity->getSetting('preview'));
$this->assertSame($bundle, $entity->getTargetBundle());
$this->assertSame($field_name, $entity->getFieldStorageDefinition()->getName());
$this->assertSame($default_value, $entity->get('default_value')[0]['status']);
$this->assertSame($default_mode, $entity->getSetting('default_mode'));
$this->assertSame($per_page, $entity->getSetting('per_page'));
$this->assertSame($anonymous, $entity->getSetting('anonymous'));
$this->assertSame($form_location, $entity->getSetting('form_location'));
$this->assertSame($preview, $entity->getSetting('preview'));
}
/**
* Tests the migrated fields.
*/
public function testMigration() {
$this->assertEntity('node.page.comment_node_page', 'comment_node_page', 'page', TRUE, 50, FALSE, CommentItemInterface::FORM_BELOW, TRUE);
$this->assertEntity('node.article.comment_node_article', 'comment_node_article', 'article', TRUE, 50, FALSE, CommentItemInterface::FORM_BELOW, TRUE);
$this->assertEntity('node.blog.comment_node_blog', 'comment_node_blog', 'blog', TRUE, 50, FALSE, CommentItemInterface::FORM_BELOW, TRUE);
$this->assertEntity('node.book.comment_node_book', 'comment_node_book', 'book', TRUE, 50, FALSE, CommentItemInterface::FORM_BELOW, TRUE);
$this->assertEntity('node.forum.comment_node_forum', 'comment_node_forum', 'forum', TRUE, 50, FALSE, CommentItemInterface::FORM_BELOW, TRUE);
$this->assertEntity('node.test_content_type.comment_node_test_content_type', 'comment_node_test_content_type', 'test_content_type', TRUE, 30, FALSE, CommentItemInterface::FORM_BELOW, TRUE);
$this->assertEntity('page', 'comment_node_page', 0, 1, 50, 0, TRUE, 1);
$this->assertEntity('article', 'comment_node_article', 2, 1, 50, 0, TRUE, 1);
$this->assertEntity('blog', 'comment_node_blog', 2, 1, 50, 0, TRUE, 1);
$this->assertEntity('book', 'comment_node_book', 2, 1, 50, 0, TRUE, 1);
$this->assertEntity('forum', 'comment_forum', 2, 1, 50, 0, TRUE, 1);
$this->assertEntity('test_content_type', 'comment_node_test_content_type', 2, 1, 30, 0, TRUE, 1);
}
}

View file

@ -3,27 +3,28 @@
namespace Drupal\Tests\comment\Kernel\Migrate\d7;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\FieldStorageConfigInterface;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Tests creation of comment reference fields for each comment type defined
* in Drupal 7.
* Tests the migration of comment fields from Drupal 7.
*
* @group comment
* @group migrate_drupal_7
*/
class MigrateCommentFieldTest extends MigrateDrupal7TestBase {
public static $modules = ['node', 'comment', 'text', 'menu_ui'];
/**
* {@inheritdoc}
*/
public static $modules = ['node', 'comment', 'text'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(static::$modules);
$this->installConfig(['comment']);
$this->executeMigrations([
'd7_node_type',
'd7_comment_type',
'd7_comment_field',
]);
@ -32,30 +33,27 @@ class MigrateCommentFieldTest extends MigrateDrupal7TestBase {
/**
* Asserts a comment field entity.
*
* @param string $id
* The entity ID.
* @param string $comment_type
* The comment type (bundle ID) the field references.
* The comment type.
*/
protected function assertEntity($id, $comment_type) {
$entity = FieldStorageConfig::load($id);
$this->assertTrue($entity instanceof FieldStorageConfigInterface);
/** @var \Drupal\field\FieldStorageConfigInterface $entity */
$this->assertIdentical('node', $entity->getTargetEntityTypeId());
$this->assertIdentical('comment', $entity->getType());
$this->assertIdentical($comment_type, $entity->getSetting('comment_type'));
protected function assertEntity($comment_type) {
$entity = FieldStorageConfig::load('node.' . $comment_type);
$this->assertInstanceOf(FieldStorageConfig::class, $entity);
$this->assertSame('node', $entity->getTargetEntityTypeId());
$this->assertSame('comment', $entity->getType());
$this->assertSame($comment_type, $entity->getSetting('comment_type'));
}
/**
* Tests the migrated fields.
* Tests the migrated comment fields.
*/
public function testMigration() {
$this->assertEntity('node.comment_node_page', 'comment_node_page');
$this->assertEntity('node.comment_node_article', 'comment_node_article');
$this->assertEntity('node.comment_node_blog', 'comment_node_blog');
$this->assertEntity('node.comment_node_book', 'comment_node_book');
$this->assertEntity('node.comment_node_forum', 'comment_node_forum');
$this->assertEntity('node.comment_node_test_content_type', 'comment_node_test_content_type');
$this->assertEntity('comment_node_page');
$this->assertEntity('comment_node_article');
$this->assertEntity('comment_node_blog');
$this->assertEntity('comment_node_book');
$this->assertEntity('comment_forum');
$this->assertEntity('comment_node_test_content_type');
}
}

View file

@ -2,19 +2,37 @@
namespace Drupal\Tests\comment\Kernel\Migrate\d7;
use Drupal\comment\CommentInterface;
use Drupal\comment\Entity\Comment;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
use Drupal\node\NodeInterface;
/**
* Tests migration of comments from Drupal 7.
* Tests the migration of comments from Drupal 7.
*
* @group comment
* @group migrate_drupal_7
*/
class MigrateCommentTest extends MigrateDrupal7TestBase {
public static $modules = ['filter', 'node', 'comment', 'text', 'menu_ui'];
/**
* {@inheritdoc}
*/
public static $modules = [
'comment',
'content_translation',
'datetime',
'filter',
'image',
'language',
'link',
'menu_ui',
// Required for translation migrations.
'migrate_drupal_multilingual',
'node',
'taxonomy',
'telephone',
'text',
];
/**
* {@inheritdoc}
@ -22,50 +40,116 @@ class MigrateCommentTest extends MigrateDrupal7TestBase {
protected function setUp() {
parent::setUp();
$this->installConfig(static::$modules);
$this->installEntitySchema('node');
$this->installEntitySchema('comment');
$this->installEntitySchema('taxonomy_term');
$this->installConfig(['comment', 'node']);
$this->installSchema('comment', ['comment_entity_statistics']);
$this->installSchema('node', ['node_access']);
$this->executeMigrations([
'd7_filter_format',
'language',
'd7_node_type',
'd7_language_content_settings',
'd7_user_role',
'd7_user',
]);
$this->executeMigration('d7_node_type');
// We only need the test_content_type node migration to run for real, so
// mock all the others.
$this->prepareMigrations([
'd7_node' => [
[[0], [0]],
],
]);
$this->executeMigrations([
'd7_node_type',
'd7_node',
'd7_node_translation',
'd7_comment_type',
'd7_comment_field',
'd7_comment_field_instance',
'd7_comment_entity_display',
'd7_comment_entity_form_display',
'd7_taxonomy_vocabulary',
'd7_field',
'd7_field_instance',
'd7_comment',
'd7_entity_translation_settings',
'd7_comment_entity_translation',
]);
}
/**
* Tests migration of comments from Drupal 7.
* Tests the migrated comments.
*/
public function testCommentMigration() {
public function testMigration() {
$comment = Comment::load(1);
$this->assertTrue($comment instanceof CommentInterface);
/** @var \Drupal\comment\CommentInterface $comment */
$this->assertIdentical('A comment', $comment->getSubject());
$this->assertIdentical('1421727536', $comment->getCreatedTime());
$this->assertIdentical('1421727536', $comment->getChangedTime());
$this->assertInstanceOf(Comment::class, $comment);
$this->assertSame('Subject field in English', $comment->getSubject());
$this->assertSame('1421727536', $comment->getCreatedTime());
$this->assertSame('1421727536', $comment->getChangedTime());
$this->assertTrue($comment->getStatus());
$this->assertIdentical('admin', $comment->getAuthorName());
$this->assertIdentical('admin@local.host', $comment->getAuthorEmail());
$this->assertIdentical('This is a comment', $comment->comment_body->value);
$this->assertIdentical('filtered_html', $comment->comment_body->format);
$this->assertEquals('2001:db8:ffff:ffff:ffff:ffff:ffff:ffff', $comment->getHostname());
$this->assertSame('admin', $comment->getAuthorName());
$this->assertSame('admin@local.host', $comment->getAuthorEmail());
$this->assertSame('This is a comment', $comment->comment_body->value);
$this->assertSame('filtered_html', $comment->comment_body->format);
$this->assertSame('2001:db8:ffff:ffff:ffff:ffff:ffff:ffff', $comment->getHostname());
$this->assertSame('en', $comment->language()->getId());
$this->assertSame('1000000', $comment->field_integer->value);
$node = $comment->getCommentedEntity();
$this->assertTrue($node instanceof NodeInterface);
$this->assertIdentical('1', $node->id());
$this->assertInstanceOf(NodeInterface::class, $node);
$this->assertSame('1', $node->id());
// Tests that comments that used the Drupal 7 Title module and that have
// their subject replaced by a real field are correctly migrated.
$comment = Comment::load(2);
$this->assertInstanceOf(Comment::class, $comment);
$this->assertSame('TNG for the win!', $comment->getSubject());
$this->assertSame('TNG is better than DS9.', $comment->comment_body->value);
$this->assertSame('en', $comment->language()->getId());
// Tests that the commented entity is correctly migrated when the comment
// was posted to a node translation.
$comment = Comment::load(3);
$this->assertInstanceOf(Comment::class, $comment);
$this->assertSame('Comment to IS translation', $comment->getSubject());
$this->assertSame('This is a comment to an Icelandic translation.', $comment->comment_body->value);
$this->assertSame('2', $comment->getCommentedEntityId());
$this->assertSame('node', $comment->getCommentedEntityTypeId());
$this->assertSame('is', $comment->language()->getId());
$node = $comment->getCommentedEntity();
$this->assertInstanceOf(NodeInterface::class, $node);
$this->assertSame('2', $node->id());
}
/**
* Tests the migration of comment entity translations.
*/
public function testCommentEntityTranslations() {
$manager = $this->container->get('content_translation.manager');
// Get the comment and its translations.
$comment = Comment::load(1);
$comment_fr = $comment->getTranslation('fr');
$comment_is = $comment->getTranslation('is');
// Test that fields translated with Entity Translation are migrated.
$this->assertSame('Subject field in English', $comment->getSubject());
$this->assertSame('Subject field in French', $comment_fr->getSubject());
$this->assertSame('Subject field in Icelandic', $comment_is->getSubject());
$this->assertSame('1000000', $comment->field_integer->value);
$this->assertSame('2000000', $comment_fr->field_integer->value);
$this->assertSame('3000000', $comment_is->field_integer->value);
// Test that the French translation metadata is correctly migrated.
$metadata_fr = $manager->getTranslationMetadata($comment_fr);
$this->assertFalse($metadata_fr->isPublished());
$this->assertSame('en', $metadata_fr->getSource());
$this->assertSame('1', $metadata_fr->getAuthor()->uid->value);
$this->assertSame('1531837764', $metadata_fr->getCreatedTime());
$this->assertSame('1531837764', $metadata_fr->getChangedTime());
$this->assertFalse($metadata_fr->isOutdated());
// Test that the Icelandic translation metadata is correctly migrated.
$metadata_is = $manager->getTranslationMetadata($comment_is);
$this->assertTrue($metadata_is->isPublished());
$this->assertSame('en', $metadata_is->getSource());
$this->assertSame('2', $metadata_is->getAuthor()->uid->value);
$this->assertSame('1531838064', $metadata_is->getCreatedTime());
$this->assertSame('1531838064', $metadata_is->getChangedTime());
$this->assertTrue($metadata_is->isOutdated());
}
}

View file

@ -2,29 +2,29 @@
namespace Drupal\Tests\comment\Kernel\Migrate\d7;
use Drupal\comment\CommentTypeInterface;
use Drupal\comment\Entity\CommentType;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Tests migration of comment types from Drupal 7.
* Tests the migration of comment types from Drupal 7.
*
* @group comment
* @group migrate_drupal_7
*/
class MigrateCommentTypeTest extends MigrateDrupal7TestBase {
public static $modules = ['node', 'comment', 'text', 'menu_ui'];
/**
* {@inheritdoc}
*/
public static $modules = ['node', 'comment', 'text'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(static::$modules);
$this->executeMigrations([
'd7_node_type',
'd7_comment_type',
]);
$this->installConfig(['comment']);
$this->executeMigration('d7_comment_type');
}
/**
@ -37,26 +37,21 @@ class MigrateCommentTypeTest extends MigrateDrupal7TestBase {
*/
protected function assertEntity($id, $label) {
$entity = CommentType::load($id);
$this->assertTrue($entity instanceof CommentTypeInterface);
/** @var \Drupal\comment\CommentTypeInterface $entity */
$this->assertIdentical($label, $entity->label());
$this->assertIdentical('node', $entity->getTargetEntityTypeId());
$this->assertInstanceOf(CommentType::class, $entity);
$this->assertSame($label, $entity->label());
$this->assertSame('node', $entity->getTargetEntityTypeId());
}
/**
* Tests the migrated comment types.
*/
public function testMigration() {
$this->assertEntity('comment_node_page', 'Basic page comment');
$this->assertEntity('comment_node_article', 'Article comment');
$this->assertEntity('comment_node_blog', 'Blog entry comment');
$this->assertEntity('comment_node_book', 'Book page comment');
$this->assertEntity('comment_node_forum', 'Forum topic comment');
$this->assertEntity('comment_forum', 'Forum topic comment');
$this->assertEntity('comment_node_page', 'Basic page comment');
$this->assertEntity('comment_node_test_content_type', 'Test content type comment');
$migration = $this->getMigration('d7_comment_type');
// Validate that the source count and processed count match up.
$this->assertIdentical($migration->getSourcePlugin()->count(), $migration->getIdMap()->processedCount());
}
}

View file

@ -66,10 +66,12 @@ class CommentSourceWithHighWaterTest extends MigrateSqlSourceTestBase {
[
'nid' => 2,
'type' => 'story',
'language' => 'en',
],
[
'nid' => 3,
'type' => 'page',
'language' => 'fr',
],
];
@ -91,6 +93,7 @@ class CommentSourceWithHighWaterTest extends MigrateSqlSourceTestBase {
'homepage' => '',
'format' => 'testformat2',
'type' => 'page',
'language' => 'fr',
],
];

View file

@ -65,10 +65,12 @@ class CommentTest extends MigrateSqlSourceTestBase {
[
'nid' => 2,
'type' => 'story',
'language' => 'en',
],
[
'nid' => 3,
'type' => 'page',
'language' => 'fr',
],
];
@ -90,6 +92,7 @@ class CommentTest extends MigrateSqlSourceTestBase {
'homepage' => '',
'format' => 'testformat1',
'type' => 'story',
'language' => 'en',
],
[
'cid' => 2,
@ -107,6 +110,7 @@ class CommentTest extends MigrateSqlSourceTestBase {
'homepage' => '',
'format' => 'testformat2',
'type' => 'page',
'language' => 'fr',
],
];

Some files were not shown because too many files have changed in this diff Show more