ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,388 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml;
use Magento\Framework\Intl\DateTimeFactory;
use Magento\Framework\Stdlib\DateTime;
use Magento\TestFramework\Mail\Template\TransportBuilderMock;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test class for \Magento\User\Controller\Adminhtml\Auth
*
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AuthTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Test form existence
* @covers \Magento\User\Controller\Adminhtml\Auth\Forgotpassword::execute
*/
public function testFormForgotpasswordAction()
{
$this->dispatch('backend/admin/auth/forgotpassword');
$expected = 'Password Help';
$this->assertStringContainsString($expected, $this->getResponse()->getBody());
}
/**
* Test redirection to startup page after success password recovering posting
*
* @covers \Magento\User\Controller\Adminhtml\Auth\Forgotpassword::execute
* @magentoDbIsolation enabled
*/
public function testForgotpasswordAction()
{
$this->getRequest()->setPostValue('email', 'test@test.com');
$this->dispatch('backend/admin/auth/forgotpassword');
$this->assertRedirect(
$this->equalTo(
Bootstrap::getObjectManager()->get(
\Magento\Backend\Helper\Data::class
)->getHomePageUrl()
)
);
}
/**
* Test email sending for forgotPassword action
*
* @magentoAdminConfigFixture admin/emails/forgot_email_template admin_emails_forgot_email_template
* @magentoAdminConfigFixture admin/emails/forgot_email_identity general
* @magentoDataFixture Magento/User/_files/user_with_role.php
*/
public function testEmailSendForgotPasswordAction()
{
/** @var TransportBuilderMock $transportMock */
$transportMock = Bootstrap::getObjectManager()->get(
TransportBuilderMock::class
);
$this->getRequest()->setPostValue('email', 'adminUser@example.com');
$this->dispatch('backend/admin/auth/forgotpassword');
$this->assertRedirect(
$this->equalTo(
Bootstrap::getObjectManager()->get(
\Magento\Backend\Helper\Data::class
)->getHomePageUrl()
)
);
$message = $transportMock->getSentMessage();
$this->assertNotEmpty($message);
$this->assertEquals(
__('Password Reset Confirmation for %1', ['John Doe'])->render(),
$message->getSubject()
);
}
/**
* Test reset password action
*
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPassword::execute
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPassword::_validateResetPasswordLinkToken
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testResetPasswordAction()
{
/** @var $user \Magento\User\Model\User */
$user = Bootstrap::getObjectManager()->create(
\Magento\User\Model\User::class
)->loadByUsername(
'dummy_username'
);
$this->assertNotEmpty($user->getId(), 'Broken fixture');
$resetPasswordToken = Bootstrap::getObjectManager()->get(
\Magento\User\Helper\Data::class
)->generateResetPasswordLinkToken();
$user->changeResetPasswordLinkToken($resetPasswordToken);
$user->save();
$this->getRequest()->setQueryValue('token', $resetPasswordToken)->setQueryValue('id', $user->getId());
$this->dispatch('backend/admin/auth/resetpassword');
$this->assertEquals('adminhtml', $this->getRequest()->getRouteName());
$this->assertEquals('auth', $this->getRequest()->getControllerName());
$this->assertEquals('resetpassword', $this->getRequest()->getActionName());
$this->assertTrue((bool)strpos($this->getResponse()->getBody(), $resetPasswordToken));
}
/**
* Test reset password action extends expiry of token
*
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPassword::execute
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPassword::_validateResetPasswordLinkToken
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testResetPasswordActionWithTokenNearExpiry()
{
/** @var $user \Magento\User\Model\User */
$user = Bootstrap::getObjectManager()->create(
\Magento\User\Model\User::class
)->loadByUsername(
'dummy_username'
);
$this->assertNotEmpty($user->getId(), 'Broken fixture');
$resetPasswordToken = Bootstrap::getObjectManager()->get(
\Magento\User\Helper\Data::class
)->generateResetPasswordLinkToken();
$user->changeResetPasswordLinkToken($resetPasswordToken);
$anHourAgo = Bootstrap::getObjectManager()->create(DateTimeFactory::class)
->create()
->sub(\DateInterval::createFromDateString('1 hour'))
->format(DateTime::DATETIME_PHP_FORMAT);
$user->setRpTokenCreatedAt($anHourAgo);
$user->save();
$this->getRequest()->setQueryValue('token', $resetPasswordToken)->setQueryValue('id', $user->getId());
$this->dispatch('backend/admin/auth/resetpassword');
$this->assertEquals('adminhtml', $this->getRequest()->getRouteName());
$this->assertEquals('auth', $this->getRequest()->getControllerName());
$this->assertEquals('resetpassword', $this->getRequest()->getActionName());
$this->assertTrue((bool)strpos($this->getResponse()->getBody(), $resetPasswordToken));
$this->assertNotEquals($anHourAgo, $user->reload()->getRpTokenCreatedAt());
}
/**
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPassword::execute
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPassword::_validateResetPasswordLinkToken
*/
public function testResetPasswordActionWithDummyToken()
{
$this->getRequest()->setQueryValue('token', 'dummy')->setQueryValue('id', 1);
$this->dispatch('backend/admin/auth/resetpassword');
$this->assertSessionMessages(
$this->equalTo(['Your password reset link has expired.']),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
$this->assertRedirect();
}
/**
* @dataProvider resetPasswordDataProvider
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPasswordPost::execute
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPasswordPost::_validateResetPasswordLinkToken
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testResetPasswordPostAction($password, $passwordConfirmation, $isPasswordChanged)
{
$objectManager = Bootstrap::getObjectManager();
/** @var $user \Magento\User\Model\User */
$user = $objectManager->create(\Magento\User\Model\User::class);
$user->loadByUsername('dummy_username');
$this->assertNotEmpty($user->getId(), 'Broken fixture');
/** @var \Magento\User\Helper\Data $helper */
$helper = $objectManager->get(\Magento\User\Helper\Data::class);
$resetPasswordToken = $helper->generateResetPasswordLinkToken();
$user->changeResetPasswordLinkToken($resetPasswordToken);
$user->save();
$oldPassword = $user->getPassword();
$this->getRequest()->setQueryValue(
'token',
$resetPasswordToken
)->setQueryValue(
'id',
$user->getId()
)->setPostValue(
'password',
$password
)->setPostValue(
'confirmation',
$passwordConfirmation
);
$this->dispatch('backend/admin/auth/resetpasswordpost');
/** @var \Magento\Backend\Helper\Data $backendHelper */
$backendHelper = $objectManager->get(\Magento\Backend\Helper\Data::class);
if ($isPasswordChanged) {
$this->assertRedirect($this->equalTo($backendHelper->getHomePageUrl()));
} else {
$this->assertRedirect(
$this->stringContains('backend/admin/auth/resetpassword')
);
}
/** @var $user \Magento\User\Model\User */
$user = $objectManager->create(\Magento\User\Model\User::class);
$user->loadByUsername('dummy_username');
if ($isPasswordChanged) {
/** @var \Magento\Framework\Encryption\EncryptorInterface $encryptor */
$encryptor = $objectManager->get(\Magento\Framework\Encryption\EncryptorInterface::class);
$this->assertTrue($encryptor->validateHash($password, $user->getPassword()));
} else {
$this->assertEquals($oldPassword, $user->getPassword());
}
}
public function resetPasswordDataProvider()
{
$password = uniqid('123q');
return [
[$password, $password, true],
[$password, '', false],
[$password, $password . '123', false],
['', '', false],
['', $password, false]
];
}
/**
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPasswordPost::execute
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPasswordPost::_validateResetPasswordLinkToken
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testResetPasswordPostActionWithDummyToken()
{
$this->getRequest()->setQueryValue('token', 'dummy')->setQueryValue('id', 1);
$this->dispatch('backend/admin/auth/resetpasswordpost');
$this->assertSessionMessages(
$this->equalTo(['Your password reset link has expired.']),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Backend\Helper\Data $backendHelper */
$backendHelper = $objectManager->get(\Magento\Backend\Helper\Data::class);
$this->assertRedirect($this->equalTo($backendHelper->getHomePageUrl()));
}
/**
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPasswordPost::execute
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPasswordPost::_validateResetPasswordLinkToken
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testResetPasswordPostActionWithInvalidPassword()
{
$objectManager = Bootstrap::getObjectManager();
$user = $objectManager->create(\Magento\User\Model\User::class);
$user->loadByUsername('dummy_username');
$resetPasswordToken = null;
if ($user->getId()) {
/** @var \Magento\User\Helper\Data $userHelper */
$userHelper = $objectManager->get(\Magento\User\Helper\Data::class);
$resetPasswordToken = $userHelper->generateResetPasswordLinkToken();
$user->changeResetPasswordLinkToken($resetPasswordToken);
$user->save();
}
$newDummyPassword = 'new_dummy_password2';
$this->getRequest()->setQueryValue(
'token',
$resetPasswordToken
)->setQueryValue(
'id',
$user->getId()
)->setPostValue(
'password',
$newDummyPassword
)->setPostValue(
'confirmation',
'invalid'
);
$this->dispatch('backend/admin/auth/resetpasswordpost');
$this->assertSessionMessages(
$this->equalTo(['Your password confirmation must match your password.']),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
$this->assertRedirect();
}
/**
* Prepare email mock to test emails
*
* @param int $occurrenceNumber
* @param string $templateId
* @param string $sender
* @return \PHPUnit\Framework\MockObject\MockObject
*/
protected function prepareEmailMock($occurrenceNumber, $templateId, $sender)
{
$transportMock = $this->getMockBuilder(\Magento\Framework\Mail\TransportInterface::class)
->setMethods(['sendMessage'])
->getMockForAbstractClass();
$transportMock->expects($this->exactly($occurrenceNumber))
->method('sendMessage');
$transportBuilderMock = $this->getMockBuilder(\Magento\Framework\Mail\Template\TransportBuilder::class)
->disableOriginalConstructor()
->setMethods(
[
'setTemplateModel',
'addTo',
'setFrom',
'setTemplateIdentifier',
'setTemplateVars',
'setTemplateOptions',
'getTransport'
]
)
->getMock();
$transportBuilderMock->method('setTemplateIdentifier')
->with($templateId)
->willReturnSelf();
$transportBuilderMock->method('setTemplateModel')
->with(\Magento\Email\Model\BackendTemplate::class)
->willReturnSelf();
$transportBuilderMock->method('setTemplateOptions')
->willReturnSelf();
$transportBuilderMock->method('setTemplateVars')
->willReturnSelf();
$transportBuilderMock->method('setFrom')
->with($sender)
->willReturnSelf();
$transportBuilderMock->method('addTo')
->willReturnSelf();
$transportBuilderMock->expects($this->exactly($occurrenceNumber))
->method('getTransport')
->willReturn($transportMock);
return $transportBuilderMock;
}
/**
* Add mocked object to environment
*
* @param \PHPUnit\Framework\MockObject\MockObject $transportBuilderMock
* @param string $originalClassName
*/
protected function addMockToClass(
\PHPUnit\Framework\MockObject\MockObject $transportBuilderMock,
$originalClassName
) {
$userMock = $this->_objectManager->create(
$originalClassName,
['transportBuilder' => $transportBuilderMock]
);
$factoryMock = $this->getMockBuilder(\Magento\User\Model\UserFactory::class)
->disableOriginalConstructor()
->setMethods(
[
'create'
]
)
->getMock();
$factoryMock->method('create')
->willReturn($userMock);
$this->_objectManager->addSharedInstance(
$factoryMock,
\Magento\User\Model\UserFactory::class
);
}
}
@@ -0,0 +1,42 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml\Locks;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Testing the list of locked users.
*
* @magentoAppArea adminhtml
*/
class GridTest extends AbstractBackendController
{
/**
* Test index action
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/User/_files/locked_users.php
*/
public function testGridAction()
{
$this->dispatch('backend/admin/locks/grid');
$body = $this->getResponse()->getBody();
$this->assertStringContainsString('data-column="username"', $body);
$this->assertStringContainsString('data-column="last_login"', $body);
$this->assertStringContainsString('data-column="last_login"', $body);
$this->assertStringContainsString('data-column="failures_num"', $body);
$this->assertStringContainsString('data-column="lock_expires"', $body);
$this->assertMatchesRegularExpression(
'/<td data-column\="username"\s*class\="[^"]*col-name[^"]*col-username[^"]*"\s*>\s*adminUser1\s*<\/td>/',
$body
);
$this->assertMatchesRegularExpression(
'/<td data-column\="username"\s*class\="[^"]*col-name[^"]*col-username[^"]*"\s*>\s*adminUser2\s*<\/td>/',
$body
);
}
}
@@ -0,0 +1,37 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml\Locks;
/**
* Locked users page test.
*
* @magentoAppArea adminhtml
*/
class IndexTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Test index action
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/User/_files/locked_users.php
*/
public function testIndexAction()
{
$this->dispatch('backend/admin/locks/index');
$body = $this->getResponse()->getBody();
$this->assertStringContainsString('<h1 class="page-title">Locked Users</h1>', $body);
$this->assertMatchesRegularExpression(
'/<td data-column\="username"\s*class\="[^"]*col-name[^"]*col-username[^"]*"\s*>\s*adminUser1\s*<\/td>/',
$body
);
$this->assertMatchesRegularExpression(
'/<td data-column\="username"\s*class\="[^"]*col-name[^"]*col-username\s*"[^"]*>\s*adminUser2\s*<\/td>/',
$body
);
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml\Locks;
/**
* Testing unlock controller.
*
* @magentoAppArea adminhtml
*/
class MassUnlockTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Test index action
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/User/_files/locked_users.php
*/
public function testMassUnlockAction()
{
$userIds = [];
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $model \Magento\User\Model\User */
$model = $objectManager->create(\Magento\User\Model\User::class);
$userIds[] = $model->loadByUsername('adminUser1')->getId();
$userIds[] = $model->loadByUsername('adminUser2')->getId();
$request = $this->getRequest();
$request->setPostValue(
'unlock',
$userIds
);
$this->dispatch('backend/admin/locks/massunlock');
$this->assertSessionMessages(
$this->containsEqual((string)__('Unlocked %1 user(s).', count($userIds))),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect();
}
}
@@ -0,0 +1,31 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml\User;
/**
* Test class for \Magento\User\Controller\Adminhtml\User\Delete
* @magentoAppArea adminhtml
*/
class DeleteTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @covers \Magento\User\Controller\Adminhtml\User\Delete::execute
*/
public function testDeleteActionWithError()
{
$user = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\User\Model\User::class);
/** @var \Magento\Framework\Message\ManagerInterface $messageManager */
$messageManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\Message\ManagerInterface::class);
$user->load(1);
$this->getRequest()->setPostValue('user_id', $user->getId() . '_suffix_ignored_in_mysql_casting_to_int');
$this->dispatch('backend/admin/user/delete');
$message = $messageManager->getMessages()->getLastAddedMessage()->getText();
$this->assertEquals('You cannot delete your own account.', $message);
}
}
@@ -0,0 +1,112 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml\User;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test class for Magento\User\Controller\Adminhtml\User\InvalidateToken.
*
* @magentoAppArea adminhtml
*/
class InvalidateTokenTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @magentoDataFixture Magento/User/_files/user_with_role.php
*/
public function testInvalidateSingleToken()
{
/** @var \Magento\Integration\Api\AdminTokenServiceInterface $tokenService */
$tokenService = Bootstrap::getObjectManager()->get(\Magento\Integration\Api\AdminTokenServiceInterface::class);
/** @var \Magento\Integration\Model\Oauth\Token $tokenModel */
$tokenModel = Bootstrap::getObjectManager()->get(\Magento\Integration\Model\Oauth\Token::class);
/** @var \Magento\User\Model\User $userModel */
$userModel = Bootstrap::getObjectManager()->get(\Magento\User\Model\User::class);
$adminUserNameFromFixture = 'adminUser';
$tokenService->createAdminAccessToken(
$adminUserNameFromFixture,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$adminUserId = $userModel->loadByUsername($adminUserNameFromFixture)->getId();
// invalidate token
$this->getRequest()->setParam('user_id', $adminUserId);
$this->dispatch('backend/admin/user/invalidateToken');
$token = $tokenModel->loadByAdminId($adminUserId);
$this->assertNull($token->getId());
}
/**
* @magentoDataFixture Magento/User/_files/user_with_role.php
*/
public function testInvalidateMultipleTokens()
{
/** @var \Magento\Integration\Api\AdminTokenServiceInterface $tokenService */
$tokenService = Bootstrap::getObjectManager()->get(\Magento\Integration\Api\AdminTokenServiceInterface::class);
/** @var \Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory $tokenModelCollectionFactory */
$tokenModelCollectionFactory = Bootstrap::getObjectManager()->get(
\Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory::class
);
/** @var \Magento\User\Model\User $userModel */
$userModel = Bootstrap::getObjectManager()->get(\Magento\User\Model\User::class);
$adminUserNameFromFixture = 'adminUser';
$tokenService->createAdminAccessToken(
$adminUserNameFromFixture,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$tokenService->createAdminAccessToken(
$adminUserNameFromFixture,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$adminUserId = $userModel->loadByUsername($adminUserNameFromFixture)->getId();
// invalidate tokens
$this->getRequest()->setParam('user_id', $adminUserId);
$this->dispatch('backend/admin/user/invalidateToken');
foreach ($tokenModelCollectionFactory->create()->addFilterByAdminId($adminUserId) as $token) {
$this->assertEquals(1, $token->getRevoked());
}
}
/**
* @magentoDataFixture Magento/User/_files/user_with_role.php
*/
public function testInvalidateTokenNoTokens()
{
/** @var \Magento\User\Model\User $userModel */
$userModel = Bootstrap::getObjectManager()->get(\Magento\User\Model\User::class);
$adminUserNameFromFixture = 'adminUser';
$adminUserId = $userModel->loadByUsername($adminUserNameFromFixture)->getId();
// invalidate token
$this->getRequest()->setParam('user_id', $adminUserId);
$this->dispatch('backend/admin/user/invalidateToken');
}
public function testInvalidateTokenNoUser()
{
$this->dispatch('backend/admin/user/invalidateToken');
$this->assertSessionMessages(
$this->equalTo(['We can\'t find a user to revoke.']),
MessageInterface::TYPE_ERROR
);
}
public function testInvalidateTokenInvalidUser()
{
$adminUserId = 999;
// invalidate token
$this->getRequest()->setParam('user_id', $adminUserId);
$this->dispatch('backend/admin/user/invalidateToken');
}
}
@@ -0,0 +1,50 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml\User;
/**
* Test class for \Magento\User\Controller\Adminhtml\User\Role.
*
* @magentoAppArea adminhtml
*/
class RoleTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
public function testEditRoleAction()
{
$roleAdmin = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Authorization\Model\Role::class);
$roleAdmin->load(\Magento\TestFramework\Bootstrap::ADMIN_ROLE_NAME, 'role_name');
$this->getRequest()->setParam('rid', $roleAdmin->getId());
$this->dispatch('backend/admin/user_role/editrole');
$this->assertStringContainsString('Role Information', $this->getResponse()->getBody());
$this->assertStringContainsString($roleAdmin->getRoleName(), $this->getResponse()->getBody());
}
/**
* @covers \Magento\User\Controller\Adminhtml\User\Role\Editrolegrid::execute
*/
public function testEditrolegridAction()
{
$this->getRequest()->setParam('ajax', true)->setParam('isAjax', true);
$this->dispatch('backend/admin/user_role/editrolegrid');
$expected = '%a<table %a id="roleUserGrid_table">%a';
$this->assertStringMatchesFormat($expected, $this->getResponse()->getBody());
}
/**
* @covers \Magento\User\Controller\Adminhtml\User\Role\RoleGrid::execute
*/
public function testRoleGridAction()
{
$this->getRequest()->setParam('ajax', true)->setParam('isAjax', true)->setParam('user_id', 1);
$this->dispatch('backend/admin/user_role/roleGrid');
$expected = '%a<table %a id="roleGrid_table">%a';
$this->assertStringMatchesFormat($expected, $this->getResponse()->getBody());
}
}
@@ -0,0 +1,336 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\TestFramework\Bootstrap;
/**
* @magentoAppArea adminhtml
*/
class UserTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Verify that the main user page contains the user grid
*/
public function testIndexAction()
{
$this->dispatch('backend/admin/user/index');
$response = $this->getResponse()->getBody();
$this->assertStringContainsString('Users', $response);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//*[@id="permissionsUserGrid_table"]',
$response
)
);
}
/**
* Verify that attempting to save a user when no data is present redirects back to the main user page
*/
public function testSaveActionNoData()
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/admin/user/save');
$this->assertRedirect($this->stringContains('backend/admin/user/index/'));
}
/**
* Verify that a user cannot be saved if it no longer exists
*
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testSaveActionWrongId()
{
/** @var $user \Magento\User\Model\User */
$user = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\User\Model\User::class
)->loadByUsername(
'dummy_username'
);
$userId = $user->getId();
$this->assertNotEmpty($userId, 'Broken fixture');
$user->delete();
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue('user_id', $userId);
$this->dispatch('backend/admin/user/save');
$this->assertSessionMessages(
$this->equalTo(['This user no longer exists.']),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
$this->assertRedirect($this->stringContains('backend/admin/user/index/'));
}
/**
* Verify that users cannot be saved if the admin password is not correct
*
* @magentoDbIsolation enabled
*/
public function testSaveActionMissingCurrentAdminPassword()
{
$fixture = uniqid();
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
[
'username' => $fixture,
'email' => "{$fixture}@example.com",
'firstname' => 'First',
'lastname' => 'Last',
'password' => 'password_with_1_number',
'password_confirmation' => 'password_with_1_number',
]
);
$this->dispatch('backend/admin/user/save');
$this->assertSessionMessages(
$this->equalTo(
['The password entered for the current user is invalid. Verify the password and try again.']
)
);
$this->assertRedirect($this->stringContains('backend/admin/user/edit'));
}
/**
* Verify that users can be successfully saved when data is correct
*
* @magentoDbIsolation enabled
*/
public function testSaveAction()
{
$fixture = uniqid();
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
[
'username' => $fixture,
'email' => "{$fixture}@example.com",
'firstname' => 'First',
'lastname' => 'Last',
'password' => 'password_with_1_number',
'password_confirmation' => 'password_with_1_number',
\Magento\User\Block\User\Edit\Tab\Main::CURRENT_USER_PASSWORD_FIELD => Bootstrap::ADMIN_PASSWORD,
]
);
$this->dispatch('backend/admin/user/save');
$this->assertSessionMessages(
$this->equalTo(['You saved the user.']),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains('backend/admin/user/index/'));
}
/**
* Verify that users with the same username or email as an existing user cannot be created
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/User/_files/user_with_role.php
*/
public function testSaveActionDuplicateUser()
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
[
'username' => 'adminUser',
'email' => 'adminUser@example.com',
'firstname' => 'John',
'lastname' => 'Doe',
'password' => \Magento\TestFramework\Bootstrap::ADMIN_PASSWORD,
'password_confirmation' => \Magento\TestFramework\Bootstrap::ADMIN_PASSWORD,
\Magento\User\Block\User\Edit\Tab\Main::CURRENT_USER_PASSWORD_FIELD => Bootstrap::ADMIN_PASSWORD,
]
);
$this->dispatch('backend/admin/user/save/active_tab/main_section');
$this->assertSessionMessages(
$this->equalTo(['A user with the same user name or email already exists.']),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
$this->assertRedirect($this->stringContains('backend/admin/user/edit/'));
$this->assertRedirect($this->matchesRegularExpression('/^((?!active_tab).)*$/'));
}
/**
* Verify password change properly updates fields when the request is valid.
*
* @param array $postData
* @param bool $isPasswordCorrect
*
* @magentoDbIsolation enabled
* @dataProvider saveActionPasswordChangeDataProvider
*/
public function testSaveActionPasswordChange($postData, $isPasswordCorrect)
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/admin/user/save');
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $user \Magento\User\Model\User */
$user = $objectManager->create(\Magento\User\Model\User::class);
$user->loadByUsername($postData['username']);
if ($isPasswordCorrect) {
$this->assertRedirect($this->stringContains('backend/admin/user/index'));
$this->assertEquals($postData['username'], $user->getUsername());
$this->assertEquals($postData['email'], $user->getEmail());
$this->assertEquals($postData['firstname'], $user->getFirstname());
$this->assertEquals($postData['lastname'], $user->getLastname());
$encryptor = $objectManager->get(\Magento\Framework\Encryption\EncryptorInterface::class);
$this->assertTrue($encryptor->validateHash($postData['password'], $user->getPassword()));
} else {
$this->assertRedirect($this->stringContains('backend/admin/user/edit'));
$this->assertEmpty($user->getData());
}
}
/**
* Dataprovider for testSaveActionPasswordChange
*
* @return array
*/
public function saveActionPasswordChangeDataProvider()
{
$password = uniqid('123q');
$passwordPairs = [
['password' => $password, 'password_confirmation' => $password, 'is_correct' => true],
['password' => $password, 'password_confirmation' => '', 'is_correct' => false],
['password' => $password, 'password_confirmation' => $password . '123', 'is_correct' => false],
['password' => '', 'password_confirmation' => '', 'is_correct' => false],
['password' => '', 'password_confirmation' => $password, 'is_correct' => false],
];
$data = [];
foreach ($passwordPairs as $passwordPair) {
$fixture = uniqid();
$postData = [
'username' => $fixture,
'email' => "{$fixture}@example.com",
'firstname' => 'First',
'lastname' => 'Last',
'password' => $passwordPair['password'],
'password_confirmation' => $passwordPair['password_confirmation'],
\Magento\User\Block\User\Edit\Tab\Main::CURRENT_USER_PASSWORD_FIELD => Bootstrap::ADMIN_PASSWORD,
];
$data[] = [$postData, $passwordPair['is_correct']];
}
return $data;
}
/**
* Verify that the role grid is present when requested
*/
public function testRoleGridAction()
{
$this->getRequest()->setParam('ajax', true)->setParam('isAjax', true);
$this->dispatch('backend/admin/user/roleGrid');
$expected = '%a<table %a id="permissionsUserGrid_table">%a';
$this->assertStringMatchesFormat($expected, $this->getResponse()->getBody());
}
/**
* Verify that the roles grid is present when requested
*
* @depends testSaveAction
*/
public function testRolesGridAction()
{
$this->getRequest()->setParam('ajax', true)->setParam('isAjax', true)->setParam('user_id', 1);
$this->dispatch('backend/admin/user/rolesGrid');
$expected = '%a<table %a id="permissionsUserRolesGrid_table">%a';
$this->assertStringMatchesFormat($expected, $this->getResponse()->getBody());
}
/**
* Verify that expected header and fieldsets are present for edit
*
* @depends testSaveAction
*/
public function testEditAction()
{
$this->getRequest()->setParam('user_id', 1);
$this->dispatch('backend/admin/user/edit');
$response = $this->getResponse()->getBody();
//check "User Information" header and fieldset
$this->assertStringContainsString('data-ui-id="adminhtml-user-edit-tabs-title"', $response);
$this->assertStringContainsString('User Information', $response);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//*[@id="user_base_fieldset"]',
$response
)
);
}
/**
* Verify that validation passes on correct data
*/
public function testValidateActionSuccess()
{
$data = [
'username' => 'admin2',
'firstname' => 'new firstname',
'lastname' => 'new lastname',
'email' => 'example@domain.com',
'password' => 'password123',
'password_confirmation' => 'password123',
];
$this->getRequest()->setPostValue($data);
$this->dispatch('backend/admin/user/validate');
$body = $this->getResponse()->getBody();
$this->assertEquals('{"error":0}', $body);
}
/**
* Verify that an unknown top level domain on an email address does not fail validation
*/
public function testValidateActionUnknownTldSuccess()
{
$data = [
'username' => 'admin2',
'firstname' => 'new firstname',
'lastname' => 'new lastname',
'email' => 'example@domain.unknown',
'password' => 'password123',
'password_confirmation' => 'password123',
];
$this->getRequest()->setPostValue($data);
$this->dispatch('backend/admin/user/validate');
$body = $this->getResponse()->getBody();
$this->assertEquals('{"error":0}', $body);
}
/**
* Verify that an invalid email address format fails the validation
*/
public function testValidateActionError()
{
$data = [
'username' => 'admin2',
'firstname' => 'new firstname',
'lastname' => 'new lastname',
'email' => 'example@-domain.cim',
'password' => 'password123',
'password_confirmation' => 'password123',
];
/**
* set customer data
*/
$this->getRequest()->setPostValue($data);
$this->dispatch('backend/admin/user/validate');
$body = $this->getResponse()->getBody();
$this->assertStringContainsString('{"error":1,"html_message":', $body);
$this->assertStringContainsString(
"'-domain.cim' is not a valid hostname for email address 'example@-domain.cim",
$body
);
}
}