Skip to content

MAGE-1301: Add integration tests for Insights events #1772

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: release/3.17.0-dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
206 changes: 206 additions & 0 deletions Test/Integration/Frontend/Insights/EventsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
<?php

namespace Algolia\AlgoliaSearch\Test\Integration\Frontend\Insights;

use Algolia\AlgoliaSearch\Api\Insights\EventProcessorInterface;
use Algolia\AlgoliaSearch\Api\InsightsClient;
use Algolia\AlgoliaSearch\Service\Insights\EventProcessor;
use Algolia\AlgoliaSearch\Test\Integration\TestCase;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\ObjectManagerInterface;
use Magento\Quote\Api\GuestCartManagementInterface;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\QuoteIdMask;
use Magento\Quote\Model\QuoteIdMaskFactory;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\OrderRepository;
use Magento\Store\Model\StoreManager;
use Magento\TestFramework\Helper\Bootstrap;

/**
* @magentoDbIsolation enabled
* @magentoAppArea frontend
*/
class EventsTest extends TestCase
{
const PLACED_ORDER_EVENT = 'Placed Order';
const EVENT_TYPE_CONVERSION = "conversion";
const EVENT_SUBTYPE_PURCHASE = "purchase";
const INDEX = 'my-index';
const TOKEN = 'dummy-token';

/**
* @var ObjectManagerInterface
*/
protected $objectManager;

/**
* @var GuestCartManagementInterface
*/
protected $cartManagement;

/**
* @var CheckoutSession
*/
protected $checkoutSession;

/**
* @var QuoteIdMaskFactory
*/
protected $quoteIdMaskFactory;

/** @var StoreManager */
protected $storeManager;

/**
* @var EventProcessor
*/
protected $eventProcessor;

/**
* @var InsightsClient
*/
protected $insightsClient;

protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();

$this->cartManagement = $this->objectManager->get(GuestCartManagementInterface::class);
$this->checkoutSession = $this->objectManager->get(CheckoutSession::class);
$this->quoteIdMaskFactory = $this->objectManager->get(QuoteIdMaskFactory::class);
$this->eventProcessor = $this->objectManager->get(EventProcessor::class);

/** @var StoreManager $storeManager */
$this->storeManager = $this->objectManager->get(StoreManager::class);

$this->insightsClient = $this->getMockBuilder(InsightsClient::class)
->disableOriginalConstructor()
->getMock();

$this->eventProcessor->setInsightsClient($this->insightsClient);
$this->eventProcessor->setAnonymousUserToken(self::TOKEN);
$this->eventProcessor->setStoreManager($this->storeManager);
}

/**
* @param Order $order
* @param bool $withQueryID
* @param string $eventName
* @return array[]
*/
protected function generateConversionEvent(Order $order, bool $withQueryID = true, string $eventName = self::PLACED_ORDER_EVENT): array
{
$event = [
EventProcessorInterface::EVENT_KEY_SUBTYPE => self::EVENT_SUBTYPE_PURCHASE,
EventProcessorInterface::EVENT_KEY_OBJECT_IDS => [],
EventProcessorInterface::EVENT_KEY_OBJECT_DATA => [],
EventProcessorInterface::EVENT_KEY_CURRENCY => 'USD',
EventProcessorInterface::EVENT_KEY_VALUE => 0,
'eventType' => self::EVENT_TYPE_CONVERSION,
'eventName' => $eventName,
'index' => self::INDEX,
'userToken' => self::TOKEN,
];

if ($withQueryID) {
$event[EventProcessorInterface::EVENT_KEY_QUERY_ID] = '';
}

foreach ($order->getItems() as $item) {
$event[EventProcessorInterface::EVENT_KEY_OBJECT_IDS][] = $item->getProductId();
$event[EventProcessorInterface::EVENT_KEY_OBJECT_DATA][] = [
'price' => $item->getPrice(),
'discount' => $item->getDiscountAmount(),
'quantity' => $item->getQtyOrdered()
];
$event[EventProcessorInterface::EVENT_KEY_VALUE] += $item->getPrice() * $item->getQtyOrdered();
}

return ['events' => [$event]];
}

/**
* @param Order $order
* @param bool $withQueryID
* @return void
*/
protected function assertOrderPurchaseEvent(Order $order, bool $withQueryID = true): void
{
$args = [$this->generateConversionEvent($order, $withQueryID), []];

$this->insightsClient
->expects(self::once())
->method('pushEvents')
->with(...$args)
->willReturn([]);

$this->eventProcessor->convertPurchase(
self::PLACED_ORDER_EVENT,
self::INDEX,
$order
);
}

/**
* Gets order entity by increment id.
*
* @param string $incrementId
* @return OrderInterface
*/
protected function getOrder(string $incrementId): OrderInterface
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('increment_id', $incrementId)
->create();

/** @var OrderRepositoryInterface $repository */
$repository = $this->objectManager->get(OrderRepositoryInterface::class);
$items = $repository->getList($searchCriteria)
->getItems();

return array_pop($items);
}

/**
* @magentoDataFixture Magento/Sales/_files/guest_quote_with_addresses.php
*/
public function testQuoteToOrder()
{
/** @var Quote $quote */
$quote = $this->objectManager->create(Quote::class);
$quote->load('guest_quote', 'reserved_order_id');

$this->checkoutSession->setQuoteId($quote->getId());

/** @var QuoteIdMask $quoteIdMask */
$quoteIdMask = $this->quoteIdMaskFactory->create();
$quoteIdMask->load($quote->getId(), 'quote_id');
$cartId = $quoteIdMask->getMaskedId();

/** @var GuestCartManagementInterface $cartManagement */
$orderId = $this->cartManagement->placeOrder($cartId);
/** @var Order $order */
$order = $this->objectManager->get(OrderRepository::class)->get($orderId);

// GrandTotal takes shipping into account
$this->assertEquals(15, $order->getGrandTotal());
$this->assertOrderPurchaseEvent($order, false);
}

