Skip to content

Commit a45dabe

Browse files
MAGETWO-82460: Fix AcountManagementTest unit test fail randomly #11605
2 parents f895075 + 194e854 commit a45dabe

File tree

2 files changed

+98
-41
lines changed

2 files changed

+98
-41
lines changed

app/code/Magento/Customer/Model/AccountManagement.php

Lines changed: 42 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,17 @@
1212
use Magento\Customer\Api\Data\AddressInterface;
1313
use Magento\Customer\Api\Data\CustomerInterface;
1414
use Magento\Customer\Api\Data\ValidationResultsInterfaceFactory;
15-
use Magento\Customer\Model\EmailNotificationInterface;
1615
use Magento\Customer\Helper\View as CustomerViewHelper;
1716
use Magento\Customer\Model\Config\Share as ConfigShare;
1817
use Magento\Customer\Model\Customer as CustomerModel;
18+
use Magento\Customer\Model\Customer\CredentialsValidator;
1919
use Magento\Customer\Model\Metadata\Validator;
2020
use Magento\Eav\Model\Validator\Attribute\Backend;
2121
use Magento\Framework\Api\ExtensibleDataObjectConverter;
2222
use Magento\Framework\App\Area;
2323
use Magento\Framework\App\Config\ScopeConfigInterface;
2424
use Magento\Framework\App\ObjectManager;
25+
use Magento\Framework\DataObjectFactory as ObjectFactory;
2526
use Magento\Framework\Encryption\EncryptorInterface as Encryptor;
2627
use Magento\Framework\Encryption\Helper\Security;
2728
use Magento\Framework\Event\ManagerInterface;
@@ -30,23 +31,22 @@
3031
use Magento\Framework\Exception\InputException;
3132
use Magento\Framework\Exception\InvalidEmailOrPasswordException;
3233
use Magento\Framework\Exception\LocalizedException;
34+
use Magento\Framework\Exception\MailException;
3335
use Magento\Framework\Exception\NoSuchEntityException;
3436
use Magento\Framework\Exception\State\ExpiredException;
3537
use Magento\Framework\Exception\State\InputMismatchException;
3638
use Magento\Framework\Exception\State\InvalidTransitionException;
37-
use Magento\Framework\DataObjectFactory as ObjectFactory;
3839
use Magento\Framework\Exception\State\UserLockedException;
39-
use Magento\Framework\Registry;
40-
use Magento\Store\Model\ScopeInterface;
41-
use Psr\Log\LoggerInterface as PsrLogger;
42-
use Magento\Framework\Exception\MailException;
40+
use Magento\Framework\Intl\DateTimeFactory;
4341
use Magento\Framework\Mail\Template\TransportBuilder;
4442
use Magento\Framework\Math\Random;
4543
use Magento\Framework\Reflection\DataObjectProcessor;
44+
use Magento\Framework\Registry;
4645
use Magento\Framework\Stdlib\DateTime;
4746
use Magento\Framework\Stdlib\StringUtils as StringHelper;
47+
use Magento\Store\Model\ScopeInterface;
4848
use Magento\Store\Model\StoreManagerInterface;
49-
use Magento\Customer\Model\Customer\CredentialsValidator;
49+
use Psr\Log\LoggerInterface as PsrLogger;
5050

5151
/**
5252
* Handle various customer account actions
@@ -293,6 +293,11 @@ class AccountManagement implements AccountManagementInterface
293293
*/
294294
private $credentialsValidator;
295295

