This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,32 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Tests for customer addresses collection
*/
namespace Magento\Customer\Model\ResourceModel\Address;
class CollectionTest extends \PHPUnit\Framework\TestCase
{
public function testSetCustomerFilter()
{
$collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Customer\Model\ResourceModel\Address\Collection::class
);
$select = $collection->getSelect();
$this->assertSame($collection, $collection->setCustomerFilter([1, 2]));
$customer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Customer\Model\Customer::class
);
$collection->setCustomerFilter($customer);
$customer->setId(3);
$collection->setCustomerFilter($customer);
$this->assertStringMatchesFormat(
'%AWHERE%S(%Sparent_id%S IN(%S1%S, %S2%S))%SAND%S(%Sparent_id%S = %S-1%S)%SAND%S(%Sparent_id%S = %S3%S)%A',
(string)$select
);
}
}
@@ -0,0 +1,708 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Model\ResourceModel;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Api\Data\AddressInterfaceFactory;
use Magento\Customer\Api\Data\RegionInterfaceFactory;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\Filter;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Api\SortOrder;
use Magento\Framework\Api\SortOrderBuilder;
use Magento\Framework\Config\CacheInterface;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Class with integration tests for AddressRepository.
*
* @SuppressWarnings(PHPMD.TooManyMethods)
* @SuppressWarnings(PHPMD.ExcessivePublicCount)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AddressRepositoryTest extends TestCase
{
/** @var AddressRepositoryInterface */
private $repository;
/** @var \Magento\Framework\ObjectManagerInterface */
private $objectManager;
/** @var \Magento\Customer\Model\Data\Address[] */
private $expectedAddresses;
/** @var AddressInterfaceFactory */
private $addressFactory;
/** @var DataObjectHelper */
private $dataObjectHelper;
/** @var CustomerRegistry */
private $customerRegistry;
/** @var StoreManagerInterface */
private $storeManager;
/** @var RegionInterfaceFactory */
private $regionFactory;
/** @var CustomerRepositoryInterface */
private $customerRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
/* @var CacheInterface $cache */
$cache = $this->objectManager->get(CacheInterface::class);
$cache->remove('extension_attributes_config');
$this->repository = $this->objectManager->get(AddressRepositoryInterface::class);
$this->addressFactory = $this->objectManager->get(AddressInterfaceFactory::class);
$this->dataObjectHelper = $this->objectManager->get(DataObjectHelper::class);
$this->customerRegistry = $this->objectManager->get(CustomerRegistry::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
$this->regionFactory = $this->objectManager->get(RegionInterfaceFactory::class);
$this->customerRepository = $this->objectManager->get(CustomerRepositoryInterface::class);
$region = $this->regionFactory->create()
->setRegionCode('AL')
->setRegion('Alabama')
->setRegionId(1);
$address = $this->addressFactory->create()
->setId('1')
->setCountryId('US')
->setCustomerId('1')
->setPostcode('75477')
->setRegion($region)
->setRegionId(1)
->setStreet(['Green str, 67'])
->setTelephone('3468676')
->setCity('CityM')
->setFirstname('John')
->setLastname('Smith')
->setCompany('CompanyName');
$address2 = $this->addressFactory->create()
->setId('2')
->setCountryId('US')
->setCustomerId('1')
->setPostcode('47676')
->setRegion($region)
->setRegionId(1)
->setStreet(['Black str, 48'])
->setCity('CityX')
->setTelephone('3234676')
->setFirstname('John')
->setLastname('Smith');
$this->expectedAddresses = [$address, $address2];
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->customerRegistry->remove(1);
}
/**
* Test for save address changes.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
* @magentoAppIsolation enabled
* @return void
*/
public function testSaveAddressChanges(): void
{
$address = $this->repository->getById(2);
$proposedAddressObject = $address;
$proposedAddressObject->setRegion($address->getRegion());
// change phone #
$proposedAddressObject->setTelephone('555' . $address->getTelephone());
$proposedAddress = $this->repository->save($proposedAddressObject);
$this->assertEquals(2, $proposedAddress->getId());
$savedAddress = $this->repository->getById(2);
$this->assertNotEquals($this->expectedAddresses[1]->getTelephone(), $savedAddress->getTelephone());
}
/**
* Test for method save address with new id.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
* @magentoAppIsolation enabled
* @return void
*/
public function testSaveAddressesIdSetButNotAlreadyExisting(): void
{
$message = (string)__(
'No such entity with %fieldName = %fieldValue',
[
'fieldName' => 'addressId',
'fieldValue' => 4200,
]
);
$this->expectException(NoSuchEntityException::class);
$this->expectExceptionMessage($message);
$proposedAddress = $this->_createSecondAddress()->setId(4200);
$this->repository->save($proposedAddress);
}
/**
* Test for method get address by id.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
* @magentoAppIsolation enabled
* @return void
*/
public function testGetAddressById(): void
{
$addressId = 2;
$address = $this->repository->getById($addressId);
$this->assertEquals($this->expectedAddresses[1], $address);
}
/**
* Test for method get address by id with incorrect id.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @return void
*/
public function testGetAddressByIdBadAddressId(): void
{
$message = (string)__(
'No such entity with %fieldName = %fieldValue',
[
'fieldName' => 'addressId',
'fieldValue' => 12345,
]
);
$this->expectException(NoSuchEntityException::class);
$this->expectExceptionMessage($message);
$this->repository->getById(12345);
}
/**
* Test for method save new address.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoAppIsolation enabled
* @return void
*/
public function testSaveNewAddress(): void
{
$proposedAddress = $this->_createSecondAddress()->setCustomerId(1);
$returnedAddress = $this->repository->save($proposedAddress);
$this->assertNotNull($returnedAddress->getId());
$savedAddress = $this->repository->getById($returnedAddress->getId());
$expectedNewAddress = $this->expectedAddresses[1];
$expectedNewAddress->setId($savedAddress->getId());
$expectedNewAddress->setRegion($this->expectedAddresses[1]->getRegion());
$this->assertEquals($expectedNewAddress->getExtensionAttributes(), $savedAddress->getExtensionAttributes());
$this->assertEquals(
$expectedNewAddress->getRegion()->getExtensionAttributes(),
$savedAddress->getRegion()->getExtensionAttributes()
);
$this->assertEquals($expectedNewAddress, $savedAddress);
}
/**
* Test for method saaveNewAddress with new attributes.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoAppIsolation enabled
* @return void
*/
public function testSaveNewAddressWithAttributes(): void
{
$proposedAddress = $this->_createFirstAddress()
->setCustomAttribute('firstname', 'Jane')
->setCustomAttribute('id', 4200)
->setCustomAttribute('weird', 'something_strange_with_hair')
->setId(null)
->setCustomerId(1);
$returnedAddress = $this->repository->save($proposedAddress);
$savedAddress = $this->repository->getById($returnedAddress->getId());
$this->assertNotEquals($proposedAddress, $savedAddress);
$this->assertArrayNotHasKey(
'weird',
$savedAddress->getCustomAttributes(),
'Only valid attributes should be available.'
);
}
/**
* Test for saving address with invalid address.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoAppIsolation enabled
* @return void
*/
public function testSaveNewInvalidAddress(): void
{
$address = $this->_createFirstAddress()
->setCustomAttribute('firstname', null)
->setId(null)
->setFirstname(null)
->setLastname(null)
->setCustomerId(1);
try {
$this->repository->save($address);
} catch (InputException $exception) {
$this->assertEquals('One or more input exceptions have occurred.', $exception->getMessage());
$errors = $exception->getErrors();
$this->assertCount(2, $errors);
$this->assertEquals('"firstname" is required. Enter and try again.', $errors[0]->getLogMessage());
$this->assertEquals('"lastname" is required. Enter and try again.', $errors[1]->getLogMessage());
}
}
/**
* Test for saving address without existing customer.
*
* @return void
*/
public function testSaveAddressesCustomerIdNotExist(): void
{
$message = (string)__(
'No such entity with %fieldName = %fieldValue',
[
'fieldName' => 'customerId',
'fieldValue' => 4200,
]
);
$this->expectException(NoSuchEntityException::class);
$this->expectExceptionMessage($message);
$proposedAddress = $this->_createSecondAddress()->setCustomerId(4200);
$this->repository->save($proposedAddress);
}
/**
* Test for saving addresses with invalid customer id.
*
* @return void
*/
public function testSaveAddressesCustomerIdInvalid(): void
{
$message = (string)__(
'No such entity with %fieldName = %fieldValue',
[
'fieldName' => 'customerId',
'fieldValue' => 'this_is_not_a_valid_id',
]
);
$this->expectException(NoSuchEntityException::class);
$this->expectExceptionMessage($message);
$proposedAddress = $this->_createSecondAddress()->setCustomerId('this_is_not_a_valid_id');
$this->repository->save($proposedAddress);
}
/**
* Test for delete method.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @return void
*/
public function testDeleteAddress(): void
{
$addressId = 1;
// See that customer already has an address with expected addressId
$addressDataObject = $this->repository->getById($addressId);
$this->assertEquals($addressDataObject->getId(), $addressId);
// Delete the address from the customer
$this->repository->delete($addressDataObject);
$message = (string)__(
'No such entity with %fieldName = %fieldValue',
[
'fieldName' => 'addressId',
'fieldValue' => 1,
]
);
$this->expectException(NoSuchEntityException::class);
$this->expectExceptionMessage($message);
$this->repository->getById($addressId);
}
/**
* Test for deleteAddressById.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @return void
*/
public function testDeleteAddressById(): void
{
$addressId = 1;
// See that customer already has an address with expected addressId
$addressDataObject = $this->repository->getById($addressId);
$this->assertEquals($addressDataObject->getId(), $addressId);
// Delete the address from the customer
$this->repository->deleteById($addressId);
$message = (string)__(
'No such entity with %fieldName = %fieldValue',
[
'fieldName' => 'addressId',
'fieldValue' => 1,
]
);
$this->expectException(NoSuchEntityException::class);
$this->expectExceptionMessage($message);
$this->repository->getById($addressId);
}
/**
* Test delete address from customer with incorrect address id.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @return void
*/
public function testDeleteAddressFromCustomerBadAddressId(): void
{
$message = (string)__(
'No such entity with %fieldName = %fieldValue',
[
'fieldName' => 'addressId',
'fieldValue' => 12345,
]
);
$this->expectException(NoSuchEntityException::class);
$this->expectExceptionMessage($message);
$this->repository->deleteById(12345);
}
/**
* Test for searching addressed.
*
* @param Filter[] $filters
* @param Filter[] $filterGroup
* @param SortOrder[] $filterOrders
* @param array $expectedResult array of expected results indexed by ID
* @param int $currentPage current page for search criteria
*
* @return void
* @dataProvider searchAddressDataProvider
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
* @magentoAppIsolation enabled
*/
public function testSearchAddresses(
$filters,
$filterGroup,
$filterOrders,
array $expectedResult,
int $currentPage
): void {
/** @var SearchCriteriaBuilder $searchBuilder */
$searchBuilder = $this->objectManager->create(SearchCriteriaBuilder::class);
foreach ($filters as $filter) {
$searchBuilder->addFilters([$filter]);
}
if ($filterGroup !== null) {
$searchBuilder->addFilters($filterGroup);
}
if ($filterOrders !== null) {
foreach ($filterOrders as $order) {
$searchBuilder->addSortOrder($order);
}
}
$searchBuilder->setPageSize(1);
$searchBuilder->setCurrentPage($currentPage);
$searchCriteria = $searchBuilder->create();
$searchResults = $this->repository->getList($searchCriteria);
$items = array_values($searchResults->getItems());
$this->assertEquals(count($expectedResult), $searchResults->getTotalCount());
$this->assertCount(1, $items);
$expectedResultIndex = count($expectedResult) - 1;
$this->assertEquals($expectedResult[$expectedResultIndex]['id'], $items[0]->getId());
$this->assertEquals($expectedResult[$expectedResultIndex]['city'], $items[0]->getCity());
$this->assertEquals($expectedResult[$expectedResultIndex]['postcode'], $items[0]->getPostcode());
$this->assertEquals($expectedResult[$expectedResultIndex]['firstname'], $items[0]->getFirstname());
}
/**
* Data provider for searchAddresses.
*
* @return array
*/
public function searchAddressDataProvider(): array
{
/**
* @var FilterBuilder $filterBuilder
*/
$filterBuilder = Bootstrap::getObjectManager()
->create(FilterBuilder::class);
/**
* @var SortOrderBuilder $orderBuilder
*/
$orderBuilder = Bootstrap::getObjectManager()
->create(SortOrderBuilder::class);
return [
'Address with postcode 75477' => [
[$filterBuilder->setField('postcode')->setValue('75477')->create()],
null,
null,
[
['id' => 1, 'city' => 'CityM', 'postcode' => 75477, 'firstname' => 'John'],
],
1
],
'Address with city CityM' => [
[$filterBuilder->setField('city')->setValue('CityM')->create()],
null,
null,
[
['id' => 1, 'city' => 'CityM', 'postcode' => 75477, 'firstname' => 'John'],
],
1
],
'Addresses with firstname John sorted by firstname desc, city asc' => [
[$filterBuilder->setField('firstname')->setValue('John')->create()],
null,
[
$orderBuilder->setField('firstname')->setDirection(SortOrder::SORT_DESC)->create(),
$orderBuilder->setField('city')->setDirection(SortOrder::SORT_ASC)->create(),
],
[
['id' => 1, 'city' => 'CityM', 'postcode' => 75477, 'firstname' => 'John'],
['id' => 2, 'city' => 'CityX', 'postcode' => 47676, 'firstname' => 'John'],
],
2
],
'Addresses with postcode of either 75477 or 47676 sorted by city desc' => [
[],
[
$filterBuilder->setField('postcode')->setValue('75477')->create(),
$filterBuilder->setField('postcode')->setValue('47676')->create(),
],
[
$orderBuilder->setField('city')->setDirection(SortOrder::SORT_DESC)->create(),
],
[
['id' => 2, 'city' => 'CityX', 'postcode' => 47676, 'firstname' => 'John'],
['id' => 1, 'city' => 'CityM', 'postcode' => 75477, 'firstname' => 'John'],
],
2
],
'Addresses with postcode greater than 0 sorted by firstname asc, postcode desc' => [
[$filterBuilder->setField('postcode')->setValue('0')->setConditionType('gt')->create()],
null,
[
$orderBuilder->setField('firstname')->setDirection(SortOrder::SORT_ASC)->create(),
$orderBuilder->setField('postcode')->setDirection(SortOrder::SORT_ASC)->create(),
],
[
['id' => 2, 'city' => 'CityX', 'postcode' => 47676, 'firstname' => 'John'],
['id' => 1, 'city' => 'CityM', 'postcode' => 75477, 'firstname' => 'John'],
],
2
],
];
}
/**
* Test for save addresses with restricted countries.
*
* @magentoDataFixture Magento/Customer/Fixtures/customer_sec_website.php
* @return void
*/
public function testSaveAddressWithRestrictedCountries(): void
{
$website = $this->storeManager->getWebsite('test');
$customer = $this->customerRepository->get('customer.web@example.com', (int)$website->getId());
$region = $this->regionFactory->create()
->setRegionCode('CA')
->setRegion('California')
->setRegionId(12);
$addressData = [
'customer_id' => $customer->getId(),
'firstname' => 'John',
'lastname' => 'Doe',
'street' => ['6161 Main Street'],
'city' => 'Culver City',
'country_id' => 'US',
'region' => $region,
'postcode' => 90230,
'telephone' => '555655431',
];
$address = $this->addressFactory->create(['data' => $addressData]);
$saved = $this->repository->save($address);
self::assertNotEmpty($saved->getId());
}
/**
* Test for saving address with extra spaces in phone.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @return void
*/
public function testSaveNewAddressWithExtraSpacesInPhone(): void
{
$proposedAddress = $this->_createSecondAddress()
->setCustomerId(1)
->setTelephone(' 123456 ');
$returnedAddress = $this->repository->save($proposedAddress);
$savedAddress = $this->repository->getById($returnedAddress->getId());
$this->assertEquals('123456', $savedAddress->getTelephone());
}
/**
* Scenario for customer's default shipping and billing address saving and rollback.
*
* @magentoDataFixture Magento/Customer/_files/customer_without_addresses.php
* @return void
*/
public function testCustomerAddressRelationSynchronisation(): void
{
/**
* Creating new address which is default shipping and billing for existing customer.
*/
$address = $this->expectedAddresses[0];
$address->setId(null);
$address->setCustomerId(1);
$address->setIsDefaultShipping(true);
$address->setIsDefaultBilling(true);
$savedAddress = $this->repository->save($address);
/**
* Customer registry should be updated with default shipping and billing addresses.
*/
$customer = $this->customerRepository->get('customer@example.com', 1);
$this->assertEquals($savedAddress->getId(), $customer->getDefaultShipping());
$this->assertEquals($savedAddress->getId(), $customer->getDefaultBilling());
/**
* Registry should be clean up for reading data from DB.
*/
$this->repository->deleteById($savedAddress->getId());
$this->customerRegistry->removeByEmail('customer@example.com');
/**
* Customer's default shipping and billing addresses should be updated.
*/
$customer = $this->customerRepository->get('customer@example.com', 1);
$this->assertNull($customer->getDefaultShipping());
$this->assertNull($customer->getDefaultBilling());
}
/**
* Update Customer Address, with Alphanumeric Zip Code
*
* @magentoDataFixture Magento/Customer/_files/customer_one_address.php
* @return void
*/
public function testUpdateWithAlphanumericZipCode(): void
{
$region = $this->regionFactory->create()
->setRegionCode('PH')
->setRegion('Pinminnoch')
->setRegionId(1);
$websiteId = (int)$this->storeManager->getWebsite('base')->getId();
$customer = $this->customerRepository->get('customer_one_address@test.com', $websiteId);
$defaultBillingAddress = $customer->getDefaultBilling();
$addressData = [
AddressInterface::FIRSTNAME => 'Doe',
AddressInterface::LASTNAME => 'Doe',
AddressInterface::MIDDLENAME => 'Middle Name',
AddressInterface::SUFFIX => '_Suffix',
AddressInterface::PREFIX => 'Prefix',
AddressInterface::COMPANY => 'Company',
AddressInterface::STREET => ['Northgate Street, 39'],
AddressInterface::CITY => 'BICKTON',
AddressInterface::COUNTRY_ID => 'GB',
AddressInterface::REGION => $region,
AddressInterface::POSTCODE => 'KA26 1PF',
AddressInterface::TELEPHONE => '999-777-111-2345',
AddressInterface::VAT_ID => '987654321',
];
$customerAddress = $this->repository->getById((int)$defaultBillingAddress);
foreach ($addressData as $key => $value) {
$customerAddress->setData($key, $value);
}
$savedAddress = $this->repository->save($customerAddress);
$customerData = $savedAddress->__toArray();
foreach ($addressData as $key => $value) {
if ($key === AddressInterface::REGION) {
$this->assertEquals($customerData[$key][AddressInterface::REGION], $value->getRegion());
} else {
$this->assertEquals($value, $customerData[$key]);
}
}
}
/**
* Helper function that returns an Address Data Object that matches the data from customer_address fixture
*
* @return AddressInterface
*/
private function _createFirstAddress(): AddressInterface
{
$address = $this->addressFactory->create();
$this->dataObjectHelper->mergeDataObjects(
AddressInterface::class,
$address,
$this->expectedAddresses[0]
);
$address->setId(null);
$address->setRegion($this->expectedAddresses[0]->getRegion());
return $address;
}
/**
* Helper function that returns an Address Data Object that matches the data from customer_two_address fixture
*
* @return AddressInterface
*/
private function _createSecondAddress(): AddressInterface
{
$address = $this->addressFactory->create();
$this->dataObjectHelper->mergeDataObjects(
AddressInterface::class,
$address,
$this->expectedAddresses[1]
);
$address->setId(null);
$address->setRegion($this->expectedAddresses[1]->getRegion());
return $address;
}
}
@@ -0,0 +1,32 @@
<?php
/**
* \Magento\Customer\Model\ResourceModel\Customer\Collection
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Model\ResourceModel\Customer;
class CollectionTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Customer\Model\ResourceModel\Customer\Collection
*/
protected $_collection;
protected function setUp(): void
{
$this->_collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Customer\Model\ResourceModel\Customer\Collection::class
);
}
public function testAddNameToSelect()
{
$this->_collection->addNameToSelect();
$joinParts = $this->_collection->getSelect()->getPart(\Magento\Framework\DB\Select::FROM);
$this->assertArrayHasKey('e', $joinParts);
$this->assertCount(1, $joinParts);
}
}
@@ -0,0 +1,69 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Model\ResourceModel\CustomerRepository;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Model\Address\CreateAddressTest as CreateAddressViaAddressRepositoryTest;
use Magento\Framework\Api\DataObjectHelper;
/**
* Test cases related to create customer address using customer repository.
*
* @magentoDbIsolation enabled
*/
class CreateAddressTest extends CreateAddressViaAddressRepositoryTest
{
/**
* @var DataObjectHelper
*/
private $dataObjectHelper;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->dataObjectHelper = $this->objectManager->get(DataObjectHelper::class);
}
/**
* Create customer address with provided address data.
*
* @param int $customerId
* @param array $addressData
* @param bool $isDefaultShipping
* @param bool $isDefaultBilling
* @return AddressInterface
*/
protected function createAddress(
int $customerId,
array $addressData,
bool $isDefaultShipping = false,
bool $isDefaultBilling = false
): AddressInterface {
if (isset($addressData['custom_region_name'])) {
$addressData[AddressInterface::REGION_ID] = $this->getRegionIdByName->execute(
$addressData['custom_region_name'],
$addressData[AddressInterface::COUNTRY_ID]
);
unset($addressData['custom_region_name']);
}
$address = $this->addressFactory->create();
$this->dataObjectHelper->populateWithArray($address, $addressData, AddressInterface::class);
$address->setIsDefaultShipping($isDefaultShipping);
$address->setIsDefaultBilling($isDefaultBilling);
$customer = $this->customerRepository->getById($customerId);
$customer->setAddresses([$address]);
$this->customerRepository->save($customer);
$addressId = (int)$address->getId();
$this->customerRegistry->remove($customerId);
return $this->addressRepository->getById($addressId);
}
}
@@ -0,0 +1,42 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Model\ResourceModel\CustomerRepository;
use Magento\Customer\Model\Address\DeleteAddressTest as DeleteAddressViaAddressRepositoryTest;
use Magento\Framework\Exception\NoSuchEntityException;
/**
* Test cases related to delete customer address using customer repository.
*
* @magentoDbIsolation enabled
*/
class DeleteAddressTest extends DeleteAddressViaAddressRepositoryTest
{
/**
* Assert that address deleted successfully.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*
* @return void
*/
public function testDeleteDefaultAddress(): void
{
$customer = $this->customerRepository->get('customer@example.com');
$this->assertEquals(1, $customer->getDefaultShipping());
$this->assertEquals(1, $customer->getDefaultBilling());
$customer->setAddresses([]);
$this->customerRepository->save($customer);
$this->customerRegistry->remove($customer->getId());
$customer = $this->customerRepository->get('customer@example.com');
$this->assertNull($customer->getDefaultShipping());
$this->assertNull($customer->getDefaultBilling());
$this->expectExceptionObject(new NoSuchEntityException(__('No such entity with addressId = 1')));
$this->addressRepository->getById(1);
}
}
@@ -0,0 +1,107 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Model\ResourceModel\CustomerRepository;
use Magento\Customer\Model\Address\UpdateAddressTest as UpdateAddressViaAddressRepositoryTest;
/**
* Test cases related to update customer address using customer repository.
*
* @magentoDbIsolation enabled
*/
class UpdateAddressTest extends UpdateAddressViaAddressRepositoryTest
{
/**
* Assert that default addresses properly updated for customer.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*
* @dataProvider updateAddressIsDefaultDataProvider
*
* @param bool $isShippingDefault
* @param bool $isBillingDefault
* @param int|null $expectedShipping
* @param int|null $expectedBilling
* @return void
*/
public function testUpdateAddressIsDefault(
bool $isShippingDefault,
bool $isBillingDefault,
?int $expectedShipping,
?int $expectedBilling
): void {
$customer = $this->customerRepository->get('customer@example.com');
$this->assertEquals(1, $customer->getDefaultShipping());
$this->assertEquals(1, $customer->getDefaultBilling());
$this->processedAddressesIds[] = 1;
$address = $this->addressRepository->getById(1);
$address->setIsDefaultShipping($isShippingDefault);
$address->setIsDefaultBilling($isBillingDefault);
$customer->setAddresses([$address]);
$this->customerRepository->save($customer);
$this->customerRegistry->remove(1);
$customer = $this->customerRepository->get('customer@example.com');
$this->assertEquals($customer->getDefaultShipping(), $expectedShipping);
$this->assertEquals($customer->getDefaultBilling(), $expectedBilling);
}
/**
* Assert that address updated successfully.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*
* @dataProvider updateAddressesDataProvider
*
* @param array $updateData
* @param array $expectedData
* @return void
*/
public function testUpdateAddress(array $updateData, array $expectedData): void
{
$this->processedAddressesIds[] = 1;
$address = $this->addressRepository->getById(1);
foreach ($updateData as $setFieldName => $setValue) {
$address->setData($setFieldName, $setValue);
}
$customer = $this->customerRepository->get('customer@example.com');
$customer->setAddresses([$address]);
$this->customerRepository->save($customer);
$updatedAddressData = $this->addressRepository->getById((int)$address->getId())->__toArray();
foreach ($expectedData as $getFieldName => $getValue) {
$this->assertTrue(isset($updatedAddressData[$getFieldName]), "Field $getFieldName wasn't found.");
$this->assertEquals($getValue, $updatedAddressData[$getFieldName]);
}
}
/**
* Assert that error message has thrown during process address update.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*
* @dataProvider updateWrongAddressesDataProvider
*
* @param array $updateData
* @param \Exception $expectException
* @return void
*/
public function testExceptionThrownDuringUpdateAddress(array $updateData, \Exception $expectException): void
{
$this->processedAddressesIds[] = 1;
$address = $this->addressRepository->getById(1);
$customer = $this->customerRepository->get('customer@example.com');
foreach ($updateData as $setFieldName => $setValue) {
$address->setData($setFieldName, $setValue);
}
$customer->setAddresses([$address]);
$this->expectExceptionObject($expectException);
$this->customerRepository->save($customer);
}
}
@@ -0,0 +1,758 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Model\ResourceModel;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Api\Data\AddressInterfaceFactory;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Customer\Model\Customer;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Customer\Test\Fixture\Customer as CustomerFixture;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\ExtensibleDataObjectConverter;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Api\SortOrder;
use Magento\Framework\Api\SortOrderBuilder;
use Magento\Framework\Config\CacheInterface;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Validator\Exception as ValidatorException;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorage;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Checks Customer insert, update, search with repository
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CustomerRepositoryTest extends \PHPUnit\Framework\TestCase
{
private const NEW_CUSTOMER_EMAIL = 'new.customer@example.com';
private const CUSTOMER_ID = 1;
/** @var AccountManagementInterface */
private $accountManagement;
/** @var CustomerRepositoryInterface */
private $customerRepository;
/** @var OrderRepositoryInterface */
private $orderRepository;
/** @var ObjectManagerInterface */
private $objectManager;
/** @var CustomerInterfaceFactory */
private $customerFactory;
/** @var AddressInterfaceFactory */
private $addressFactory;
/** @var ExtensibleDataObjectConverter */
private $converter;
/** @var DataObjectHelper */
protected $dataObjectHelper;
/** @var EncryptorInterface */
protected $encryptor;
/** @var CustomerRegistry */
protected $customerRegistry;
/**
* @var DataFixtureStorage
*/
private $fixtures;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->customerRepository = $this->objectManager->create(CustomerRepositoryInterface::class);
$this->orderRepository = $this->objectManager->create(OrderRepositoryInterface::class);
$this->customerFactory = $this->objectManager->create(CustomerInterfaceFactory::class);
$this->addressFactory = $this->objectManager->create(AddressInterfaceFactory::class);
$this->accountManagement = $this->objectManager->create(AccountManagementInterface::class);
$this->converter = $this->objectManager->create(ExtensibleDataObjectConverter::class);
$this->dataObjectHelper = $this->objectManager->create(DataObjectHelper::class);
$this->encryptor = $this->objectManager->create(EncryptorInterface::class);
$this->customerRegistry = $this->objectManager->create(CustomerRegistry::class);
$this->fixtures = DataFixtureStorageManager::getStorage();
/** @var CacheInterface $cache */
$cache = $this->objectManager->create(CacheInterface::class);
$cache->remove('extension_attributes_config');
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Customer\Model\CustomerRegistry $customerRegistry */
$customerRegistry = $objectManager->get(CustomerRegistry::class);
$customerRegistry->remove(1);
}
/**
* Check if first name update was successful
*
* @magentoDbIsolation enabled
*/
public function testCreateCustomerNewThenUpdateFirstName()
{
/** Create a new customer */
$email = 'first_last@example.com';
$storeId = 1;
$firstname = 'Tester';
$lastname = 'McTest';
$groupId = 1;
$newCustomerEntity = $this->customerFactory->create()
->setStoreId($storeId)
->setEmail($email)
->setFirstname($firstname)
->setLastname($lastname)
->setGroupId($groupId);
$customer = $this->customerRepository->save($newCustomerEntity);
/** Update customer */
$newCustomerFirstname = 'New First Name';
$updatedCustomer = $this->customerFactory->create();
$this->dataObjectHelper->mergeDataObjects(
CustomerInterface::class,
$updatedCustomer,
$customer
);
$updatedCustomer->setFirstname($newCustomerFirstname);
$this->customerRepository->save($updatedCustomer);
/** Check if update was successful */
$customer = $this->customerRepository->get($customer->getEmail());
$this->assertEquals($newCustomerFirstname, $customer->getFirstname());
$this->assertEquals($lastname, $customer->getLastname());
}
/**
* Test create new customer
*
* @magentoDbIsolation enabled
*/
public function testCreateNewCustomer()
{
$email = 'email@example.com';
$storeId = 1;
$firstname = 'Tester';
$lastname = 'McTest';
$groupId = 1;
$newCustomerEntity = $this->customerFactory->create()
->setStoreId($storeId)
->setEmail($email)
->setFirstname($firstname)
->setLastname($lastname)
->setGroupId($groupId);
$savedCustomer = $this->customerRepository->save($newCustomerEntity);
$this->assertNotNull($savedCustomer->getId());
$this->assertEquals($email, $savedCustomer->getEmail());
$this->assertEquals($storeId, $savedCustomer->getStoreId());
$this->assertEquals($firstname, $savedCustomer->getFirstname());
$this->assertEquals($lastname, $savedCustomer->getLastname());
$this->assertEquals($groupId, $savedCustomer->getGroupId());
$this->assertTrue(!$savedCustomer->getSuffix());
}
/**
* Test update customer
*
* @dataProvider updateCustomerDataProvider
* @magentoAppArea frontend
* @magentoDataFixture Magento/Customer/_files/customer.php
* @param int|null $defaultBilling
* @param int|null $defaultShipping
*/
public function testUpdateCustomer($defaultBilling, $defaultShipping)
{
$existingCustomerId = 1;
$email = 'savecustomer@example.com';
$firstName = 'Firstsave';
$lastName = 'Lastsave';
$newPassword = 'newPassword123';
$newPasswordHash = $this->encryptor->getHash($newPassword, true);
$customerBefore = $this->customerRepository->getById($existingCustomerId);
$customerData = array_merge($customerBefore->__toArray(), [
'id' => 1,
'email' => $email,
'firstname' => $firstName,
'lastname' => $lastName,
'created_in' => 'Admin',
'password' => 'notsaved',
'default_billing' => $defaultBilling,
'default_shipping' => $defaultShipping
]);
$customerDetails = $this->customerFactory->create();
$this->dataObjectHelper->populateWithArray(
$customerDetails,
$customerData,
CustomerInterface::class
);
$this->customerRepository->save($customerDetails, $newPasswordHash);
$customerAfter = $this->customerRepository->getById($existingCustomerId);
$this->assertEquals($email, $customerAfter->getEmail());
$this->assertEquals($firstName, $customerAfter->getFirstname());
$this->assertEquals($lastName, $customerAfter->getLastname());
$this->assertEquals($defaultBilling, $customerAfter->getDefaultBilling());
$this->assertEquals($defaultShipping, $customerAfter->getDefaultShipping());
$this->expectedDefaultShippingsInCustomerModelAttributes(
$existingCustomerId,
$defaultBilling,
$defaultShipping
);
$this->assertEquals('Admin', $customerAfter->getCreatedIn());
$this->accountManagement->authenticate($customerAfter->getEmail(), $newPassword);
$attributesBefore = $this->converter->toFlatArray(
$customerBefore,
[],
CustomerInterface::class
);
$attributesAfter = $this->converter->toFlatArray(
$customerAfter,
[],
CustomerInterface::class
);
// ignore 'updated_at'
unset($attributesBefore['updated_at']);
unset($attributesAfter['updated_at']);
$inBeforeOnly = array_diff_assoc($attributesBefore, $attributesAfter);
$inAfterOnly = array_diff_assoc($attributesAfter, $attributesBefore);
$expectedInBefore = [
'firstname',
'lastname',
'email',
];
foreach ($expectedInBefore as $key) {
$this->assertContains($key, array_keys($inBeforeOnly));
}
$this->assertContains('created_in', array_keys($inAfterOnly));
$this->assertContains('firstname', array_keys($inAfterOnly));
$this->assertContains('lastname', array_keys($inAfterOnly));
$this->assertContains('email', array_keys($inAfterOnly));
$this->assertNotContains('password_hash', array_keys($inAfterOnly));
}
/**
* Test update customer custom attributes
*
* @magentoDataFixture Magento/Customer/_files/attribute_user_defined_custom_attribute.php
* @return void
*/
#[
DataFixture(\Magento\Customer\Test\Fixture\Customer::class, ['email' => 'customer@mail.com'])
]
public function testUpdateCustomerAttributesAutoIncrement()
{
$newAttributeValue = 'value1';
$updateAttributeValue = 'value2';
$customer = $this->customerRepository->get('customer@mail.com');
$customer->setCustomAttribute('custom_attribute1', $newAttributeValue);
$savedCustomer = $this->customerRepository->save($customer);
$savedCustomer->setCustomAttribute('custom_attribute1', $updateAttributeValue);
$this->customerRepository->save($savedCustomer);
$customer = $this->customerRepository->get('customer@mail.com');
$this->assertSame(
$customer->getCustomAttribute('custom_attribute1')->getValue(),
$updateAttributeValue
);
$resource = $this->objectManager->get(\Magento\Framework\App\ResourceConnection::class);
$connection = $resource->getConnection();
$tableStatus = $connection->showTableStatus('customer_entity_varchar');
$this->assertSame($tableStatus['Auto_increment'], '2');
}
/**
* Test update customer address
*
* @magentoAppArea frontend
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
*/
public function testUpdateCustomerAddress()
{
$customerId = 1;
$city = 'San Jose';
$email = 'customer@example.com';
$customer = $this->customerRepository->getById($customerId);
$customerDetails = $customer->__toArray();
$addresses = $customer->getAddresses();
$addressId = $addresses[0]->getId();
$newAddress = array_merge($addresses[0]->__toArray(), ['city' => $city]);
$newAddressDataObject = $this->addressFactory->create();
$this->dataObjectHelper->populateWithArray(
$newAddressDataObject,
$newAddress,
AddressInterface::class
);
$newAddressDataObject->setRegion($addresses[0]->getRegion());
$newCustomerEntity = $this->customerFactory->create();
$this->dataObjectHelper->populateWithArray(
$newCustomerEntity,
$customerDetails,
CustomerInterface::class
);
$newCustomerEntity->setId($customerId)
->setAddresses([$newAddressDataObject, $addresses[1]]);
$this->customerRepository->save($newCustomerEntity);
$newCustomer = $this->customerRepository->get($email);
$this->assertCount(2, $newCustomer->getAddresses());
foreach ($newCustomer->getAddresses() as $newAddress) {
if ($newAddress->getId() == $addressId) {
$this->assertEquals($city, $newAddress->getCity());
}
}
}
/**
* Test preserve all addresses after customer update
*
* @magentoAppArea frontend
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
*/
public function testUpdateCustomerPreserveAllAddresses()
{
$customerId = 1;
$customer = $this->customerRepository->getById($customerId);
$customerDetails = $customer->__toArray();
$newCustomerEntity = $this->customerFactory->create();
$this->dataObjectHelper->populateWithArray(
$newCustomerEntity,
$customerDetails,
CustomerInterface::class
);
$newCustomerEntity->setId($customer->getId())
->setAddresses(null);
$this->customerRepository->save($newCustomerEntity);
$newCustomerDetails = $this->customerRepository->getById($customerId);
//Verify that old addresses are still present
$this->assertCount(2, $newCustomerDetails->getAddresses());
}
/**
* Test update delete all addresses with empty arrays
*
* @magentoAppArea frontend
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
*/
public function testUpdateCustomerDeleteAllAddressesWithEmptyArray()
{
$customerId = 1;
$customer = $this->customerRepository->getById($customerId);
$customerDetails = $customer->__toArray();
$newCustomerEntity = $this->customerFactory->create();
$this->dataObjectHelper->populateWithArray(
$newCustomerEntity,
$customerDetails,
CustomerInterface::class
);
$newCustomerEntity->setId($customer->getId())
->setAddresses([]);
$this->customerRepository->save($newCustomerEntity);
$newCustomerDetails = $this->customerRepository->getById($customerId);
//Verify that old addresses are removed
$this->assertCount(0, $newCustomerDetails->getAddresses());
}
/**
* Test customer update with new address
*
* @magentoAppArea frontend
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
*/
public function testUpdateCustomerWithNewAddress()
{
$customerId = 1;
$customer = $this->customerRepository->getById($customerId);
$customerDetails = $customer->__toArray();
unset($customerDetails['default_billing']);
unset($customerDetails['default_shipping']);
$beforeSaveCustomer = $this->customerFactory->create();
$this->dataObjectHelper->populateWithArray(
$beforeSaveCustomer,
$customerDetails,
CustomerInterface::class
);
$addresses = $customer->getAddresses();
$beforeSaveAddress = $addresses[0]->__toArray();
unset($beforeSaveAddress['id']);
$newAddressDataObject = $this->addressFactory->create();
$this->dataObjectHelper->populateWithArray(
$newAddressDataObject,
$beforeSaveAddress,
AddressInterface::class
);
$beforeSaveCustomer->setAddresses([$newAddressDataObject]);
$this->customerRepository->save($beforeSaveCustomer);
$newCustomer = $this->customerRepository->getById($customerId);
$newCustomerAddresses = $newCustomer->getAddresses();
$addressId = $newCustomerAddresses[0]->getId();
$this->assertEquals($newCustomer->getDefaultBilling(), $addressId, "Default billing invalid value");
$this->assertEquals($newCustomer->getDefaultShipping(), $addressId, "Default shipping invalid value");
}
/**
* Test search customers
*
* @param \Magento\Framework\Api\Filter[] $filters
* @param \Magento\Framework\Api\Filter[] $filterGroup
* @param array $expectedResult array of expected results indexed by ID
*
* @dataProvider searchCustomersDataProvider
*
* @magentoDataFixture Magento/Customer/_files/three_customers.php
* @magentoDbIsolation enabled
*/
public function testSearchCustomers($filters, $filterGroup, $expectedResult)
{
/** @var SearchCriteriaBuilder $searchBuilder */
$searchBuilder = Bootstrap::getObjectManager()->create(SearchCriteriaBuilder::class);
foreach ($filters as $filter) {
$searchBuilder->addFilters([$filter]);
}
if ($filterGroup !== null) {
$searchBuilder->addFilters($filterGroup);
}
$searchResults = $this->customerRepository->getList($searchBuilder->create());
$this->assertEquals(count($expectedResult), $searchResults->getTotalCount());
foreach ($searchResults->getItems() as $item) {
$this->assertEquals($expectedResult[$item->getId()]['email'], $item->getEmail());
$this->assertEquals($expectedResult[$item->getId()]['firstname'], $item->getFirstname());
unset($expectedResult[$item->getId()]);
}
}
/**
* Test ordering
*
* @magentoDataFixture Magento/Customer/_files/three_customers.php
* @magentoDbIsolation enabled
*/
public function testSearchCustomersOrder()
{
/** @var SearchCriteriaBuilder $searchBuilder */
$objectManager = Bootstrap::getObjectManager();
$searchBuilder = $objectManager->create(SearchCriteriaBuilder::class);
// Filter for 'firstname' like 'First'
$filterBuilder = $objectManager->create(FilterBuilder::class);
$firstnameFilter = $filterBuilder->setField('firstname')
->setConditionType('like')
->setValue('First%')
->create();
$searchBuilder->addFilters([$firstnameFilter]);
// Search ascending order
$sortOrderBuilder = $objectManager->create(SortOrderBuilder::class);
$sortOrder = $sortOrderBuilder
->setField('lastname')
->setDirection(SortOrder::SORT_ASC)
->create();
$searchBuilder->addSortOrder($sortOrder);
$searchResults = $this->customerRepository->getList($searchBuilder->create());
$this->assertEquals(3, $searchResults->getTotalCount());
$this->assertEquals('Lastname', $searchResults->getItems()[0]->getLastname());
$this->assertEquals('Lastname2', $searchResults->getItems()[1]->getLastname());
$this->assertEquals('Lastname3', $searchResults->getItems()[2]->getLastname());
// Search descending order
$sortOrder = $sortOrderBuilder
->setField('lastname')
->setDirection(SortOrder::SORT_DESC)
->create();
$searchBuilder->addSortOrder($sortOrder);
$searchResults = $this->customerRepository->getList($searchBuilder->create());
$this->assertEquals('Lastname3', $searchResults->getItems()[0]->getLastname());
$this->assertEquals('Lastname2', $searchResults->getItems()[1]->getLastname());
$this->assertEquals('Lastname', $searchResults->getItems()[2]->getLastname());
}
/**
* Test delete
*
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoAppIsolation enabled
*/
public function testDelete()
{
$fixtureCustomerEmail = 'customer@example.com';
$customer = $this->customerRepository->get($fixtureCustomerEmail);
$this->customerRepository->delete($customer);
/** Ensure that customer was deleted */
$this->expectException(NoSuchEntityException::class);
$this->expectExceptionMessage('No such entity with email = customer@example.com, websiteId = 1');
$this->customerRepository->get($fixtureCustomerEmail);
}
/**
* Test delete by id
*
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoAppIsolation enabled
*/
public function testDeleteById()
{
$fixtureCustomerEmail = 'customer@example.com';
$fixtureCustomerId = 1;
$this->customerRepository->deleteById($fixtureCustomerId);
/** Ensure that customer was deleted */
$this->expectException(NoSuchEntityException::class);
$this->expectExceptionMessage('No such entity with email = customer@example.com, websiteId = 1');
$this->customerRepository->get($fixtureCustomerEmail);
}
/**
* DataProvider update customer
*
* @return array
*/
public function updateCustomerDataProvider()
{
return [
'Customer remove default shipping and billing' => [
null,
null
],
'Customer update default shipping and billing' => [
1,
1
],
];
}
/**
* Search customer data provider
*
* @return array
*/
public function searchCustomersDataProvider()
{
$builder = Bootstrap::getObjectManager()->create(FilterBuilder::class);
return [
'Customer with specific email' => [
[$builder->setField('email')->setValue('customer@search.example.com')->create()],
null,
[1 => ['email' => 'customer@search.example.com', 'firstname' => 'Firstname']],
],
'Customer with specific first name' => [
[$builder->setField('firstname')->setValue('Firstname2')->create()],
null,
[2 => ['email' => 'customer2@search.example.com', 'firstname' => 'Firstname2']],
],
'Customers with either email' => [
[],
[
$builder->setField('firstname')->setValue('Firstname')->create(),
$builder->setField('firstname')->setValue('Firstname2')->create()
],
[
1 => ['email' => 'customer@search.example.com', 'firstname' => 'Firstname'],
2 => ['email' => 'customer2@search.example.com', 'firstname' => 'Firstname2']
],
],
'Customers created since' => [
[
$builder->setField('created_at')->setValue('2011-02-28 15:52:26')
->setConditionType('gt')->create(),
],
[],
[
1 => ['email' => 'customer@search.example.com', 'firstname' => 'Firstname'],
3 => ['email' => 'customer3@search.example.com', 'firstname' => 'Firstname3']
],
]
];
}
/**
* Check defaults billing and shipping in customer model
*
* @param $customerId
* @param $defaultBilling
* @param $defaultShipping
*/
protected function expectedDefaultShippingsInCustomerModelAttributes(
$customerId,
$defaultBilling,
$defaultShipping
) {
/**
* @var Customer $customer
*/
$customer = $this->objectManager->create(Customer::class);
/** @var \Magento\Customer\Model\Customer $customer */
$customer->load($customerId);
$this->assertEquals(
$defaultBilling,
$customer->getDefaultBilling(),
'default_billing customer attribute did not updated'
);
$this->assertEquals(
$defaultShipping,
$customer->getDefaultShipping(),
'default_shipping customer attribute did not updated'
);
}
/**
* Test update default shipping and default billing address
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDbIsolation enabled
*/
public function testUpdateDefaultShippingAndDefaultBillingTest()
{
$customerId = 1;
$customerData = [
"id" => 1,
"website_id" => 1,
"email" => "roni_cost@example.com",
"firstname" => "1111",
"lastname" => "Boss",
"middlename" => null,
"gender" => 0
];
$customerEntity = $this->customerFactory->create(['data' => $customerData]);
$customer = $this->customerRepository->getById($customerId);
$oldDefaultBilling = $customer->getDefaultBilling();
$oldDefaultShipping = $customer->getDefaultShipping();
$savedCustomer = $this->customerRepository->save($customerEntity);
$this->assertEquals(
$savedCustomer->getDefaultBilling(),
$oldDefaultBilling,
'Default billing should not be overridden'
);
$this->assertEquals(
$savedCustomer->getDefaultShipping(),
$oldDefaultShipping,
'Default shipping should not be overridden'
);
}
/**
* Test that UpgradeOrderCustomerEmailObserver is executed
*
* @magentoDataFixture Magento/Sales/_files/order_with_customer.php
* @magentoDbIsolation enabled
*/
public function testUpgradeOrderCustomerEmailObserverWhenEmailIsModified()
{
$customer = $this->customerRepository->getById(self::CUSTOMER_ID);
$customer->setEmail(self::NEW_CUSTOMER_EMAIL);
$this->customerRepository->save($customer);
/** @var SearchCriteriaBuilder $searchBuilder */
$searchBuilder = $this->objectManager->create(SearchCriteriaBuilder::class);
$searchCriteria = $searchBuilder
->addFilter(OrderInterface::CUSTOMER_ID, $customer->getId())
->create();
$customerOrders = $this->orderRepository->getList($searchCriteria);
foreach ($customerOrders as $customerOrder) {
$this->assertEquals(self::NEW_CUSTOMER_EMAIL, $customerOrder->getCustomerEmail());
}
}
/**
* Test that UpgradeOrderCustomerEmailObserver is executed but does not update orders
*
* @magentoDataFixture Magento/Sales/_files/order_with_customer.php
* @magentoDbIsolation enabled
*/
public function testUpgradeOrderCustomerEmailObserverWhenEmailIsNotModified(): void
{
$customer = $this->customerRepository->getById(self::CUSTOMER_ID);
$this->customerRepository->save($customer);
/** @var SearchCriteriaBuilder $searchBuilder */
$searchBuilder = $this->objectManager->create(SearchCriteriaBuilder::class);
$searchCriteria = $searchBuilder
->addFilter(OrderInterface::CUSTOMER_ID, $customer->getId())
->create();
$customerOrders = $this->orderRepository->getList($searchCriteria);
foreach ($customerOrders as $customerOrder) {
$this->assertEquals('customer@example.com', $customerOrder->getCustomerEmail());
}
}
public function testSaveCustomerWithInvalidAttrValue(): void
{
$customerData = [
'website_id' => 1,
'email' => 'email1@example.com',
'firstname' => 'Firstname',
'lastname' => 'Lastname',
'gender' => 123,
];
$customer = $this->customerFactory->create(['data' => $customerData]);
$this->expectException(ValidatorException::class);
$this->expectExceptionMessage('Attribute gender does not contain option with Id 123');
$this->customerRepository->save($customer);
}
#[
DataFixture(
CustomerFixture::class,
[
'email' => 'émâíl123@example.com',
'rp_token' => 'random_token_123'
],
as: 'customer'
)
]
public function testSaveCustomerWithEmailWithDiacritics(): void
{
$customer = $this->fixtures->get('customer');
$this->assertEquals('émâíl123@example.com', $customer->getEmail());
$this->assertNotEquals('random_token_123', $customer->getRpToken());
}
}
@@ -0,0 +1,61 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Model\ResourceModel;
use Magento\Framework\ObjectManagerInterface;
use Magento\Customer\Model\Customer as CustomerModel;
/**
* Integration test for @see \Magento\Customer\Model\ResourceModel\Customer
*/
class CustomerTest extends \PHPUnit\Framework\TestCase
{
/**
* @var CustomerModel
*/
private $customerModel;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->customerModel = $this->objectManager->create(CustomerModel::class);
parent::setUp();
}
/**
* Test save rp token
*
* @throws \Exception
*/
public function testSave(): void
{
$token='randomstring';
$email= uniqid()."@example.com";
$this->customerModel->setData(
[
'email' => $email,
'rp_token' => $token,
'firstname'=> 'John',
'lastname' => 'Doe'
]
)->save();
$consumerResourceModel = $this->customerModel->getResource();
$this->assertEquals($token, $this->customerModel->getRpToken());
$this->assertNotEquals(
$this->customerModel->getRpToken(),
$consumerResourceModel->load($this->customerModel, 'rp_token')
);
}
}
@@ -0,0 +1,88 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Model\ResourceModel\Grid;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Framework\Exception\InvalidEmailOrPasswordException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Indexer\TestCase;
/**
* Test if customer account lock on too many failed authentication attempts triggers customer grid reindex
*
* @SuppressWarnings(PHPMD)
*/
class CollectionReindexOnAccountLockTest extends TestCase
{
/**
* Trigger customer account lock by making 10 failed authentication attempts
*/
private function lockCustomerAccountWithInvalidAuthentications()
{
/** @var AccountManagementInterface */
$accountManagement = Bootstrap::getObjectManager()->create(AccountManagementInterface::class);
for ($i = 0; $i < 10; $i++) {
try {
$accountManagement->authenticate('customer@example.com', 'wrongPassword');
// phpcs:ignore Magento2.CodeAnalysis.EmptyBlock
} catch (InvalidEmailOrPasswordException $e) {
}
}
}
/**
* @return string|null
* @throws NoSuchEntityException
*/
private function getCustomerLockExpire(): ?string
{
/** @var CustomerRegistry $customerRegistry */
$customerRegistry = Bootstrap::getObjectManager()->create(CustomerRegistry::class);
$customerModel = $customerRegistry->retrieve(1);
$this->assertNotEmpty($customerModel);
return $customerModel->getData('lock_expires');
}
/**
* @return string|null
*/
private function getCustomerGridLockExpire(): ?string
{
/** @var Collection */
$gridCustomerCollection = Bootstrap::getObjectManager()->create(Collection::class);
$gridCustomerItem = $gridCustomerCollection->getItemById(1);
$this->assertNotEmpty($gridCustomerItem);
return $gridCustomerItem->getData('lock_expires');
}
/**
* Test if customer account lock on too many failed authentication attempts triggers customer grid reindex
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoAppIsolation enabled
* @magentoDbIsolation disabled
*/
public function testCustomerAccountReindexOnLock()
{
$this->assertSame(
$this->getCustomerGridLockExpire(),
$this->getCustomerLockExpire()
);
$this->lockCustomerAccountWithInvalidAuthentications();
$this->assertSame(
$this->getCustomerGridLockExpire(),
$this->getCustomerLockExpire()
);
}
}
@@ -0,0 +1,99 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Model\ResourceModel\Grid;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Indexer\TestCase;
/**
* Customer grid collection tests.
*/
class CollectionTest extends TestCase
{
public static function setUpBeforeClass(): void
{
$db = Bootstrap::getInstance()
->getBootstrap()
->getApplication()
->getDbInstance();
if (!$db->isDbDumpExists()) {
throw new \LogicException('DB dump does not exist.');
}
$db->restoreFromDbDump();
parent::setUpBeforeClass();
}
/**
* Test updated data for customer grid indexer during save/update customer data(including address data)
* in 'Update on Schedule' mode.
*
* Customer Grid Indexer can't work in 'Update on Schedule' mode. All data for indexer must be updated in realtime
* during save/update customer data(including address data).
*
* @magentoDataFixture Magento/Customer/_files/customer_grid_indexer_enabled_update_on_schedule.php
* @magentoDataFixture Magento/Customer/_files/customer_sample.php
* @magentoAppIsolation enabled
* @magentoDbIsolation disabled
*/
public function testGetItemByIdForUpdateOnSchedule()
{
$targetObject = Bootstrap::getObjectManager()
->create(Collection::class);
$customerRepository = Bootstrap::getObjectManager()
->create(CustomerRepositoryInterface::class);
/** Verify after first save */
/** @var CustomerInterface $newCustomer */
$newCustomer = $customerRepository->get('customer@example.com');
/** @var CustomerInterface $item */
$item = $targetObject->getItemById($newCustomer->getId());
$this->assertNotEmpty($item);
$this->assertSame($newCustomer->getEmail(), $item->getEmail());
$this->assertSame('test street test city Armed Forces Middle East 01001', $item->getBillingFull());
/** Verify after update */
$newCustomer->setEmail('customer_updated@example.com');
$customerRepository->save($newCustomer);
$targetObject->clear();
$item = $targetObject->getItemById($newCustomer->getId());
$this->assertSame($newCustomer->getEmail(), $item->getEmail());
}
/**
* Verifies that filter condition date is being converted to config timezone before select sql query
*
* @return void
*/
public function testAddFieldToFilter(): void
{
$filterDate = "2021-01-26 00:00:00";
/** @var TimezoneInterface $timeZone */
$timeZone = Bootstrap::getObjectManager()
->get(TimezoneInterface::class);
/** @var Collection $gridCollection */
$gridCollection = Bootstrap::getObjectManager()
->get(Collection::class);
$convertedDate = $timeZone->convertConfigTimeToUtc($filterDate);
$collection = $gridCollection->addFieldToFilter('created_at', ['qteq' => $filterDate]);
$expectedSelect = "WHERE (((`main_table`.`created_at` = '{$convertedDate}')))";
$this->assertStringContainsString($expectedSelect, $collection->getSelectSql(true));
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
parent::tearDown();
}
}
@@ -0,0 +1,118 @@
<?php
/**
* \Magento\Customer\Model\ResourceModel\Group\Grid\ServiceCollection
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Model\ResourceModel\Group\Grid;
class ServiceCollectionTest extends \PHPUnit\Framework\TestCase
{
/** @var ServiceCollection */
protected $collection;
protected function setUp(): void
{
$this->collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Customer\Model\ResourceModel\Group\Grid\ServiceCollection::class
);
}
public function testSetOrder()
{
$this->collection->setOrder('code', \Magento\Framework\Data\Collection::SORT_ORDER_ASC);
$this->collection->loadData();
$items = $this->collection->getItems();
$this->assertCount(4, $items);
$this->assertEquals('General', $items[0]->getCode());
$this->assertEquals('1', $items[0]->getId());
$this->assertEquals('3', $items[0]->getTaxClassId());
$this->assertEquals('NOT LOGGED IN', $items[1]->getCode());
$this->assertEquals('0', $items[1]->getId());
$this->assertEquals('3', $items[1]->getTaxClassId());
$this->assertEquals('Retailer', $items[2]->getCode());
$this->assertEquals('3', $items[2]->getId());
$this->assertEquals('3', $items[2]->getTaxClassId());
$this->assertEquals('Wholesale', $items[3]->getCode());
$this->assertEquals('2', $items[3]->getId());
$this->assertEquals('3', $items[3]->getTaxClassId());
}
public function testArrayFilter()
{
$this->collection->addFieldToFilter(['code'], [['NOT LOGGED IN']]);
$this->collection->loadData();
$items = $this->collection->getItems();
$this->assertCount(1, $items);
$this->assertEquals('NOT LOGGED IN', $items[0]->getCode());
$this->assertEquals('0', $items[0]->getId());
$this->assertEquals('3', $items[0]->getTaxClassId());
}
public function testOrArrayFilter()
{
$this->collection->addFieldToFilter(['code', 'code'], ['General', 'Retailer']);
$this->collection->loadData();
$items = $this->collection->getItems();
$this->assertCount(2, $items);
$this->assertEquals('General', $items[0]->getCode());
$this->assertEquals('1', $items[0]->getId());
$this->assertEquals('3', $items[0]->getTaxClassId());
$this->assertEquals('Retailer', $items[1]->getCode());
$this->assertEquals('3', $items[1]->getId());
$this->assertEquals('3', $items[1]->getTaxClassId());
}
public function testSingleFilter()
{
$this->collection->addFieldToFilter('code', 'NOT LOGGED IN');
$this->collection->loadData();
$items = $this->collection->getItems();
$this->assertCount(1, $items);
$this->assertEquals('NOT LOGGED IN', $items[0]->getCode());
$this->assertEquals('0', $items[0]->getId());
$this->assertEquals('3', $items[0]->getTaxClassId());
}
public function testSingleLikeFilter()
{
$this->collection->addFieldToFilter('code', ['like' => 'NOT%']);
$this->collection->loadData();
$items = $this->collection->getItems();
$this->assertCount(1, $items);
$this->assertEquals('NOT LOGGED IN', $items[0]->getCode());
$this->assertEquals('0', $items[0]->getId());
$this->assertEquals('3', $items[0]->getTaxClassId());
}
/**
*/
public function testAddToFilterException()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('The array of fields failed to pass. The array must include at one field.');
$this->collection->addFieldToFilter([], 'not_array');
}
/**
*/
public function testAddToFilterExceptionArrayNotSymmetric()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('The field array failed to pass. The array must have a matching condition array.');
$this->collection->addFieldToFilter(['field2', 'field2'], ['condition1']);
}
}
@@ -0,0 +1,353 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Model\ResourceModel;
use Magento\Customer\Api\Data\GroupInterface;
use Magento\Framework\Api\SortOrder;
/**
* Integration test for \Magento\Customer\Model\ResourceModel\GroupRepository
*/
class GroupRepositoryTest extends \PHPUnit\Framework\TestCase
{
/** The group id of the "NOT LOGGED IN" group */
const NOT_LOGGED_IN_GROUP_ID = 0;
/** @var \Magento\Customer\Api\GroupRepositoryInterface */
private $groupRepository;
/** @var \Magento\Framework\ObjectManagerInterface */
private $objectManager;
/** @var \Magento\Customer\Api\Data\GroupInterfaceFactory */
private $groupFactory;
/** @var \Magento\Framework\Api\SearchCriteriaBuilder */
private $searchCriteriaBuilder;
/** @var \Magento\Framework\Api\SortOrderBuilder */
private $sortOrderBuilder;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->groupRepository = $this->objectManager->create(\Magento\Customer\Api\GroupRepositoryInterface::class);
$this->groupFactory = $this->objectManager->create(\Magento\Customer\Api\Data\GroupInterfaceFactory::class);
$this->searchCriteriaBuilder = $this->objectManager->create(
\Magento\Framework\Api\SearchCriteriaBuilder::class
);
$this->sortOrderBuilder = $this->objectManager->create(\Magento\Framework\Api\SortOrderBuilder::class);
}
/**
* @param array $testGroup
* @dataProvider getGroupsDataProvider
*/
public function testGetGroup($testGroup)
{
$group = $this->groupRepository->getById($testGroup[GroupInterface::ID]);
$this->assertEquals($testGroup[GroupInterface::ID], $group->getId());
$this->assertEquals($testGroup[GroupInterface::CODE], $group->getCode());
$this->assertEquals($testGroup[GroupInterface::TAX_CLASS_ID], $group->getTaxClassId());
}
/**
* @return array
*/
public function getGroupsDataProvider()
{
return [
[[GroupInterface::ID => 0, GroupInterface::CODE => 'NOT LOGGED IN', GroupInterface::TAX_CLASS_ID => 3]],
[[GroupInterface::ID => 1, GroupInterface::CODE => 'General', GroupInterface::TAX_CLASS_ID => 3]],
[[GroupInterface::ID => 2, GroupInterface::CODE => 'Wholesale', GroupInterface::TAX_CLASS_ID => 3]],
[[GroupInterface::ID => 3, GroupInterface::CODE => 'Retailer', GroupInterface::TAX_CLASS_ID => 3]],
];
}
/**
*/
public function testGetGroupException()
{
$this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class);
$this->expectExceptionMessage('No such entity with id = 9999');
$this->groupRepository->getById(9999);
}
/**
* @magentoDbIsolation enabled
*/
public function testCreateGroup()
{
$group = $this->groupFactory->create()->setId(null)->setCode('Create Group')->setTaxClassId(3);
$groupId = $this->groupRepository->save($group)->getId();
$this->assertNotNull($groupId);
$newGroup = $this->groupRepository->getById($groupId);
$this->assertEquals($groupId, $newGroup->getId());
$this->assertEquals($group->getCode(), $newGroup->getCode());
$this->assertEquals($group->getTaxClassId(), $newGroup->getTaxClassId());
}
/**
* @magentoDbIsolation enabled
*/
public function testCreateGroupDefaultTaxClass()
{
$group = $this->groupFactory->create()->setId(null)->setCode('Create Group')->setTaxClassId(null);
$groupId = $this->groupRepository->save($group)->getId();
$this->assertNotNull($groupId);
$newGroup = $this->groupRepository->getById($groupId);
$this->assertEquals($groupId, $newGroup->getId());
$this->assertEquals($group->getCode(), $newGroup->getCode());
$this->assertEquals(GroupRepository::DEFAULT_TAX_CLASS_ID, $newGroup->getTaxClassId());
}
/**
* @magentoDbIsolation enabled
*/
public function testUpdateGroup()
{
$group = $this->groupFactory->create()->setId(null)->setCode('New Group')->setTaxClassId(3);
$groupId = $this->groupRepository->save($group)->getId();
$this->assertNotNull($groupId);
$newGroup = $this->groupRepository->getById($groupId);
$this->assertEquals($groupId, $newGroup->getId());
$this->assertEquals($group->getCode(), $newGroup->getCode());
$this->assertEquals($group->getTaxClassId(), $newGroup->getTaxClassId());
$updates = $this->groupFactory->create()->setId($groupId)->setCode('Updated Group')->setTaxClassId(3);
$this->assertNotNull($this->groupRepository->save($updates));
$updatedGroup = $this->groupRepository->getById($groupId);
$this->assertEquals($updates->getCode(), $updatedGroup->getCode(), 'Code not updated.');
$this->assertEquals($updates->getTaxClassId(), $updatedGroup->getTaxClassId(), 'Tax Class should not change.');
}
/**
* @magentoDbIsolation enabled
*/
public function testUpdateGroupException()
{
$this->expectException(\Magento\Framework\Exception\InputException::class);
$this->expectExceptionMessage('Invalid value of "9999" provided for the taxClassId field.');
$group = $this->groupFactory->create()->setId(null)->setCode('New Group')->setTaxClassId(3);
$groupId = $this->groupRepository->save($group)->getId();
$this->assertNotNull($groupId);
$newGroup = $this->groupRepository->getById($groupId);
$this->assertEquals($groupId, $newGroup->getId());
$this->assertEquals($group->getCode(), $newGroup->getCode());
$this->assertEquals($group->getTaxClassId(), $newGroup->getTaxClassId());
$updates = $this->groupFactory->create()->setId($groupId)->setCode('Updated Group')->setTaxClassId(9999);
$this->groupRepository->save($updates);
$updatedGroup = $this->groupRepository->getById($groupId);
$this->assertEquals($updates->getCode(), $updatedGroup->getCode());
$this->assertEquals($updates->getTaxClassId(), $updatedGroup->getTaxClassId());
}
/**
* @magentoDbIsolation enabled
*/
public function testDelete()
{
$group = $this->groupFactory->create()->setId(null)->setCode('New Group')->setTaxClassId(3);
$groupId = $this->groupRepository->save($group)->getId();
$newGroup = $this->groupRepository->getById($groupId);
$this->assertTrue($this->groupRepository->delete($newGroup));
}
/**
* @magentoDbIsolation enabled
*/
public function testDeleteById()
{
$group = $this->groupFactory->create()->setId(null)->setCode('New Group')->setTaxClassId(3);
$groupId = $this->groupRepository->save($group)->getId();
$this->assertTrue($this->groupRepository->deleteById($groupId));
}
/**
*/
public function testDeleteDoesNotExist()
{
$this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class);
$this->expectExceptionMessage('No such entity with id = 9999');
$this->assertFalse($this->groupRepository->deleteById(9999));
}
public function testGetAllGroups()
{
$searchResults = $this->groupRepository->getList($this->searchCriteriaBuilder->create());
/** @var GroupInterface[] $results */
$results = $searchResults->getItems();
$this->assertCount(4, $results);
}
/**
* @param array $filters
* @param array $filterGroup
* @param array $expectedResult array of expected results indexed by ID
*
* @dataProvider searchGroupsDataProvider
*/
public function testGetList($filters, $filterGroup, $expectedResult)
{
foreach ($filters as $filter) {
$this->searchCriteriaBuilder->addFilters([$filter]);
}
if ($filterGroup !== null) {
$this->searchCriteriaBuilder->addFilters($filterGroup);
}
$searchResults = $this->groupRepository->getList($this->searchCriteriaBuilder->create());
/** @var $item GroupInterface */
foreach ($searchResults->getItems() as $item) {
$this->assertEquals($expectedResult[$item->getId()][GroupInterface::CODE], $item->getCode());
$this->assertEquals($expectedResult[$item->getId()][GroupInterface::TAX_CLASS_ID], $item->getTaxClassId());
unset($expectedResult[$item->getId()]);
}
}
public function searchGroupsDataProvider()
{
$builder = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Framework\Api\FilterBuilder::class);
return [
'eq' => [
[$builder->setField(GroupInterface::CODE)->setValue('General')->create()],
null,
[1 => [GroupInterface::CODE => 'General', GroupInterface::TAX_CLASS_ID => 3]],
],
'and' => [
[
$builder->setField(GroupInterface::CODE)->setValue('General')->create(),
$builder->setField(GroupInterface::TAX_CLASS_ID)->setValue('3')->create(),
$builder->setField(GroupInterface::ID)->setValue('1')->create(),
],
[],
[1 => [GroupInterface::CODE => 'General', GroupInterface::TAX_CLASS_ID => 3]],
],
'or' => [
[],
[
$builder->setField(GroupInterface::CODE)->setValue('General')->create(),
$builder->setField(GroupInterface::CODE)->setValue('Wholesale')->create(),
],
[
1 => [GroupInterface::CODE => 'General', GroupInterface::TAX_CLASS_ID => 3],
2 => [GroupInterface::CODE => 'Wholesale', GroupInterface::TAX_CLASS_ID => 3]
],
],
'like' => [
[
$builder->setField(GroupInterface::CODE)->setValue('er')->setConditionType('like')
->create(),
],
[],
[
1 => [GroupInterface::CODE => 'General', GroupInterface::TAX_CLASS_ID => 3],
3 => [GroupInterface::CODE => 'Retailer', GroupInterface::TAX_CLASS_ID => 3]
],
],
'like_tax_name' => [
[
$builder->setField(GroupInterface::TAX_CLASS_NAME)->setValue('Retail Customer')
->setConditionType('like')
->create(),
],
[],
[
0 => [GroupInterface::CODE => 'NOT LOGGED IN', GroupInterface::TAX_CLASS_ID => 3],
1 => [GroupInterface::CODE => 'General', GroupInterface::TAX_CLASS_ID => 3],
2 => [GroupInterface::CODE => 'Wholesale', GroupInterface::TAX_CLASS_ID => 3],
3 => [GroupInterface::CODE => 'Retailer', GroupInterface::TAX_CLASS_ID => 3],
],
],
];
}
/**
* @param string $field
* @param string, $direction
* @param string, $methodName
* @param array $expectedResult
*
* @dataProvider sortOrderDataProvider
*/
public function testGetListSortOrder($field, $direction, $methodName, $expectedResult)
{
/** @var SortOrder $sortOrder */
/** @var string $direction */
$direction = ($direction == 'ASC') ? SortOrder::SORT_ASC : SortOrder::SORT_DESC;
$sortOrder = $this->sortOrderBuilder->setField($field)->setDirection($direction)->create();
$this->searchCriteriaBuilder->addSortOrder($sortOrder);
$searchResults = $this->groupRepository->getList($this->searchCriteriaBuilder->create());
/** @var \Magento\Customer\Api\Data\GroupInterface[] $resultItems */
$resultItems = $searchResults->getItems();
$this->assertTrue(count($resultItems) > 0);
$result = [];
foreach ($resultItems as $item) {
/** @var \Magento\Customer\Model\Data\Group $item */
$result[] = $item->$methodName();
}
$this->assertEquals($expectedResult, $result);
}
/**
* @return array
*/
public function sortOrderDataProvider()
{
return [
[
GroupInterface::ID,
'ASC',
'getId',
[0, 1, 2, 3],
],
[
GroupInterface::ID,
'DESC',
'getId',
[3, 2, 1, 0],
],
[
GroupInterface::CODE,
'ASC',
'getCode',
['General', 'NOT LOGGED IN', 'Retailer', 'Wholesale'],
],
[
GroupInterface::CODE,
'DESC',
'getCode',
['Wholesale', 'Retailer', 'NOT LOGGED IN', 'General'],
],
[
GroupInterface::TAX_CLASS_NAME,
'ASC',
'getTaxClassName',
['Retail Customer', 'Retail Customer', 'Retail Customer', 'Retail Customer']
],
[
GroupInterface::TAX_CLASS_NAME,
'DESC',
'getTaxClassName',
['Retail Customer', 'Retail Customer', 'Retail Customer', 'Retail Customer']
],
];
}
}