/**
* @magentoDataFixture Algolia_AlgoliaSearch::Test/Integration/Frontend/Insights/_files/order_with_two_order_items.php
*/
public function testOrderWithTwoOrderItems()
{
/** @var Order $order */
$order = $this->getOrder('100000001');

$this->assertOrderPurchaseEvent($order);
}
}
19 changes: 19 additions & 0 deletions Test/Integration/Frontend/Insights/_files/address_data.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

return [
'region' => 'CA',
'region_id' => '12',
'postcode' => '11111',
'company' => 'Test Company',
'lastname' => 'lastname',
'firstname' => 'firstname',
'street' => 'street',
'city' => 'Los Angeles',
'email' => '[email protected]',
'telephone' => '11111111',
'country_id' => 'US'
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Sales\Api\Data\OrderAddressInterfaceFactory;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Api\Data\OrderItemInterfaceFactory;
use Magento\Sales\Api\Data\OrderPaymentInterfaceFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Address;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
use Magento\Customer\Model\CustomerRegistry;
use Magento\TestFramework\Helper\Bootstrap;

Resolver::getInstance()->requireDataFixture('Magento/Customer/_files/customer.php');
Resolver::getInstance()->requireDataFixture('Algolia_AlgoliaSearch::Test/Integration/Frontend/Insights//_files/products.php');

$objectManager = Bootstrap::getObjectManager();
$addressData = include __DIR__ . '/address_data.php';
/** @var CustomerRegistry $customerRegistry */
$customerRegistry = $objectManager->create(CustomerRegistry::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(ProductRepositoryInterface::class);
$customer = $customerRegistry->retrieve(1);
$product = $productRepository->get('simple');
$customDesignProduct = $productRepository->get('custom-design-simple-product');
/** @var OrderAddressInterfaceFactory $addressFactory */
$addressFactory = $objectManager->get(OrderAddressInterfaceFactory::class);
/** @var OrderPaymentInterfaceFactory $paymentFactory */
$paymentFactory = $objectManager->get(OrderPaymentInterfaceFactory::class);
/** @var OrderInterfaceFactory $orderFactory */
$orderFactory = $objectManager->get(OrderInterfaceFactory::class);
/** @var OrderItemInterfaceFactory $orderItemFactory */
$orderItemFactory = $objectManager->get(OrderItemInterfaceFactory::class);
/** @var StoreManagerInterface $storeManager */
$storeManager = $objectManager->get(StoreManagerInterface::class);
/** @var OrderRepositoryInterface $orderRepository */
$orderRepository = $objectManager->get(OrderRepositoryInterface::class);

$billingAddress = $addressFactory->create(['data' => $addressData]);
$billingAddress->setAddressType(Address::TYPE_BILLING);
$shippingAddress = $addressFactory->create(['data' => $addressData]);
$shippingAddress->setAddressType(Address::TYPE_SHIPPING);
$payment = $paymentFactory->create();
$payment->setMethod('checkmo')->setAdditionalInformation(
[
'last_trans_id' => '11122',
'metadata' => [
'type' => 'free',
'fraudulent' => false,
]
]
);

$defaultStoreId = $storeManager->getStore('default')->getId();
$order = $orderFactory->create();
$order->setIncrementId('100000001')
->setState(Order::STATE_PROCESSING)
->setStatus($order->getConfig()->getStateDefaultStatus(Order::STATE_PROCESSING))
->setSubtotal(20)
->setGrandTotal(20)
->setBaseSubtotal(20)
->setBaseGrandTotal(20)
->setCustomerIsGuest(false)
->setCustomerId($customer->getId())
->setCustomerEmail($customer->getEmail())
->setBillingAddress($billingAddress)
->setShippingAddress($shippingAddress)
->setStoreId($defaultStoreId)
->setPayment($payment);

$orderItem = $orderItemFactory->create();
$orderItem->setProductId($product->getId())
->setQtyOrdered(5)
->setBasePrice($product->getPrice())
->setPrice($product->getPrice())
->setRowTotal($product->getPrice())
->setProductType($product->getTypeId())
->setName($product->getName())
->setSku($product->getSku());
$order->addItem($orderItem);

$orderItem = $orderItemFactory->create();
$orderItem->setProductId($customDesignProduct->getId())
->setQtyOrdered(5)
->setBasePrice($customDesignProduct->getPrice())
->setPrice($customDesignProduct->getPrice())
->setRowTotal($customDesignProduct->getPrice())
->setProductType($customDesignProduct->getTypeId())
->setName($customDesignProduct->getName())
->setSku($customDesignProduct->getSku());
$order->addItem($orderItem);
$orderRepository->save($order);
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

use Magento\Framework\Registry;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;

$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
/** @var OrderRepositoryInterface $orderRepository */
$orderRepository = $objectManager->get(OrderRepositoryInterface::class);
/** @var CollectionFactory $orderCollectionFactory */
$orderCollectionFactory = $objectManager->get(CollectionFactory::class);

$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
$order = $orderCollectionFactory->create()
->addFieldToFilter(OrderInterface::INCREMENT_ID, '100000001')
->setPageSize(1)
->getFirstItem();
if ($order->getId()) {
$orderRepository->delete($order);
}

$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);

Resolver::getInstance()->requireDataFixture('Magento/Customer/_files/customer_rollback.php');
Resolver::getInstance()->requireDataFixture('Algolia_AlgoliaSearch::Test/Integration/Frontend/Insights/_files/products_rollback.php');
Loading