296+
/**
297+
* @var DateTimeFactory
298+
*/
299+
private $dateTimeFactory;
300+
296301
/**
297302
* @param CustomerFactory $customerFactory
298303
* @param ManagerInterface $eventManager
@@ -318,6 +323,7 @@ class AccountManagement implements AccountManagementInterface
318323
* @param ObjectFactory $objectFactory
319324
* @param ExtensibleDataObjectConverter $extensibleDataObjectConverter
320325
* @param CredentialsValidator|null $credentialsValidator
326+
* @param DateTimeFactory $dateTimeFactory
321327
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
322328
*/
323329
public function __construct(
@@ -344,7 +350,8 @@ public function __construct(
344350
CustomerModel $customerModel,
345351
ObjectFactory $objectFactory,
346352
ExtensibleDataObjectConverter $extensibleDataObjectConverter,
347-
CredentialsValidator $credentialsValidator = null
353+
CredentialsValidator $credentialsValidator = null,
354+
DateTimeFactory $dateTimeFactory = null
348355
) {
349356
$this->customerFactory = $customerFactory;
350357
$this->eventManager = $eventManager;
@@ -369,8 +376,9 @@ public function __construct(
369376
$this->customerModel = $customerModel;
370377
$this->objectFactory = $objectFactory;
371378
$this->extensibleDataObjectConverter = $extensibleDataObjectConverter;
372-
$this->credentialsValidator = $credentialsValidator ?: ObjectManager::getInstance()
373-
->get(CredentialsValidator::class);
379+
$this->credentialsValidator =
380+
$credentialsValidator ?: ObjectManager::getInstance()->get(CredentialsValidator::class);
381+
$this->dateTimeFactory = $dateTimeFactory ?: ObjectManager::getInstance()->get(DateTimeFactory::class);
374382
}
375383

376384
/**
@@ -380,7 +388,6 @@ public function __construct(
380388
*/
381389
private function getAuthentication()
382390
{
383-
384391
if (!($this->authentication instanceof AuthenticationInterface)) {
385392
return \Magento\Framework\App\ObjectManager::getInstance()->get(
386393
\Magento\Customer\Model\AuthenticationInterface::class
@@ -613,16 +620,16 @@ protected function makeRequiredCharactersCheck($password)
613620
$return = 0;
614621

615622
if (preg_match('/[0-9]+/', $password)) {
616-
$counter ++;
623+
$counter++;
617624
}
618625
if (preg_match('/[A-Z]+/', $password)) {
619-
$counter ++;
626+
$counter++;
620627
}
621628
if (preg_match('/[a-z]+/', $password)) {
622-
$counter ++;
629+
$counter++;
623630
}
624631
if (preg_match('/[^a-zA-Z0-9]+/', $password)) {
625-
$counter ++;
632+
$counter++;
626633
}
627634

628635
if ($counter < $requiredNumber) {
@@ -890,16 +897,14 @@ public function validate(CustomerInterface $customer)
890897

891898
$result = $this->getEavValidator()->isValid($customerModel);
892899
if ($result === false && is_array($this->getEavValidator()->getMessages())) {
893-
return $validationResults->setIsValid(false)
894-
->setMessages(
895-
call_user_func_array(
896-
'array_merge',
897-
$this->getEavValidator()->getMessages()
898-
)
899-
);
900+
return $validationResults->setIsValid(false)->setMessages(
901+
call_user_func_array(
902+
'array_merge',
903+
$this->getEavValidator()->getMessages()
904+
)
905+
);
900906
}
901-
return $validationResults->setIsValid(true)
902-
->setMessages([]);
907+
return $validationResults->setIsValid(true)->setMessages([]);
903908
}
904909

905910
/**
@@ -949,10 +954,12 @@ public function isCustomerInStore($customerWebsiteId, $storeId)
949954
private function validateResetPasswordToken($customerId, $resetPasswordLinkToken)
950955
{
951956
if (empty($customerId) || $customerId < 0) {
952-
throw new InputException(__(
953-
'Invalid value of "%value" provided for the %fieldName field.',
954-
['value' => $customerId, 'fieldName' => 'customerId']
955-
));
957+
throw new InputException(
958+
__(
959+
'Invalid value of "%value" provided for the %fieldName field.',
960+
['value' => $customerId, 'fieldName' => 'customerId']
961+
)
962+
);
956963
}
957964
if (!is_string($resetPasswordLinkToken) || empty($resetPasswordLinkToken)) {
958965
$params = ['fieldName' => 'resetPasswordLinkToken'];
@@ -1178,8 +1185,8 @@ public function isResetPasswordLinkTokenExpired($rpToken, $rpTokenCreatedAt)
11781185

11791186
$expirationPeriod = $this->customerModel->getResetPasswordLinkExpirationPeriod();
11801187

1181-
$currentTimestamp = (new \DateTime())->getTimestamp();
1182-
$tokenTimestamp = (new \DateTime($rpTokenCreatedAt))->getTimestamp();
1188+
$currentTimestamp = $this->dateTimeFactory->create()->getTimestamp();
1189+
$tokenTimestamp = $this->dateTimeFactory->create($rpTokenCreatedAt)->getTimestamp();
11831190
if ($tokenTimestamp > $currentTimestamp) {
11841191
return true;
11851192
}
@@ -1215,7 +1222,9 @@ public function changeResetPasswordLinkToken($customer, $passwordLinkToken)
12151222
if (is_string($passwordLinkToken) && !empty($passwordLinkToken)) {
12161223
$customerSecure = $this->customerRegistry->retrieveSecureData($customer->getId());
12171224
$customerSecure->setRpToken($passwordLinkToken);
1218-
$customerSecure->setRpTokenCreatedAt((new \DateTime())->format(DateTime::DATETIME_PHP_FORMAT));
1225+
$customerSecure->setRpTokenCreatedAt(
1226+
$this->dateTimeFactory->create()->format(DateTime::DATETIME_PHP_FORMAT)
1227+
);
12191228
$this->customerRepository->save($customer);
12201229
}
12211230
return true;
@@ -1304,8 +1313,8 @@ protected function getFullCustomerObject($customer)
13041313
// No need to flatten the custom attributes or nested objects since the only usage is for email templates and
13051314
// object passed for events
13061315
$mergedCustomerData = $this->customerRegistry->retrieveSecureData($customer->getId());
1307-
$customerData = $this->dataProcessor
1308-
->buildOutputDataArray($customer, \Magento\Customer\Api\Data\CustomerInterface::class);
1316+
$customerData =
1317+
$this->dataProcessor->buildOutputDataArray($customer, \Magento\Customer\Api\Data\CustomerInterface::class);
13091318
$mergedCustomerData->addData($customerData);
13101319
$mergedCustomerData->setData('name', $this->customerViewHelper->getCustomerName($customer));
13111320
return $mergedCustomerData;

app/code/Magento/Customer/Test/Unit/Model/AccountManagementTest.php

Lines changed: 56 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
use Magento\Customer\Model\EmailNotificationInterface;
1111
use Magento\Framework\App\Area;
1212
use Magento\Framework\Exception\NoSuchEntityException;
13+
use Magento\Framework\Intl\DateTimeFactory;
1314
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper;
1415
use Magento\Store\Model\ScopeInterface;
1516

@@ -114,6 +115,11 @@ class AccountManagementTest extends \PHPUnit\Framework\TestCase
114115
*/
115116
protected $emailNotificationMock;
116117

118+
/**
119+
* @var DateTimeFactory|\PHPUnit_Framework_MockObject_MockObject
120+
*/
121+
private $dateTimeFactory;
122+
117123
/**
118124
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
119125
*/
@@ -163,6 +169,8 @@ protected function setUp()
163169
->disableOriginalConstructor()
164170
->getMock();
165171

172+
$this->dateTimeFactory = $this->createMock(DateTimeFactory::class);
173+
166174
$this->objectManagerHelper = new ObjectManagerHelper($this);
167175
$this->accountManagement = $this->objectManagerHelper->getObject(
168176
\Magento\Customer\Model\AccountManagement::class,
@@ -190,6 +198,7 @@ protected function setUp()
190198
'customerModel' => $this->customer,
191199
'objectFactory' => $this->objectFactory,
192200
'extensibleDataObjectConverter' => $this->extensibleDataObjectConverter,
201+
'dateTimeFactory' => $this->dateTimeFactory,
193202
]
194203
);
195204
$reflection = new \ReflectionClass(get_class($this->accountManagement));
@@ -552,6 +561,8 @@ public function testCreateAccountWithoutPassword()
552561
$customerEmail = '[email protected]';
553562
$newLinkToken = '2jh43j5h2345jh23lh452h345hfuzasd96ofu';
554563

564+
$datetime = $this->prepareDateTimeFactory();
565+
555566
$address = $this->getMockBuilder(\Magento\Customer\Api\Data\AddressInterface::class)
556567
->disableOriginalConstructor()
557568
->getMock();
@@ -624,7 +635,9 @@ public function testCreateAccountWithoutPassword()
624635
->method('setRpToken')
625636
->with($newLinkToken);
626637
$customerSecure->expects($this->any())
627-
->method('setRpTokenCreatedAt');
638+
->method('setRpTokenCreatedAt')
639+
->with($datetime)
640+
->willReturnSelf();
628641
$customerSecure->expects($this->any())
629642
->method('getPasswordHash')
630643
->willReturn(null);
@@ -756,6 +769,8 @@ public function testCreateAccountWithPassword()
756769
$minPasswordLength = 5;
757770
$minCharacterSetsNum = 2;
758771

772+
$datetime = $this->prepareDateTimeFactory();
773+
759774
$this->scopeConfig->expects($this->any())
760775
->method('getValue')
761776
->willReturnMap(
@@ -865,7 +880,9 @@ public function testCreateAccountWithPassword()
865880
->method('setRpToken')
866881
->with($newLinkToken);
867882
$customerSecure->expects($this->any())
868-
->method('setRpTokenCreatedAt');
883+
->method('setRpTokenCreatedAt')
884+
->with($datetime)
885+
->willReturnSelf();
869886
$customerSecure->expects($this->any())
870887
->method('getPasswordHash')
871888
->willReturn($hash);
@@ -995,7 +1012,7 @@ protected function prepareInitiatePasswordReset($email, $templateIdentifier, $se
9951012
{
9961013
$websiteId = 1;
9971014

998-
$dateTime = date(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT);
1015+
$datetime = $this->prepareDateTimeFactory();
9991016

10001017
$customerData = ['key' => 'value'];
10011018
$customerName = 'Customer Name';
@@ -1047,7 +1064,7 @@ protected function prepareInitiatePasswordReset($email, $templateIdentifier, $se
10471064
->willReturnSelf();
10481065
$this->customerSecure->expects($this->any())
10491066
->method('setRpTokenCreatedAt')
1050-
->with($dateTime)
1067+
->with($datetime)
10511068
->willReturnSelf();
10521069
$this->customerSecure->expects($this->any())
10531070
->method('addData')
@@ -1257,18 +1274,20 @@ private function reInitModel()
12571274
->method('getRpToken')
12581275
->willReturn('newStringToken');
12591276

1260-
$date = date('Y-m-d', strtotime('-1 year'));
1277+
$pastDateTime = '2016-10-25 00:00:00';
12611278

12621279
$this->customerSecure
12631280
->expects($this->any())
12641281
->method('getRpTokenCreatedAt')
1265-
->willReturn($date);
1282+
->willReturn($pastDateTime);
12661283

12671284
$this->customer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class)
12681285
->disableOriginalConstructor()
12691286
->setMethods(['getResetPasswordLinkExpirationPeriod'])
12701287
->getMock();
12711288

1289+
$this->prepareDateTimeFactory();
1290+
12721291
$this->objectManagerHelper = new ObjectManagerHelper($this);
12731292
$this->accountManagement = $this->objectManagerHelper->getObject(
12741293
\Magento\Customer\Model\AccountManagement::class,
@@ -1277,6 +1296,7 @@ private function reInitModel()
12771296
'customerRegistry' => $this->customerRegistry,
12781297
'customerRepository' => $this->customerRepository,
12791298
'customerModel' => $this->customer,
1299+
'dateTimeFactory' => $this->dateTimeFactory,
12801300
]
12811301
);
12821302
$reflection = new \ReflectionClass(get_class($this->accountManagement));
@@ -1320,7 +1340,7 @@ public function testChangePassword()
13201340
->with(null);
13211341
$customerSecure->expects($this->once())
13221342
->method('setRpTokenCreatedAt')
1323-
->with(null);
1343+
->willReturnSelf();
13241344
$customerSecure->expects($this->any())
13251345
->method('getPasswordHash')
13261346
->willReturn($passwordHash);
@@ -1586,6 +1606,8 @@ public function testCreateAccountWithPasswordHashWithCustomerAddresses()
15861606
$storeId = 1;
15871607
$hash = '4nj54lkj5jfi03j49f8bgujfgsd';
15881608

1609+
$this->prepareDateTimeFactory();
1610+
15891611
//Handle store
15901612
$store = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock();
15911613
$store->expects($this->any())
@@ -1630,7 +1652,7 @@ public function testCreateAccountWithPasswordHashWithCustomerAddresses()
16301652
->expects($this->any())
16311653
->method("getId")
16321654
->willReturn($customerId);
1633-
//Return Customer from customer repositoryå
1655+
//Return Customer from customer repository
16341656
$this->customerRepository
16351657
->expects($this->atLeastOnce())
16361658
->method('save')
@@ -1673,4 +1695,30 @@ public function testCreateAccountWithPasswordHashWithCustomerAddresses()
16731695

16741696
$this->assertSame($customer, $this->accountManagement->createAccountWithPasswordHash($customer, $hash));
16751697
}
1698+
1699+
/**
1700+
* @return string
1701+
*/
1702+
private function prepareDateTimeFactory()
1703+
{
1704+
$dateTime = '2017-10-25 18:57:08';
1705+
$timestamp = '1508983028';
1706+
$dateTimeMock = $this->createMock(\DateTime::class);
1707+
$dateTimeMock->expects($this->any())
1708+
->method('format')
1709+
->with(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT)
1710+
->willReturn($dateTime);
1711+
1712+
$dateTimeMock
1713+
->expects($this->any())
1714+
->method('getTimestamp')
1715+
->willReturn($timestamp);
1716+
1717+
$this->dateTimeFactory
1718+
->expects($this->any())
1719+
->method('create')
1720+
->willReturn($dateTimeMock);
1721+
1722+
return $dateTime;
1723+
}
16761724
}

0 commit comments

Comments
 (0)