First upload

This commit is contained in:
Nikolai Fesenko
2025-02-02 13:37:56 +01:00
commit 8d227c9191
3281 changed files with 362319 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
declare(strict_types=1);
namespace OxidEsales\PayPalModule\Tests\Unit;
trait AdminUserTrait
{
public static function setUpBeforeClass(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDB()->execute(
"REPLACE INTO `oxuser` (`OXID`, `OXACTIVE`, `OXRIGHTS`, `OXSHOPID`, `OXUSERNAME`, `OXPASSWORD`, `OXPASSSALT`, `OXCUSTNR`, `OXUSTID`, `OXCOMPANY`, `OXFNAME`, `OXLNAME`, `OXSTREET`, `OXSTREETNR`, `OXADDINFO`, `OXCITY`, `OXCOUNTRYID`, `OXSTATEID`, `OXZIP`, `OXFON`, `OXFAX`, `OXSAL`, `OXBONI`, `OXCREATE`, `OXREGISTER`, `OXPRIVFON`, `OXMOBFON`, `OXBIRTHDATE`, `OXURL`, `OXUPDATEKEY`, `OXUPDATEEXP`, `OXPOINTS`) VALUES ('oxdefaultadmin', 1, 'malladmin', 1, 'admin', 'e3a8a383819630e42d9ef90be2347ea70364b5efbb11dfc59adbf98487e196fffe4ef4b76174a7be3f2338581e507baa61c852b7d52f4378e21bd2de8c1efa5e', '61646D696E61646D696E61646D696E', 1, '', 'Your Company Name', 'John', 'Doe', 'Maple Street', '2425', '', 'Any City', 'a7c40f631fc920687.20179984', '', '9041', '217-8918712', '217-8918713', 'MR', 1000, '2003-01-01 00:00:00', '2003-01-01 00:00:00', '', '', '0000-00-00', '', '', 0, 0);"
);
}
public static function tearDownAfterClass(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDB()->execute(
"DELETE FROM `oxuser` where OXID = 'oxdefaultadmin'"
);
}
}

View File

@@ -0,0 +1,52 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
abstract class BaseUnitTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* @param string $needle
* @param string $haystack
* @param string $message
*/
protected function doAssertStringContainsString($needle, $haystack, $message = '')
{
if (method_exists($this, 'assertStringContainsString')) {
parent::assertStringContainsString($needle, $haystack, $message);
} else {
parent::assertContains($needle, $haystack, $message);
}
}
/**
* @param string $needle
* @param string $haystack
* @param string $message
*/
protected function doAssertStringNotContainsString($needle, $haystack, $message = '')
{
if (method_exists($this, 'assertStringNotContainsString')) {
parent::assertStringNotContainsString($needle, $haystack, $message);
} else {
parent::assertNotContains($needle, $haystack, $message);
}
}
}

View File

@@ -0,0 +1,114 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Component;
use OxidEsales\Eshop\Application\Component\BasketComponent;
class BasketComponentTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function providerActionExpressCheckoutFromDetailsPage()
{
$url = $this->getConfig()->getCurrentShopUrl(false) . 'index.php?cl=start';
return array(
// Article valid
array(true, 1, 'oepaypalexpresscheckoutdispatcher?fnc=setExpressCheckout&displayCartInPayPal=0&oePayPalCancelURL=' . urlencode($url)),
// Article not valid
array(false, 1, null),
// Article not not valid- amount is zero
array(false, 0, 'start?')
);
}
/**
* Checks if action returns correct url when article is valid and is not valid
*
* @param $isArticleValid
* @param $expectedUrl
* @param $articleAmount
*
* @dataProvider providerActionExpressCheckoutFromDetailsPage
*/
public function testActionExpressCheckoutFromDetailsPage($isArticleValid, $articleAmount, $expectedUrl)
{
$this->getConfig()->setConfigParam('blSeoMode', false);
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutValidator::class);
$mockBuilder->setMethods(['isArticleValid']);
$validator = $mockBuilder->getMock();
$validator->expects($this->any())->method('isArticleValid')->will($this->returnValue($isArticleValid));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutCurrentItem::class);
$mockBuilder->setMethods(['getArticleAmount']);
$currentItem = $mockBuilder->getMock();
$currentItem->expects($this->any())->method('getArticleAmount')->will($this->returnValue($articleAmount));
/** @var BasketComponent $cmpBasket */
$mockBuilder = $this->getMockBuilder(BasketComponent::class);
$mockBuilder->setMethods(['getValidator', 'getCurrentArticle']);
$cmpBasket = $mockBuilder->getMock();
$cmpBasket->expects($this->any())->method('getValidator')->will($this->returnValue($validator));
$cmpBasket->expects($this->any())->method('getCurrentArticle')->will($this->returnValue($currentItem));
$this->assertEquals($expectedUrl, $cmpBasket->actionExpressCheckoutFromDetailsPage());
}
/**
* Checks if action returns correct url with cancel URL
*/
public function testActionExpressCheckoutFromDetailsPage_CheckCancelUrl()
{
$this->getConfig()->setConfigParam('blSeoMode', false);
$url = $this->getConfig()->getCurrentShopUrl(false) . 'index.php?cl=start';
$cancelURL = urlencode($url);
$expectedURL = 'oepaypalexpresscheckoutdispatcher?fnc=setExpressCheckout&displayCartInPayPal=0&oePayPalCancelURL=' . $cancelURL;
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutValidator::class);
$mockBuilder->setMethods(['isArticleValid']);
$validator = $mockBuilder->getMock();
$validator->expects($this->any())->method('isArticleValid')->will($this->returnValue(true));
/** @var BasketComponent $cmpBasket */
$mockBuilder = $this->getMockBuilder(BasketComponent::class);
$mockBuilder->setMethods(['getValidator']);
$cmpBasket = $mockBuilder->getMock();
$cmpBasket->expects($this->any())->method('getValidator')->will($this->returnValue($validator));
$this->assertEquals($expectedURL, $cmpBasket->actionExpressCheckoutFromDetailsPage());
}
/**
* Checks if action returns correct URL part
*/
public function testActionNotAddToBasketAndGoToCheckout()
{
$this->getConfig()->setConfigParam('blSeoMode', false);
$url = $this->getConfig()->getCurrentShopUrl(false) . 'index.php?cl=start';
$cancelURL = urlencode($url);
$expectedUrl = 'oepaypalexpresscheckoutdispatcher?fnc=setExpressCheckout&displayCartInPayPal=0&oePayPalCancelURL=' . $cancelURL;
$cmpBasket = oxNew(BasketComponent::class);
$this->assertEquals($expectedUrl, $cmpBasket->actionNotAddToBasketAndGoToCheckout());
}
}

View File

@@ -0,0 +1,135 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Component\Widget;
class ArticleDetailsTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
protected function createDetailsMock($articleInfo, $showECSPopUp = 0)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Component\BasketComponent::class);
$mockBuilder->setMethods(['getCurrentArticleInfo', 'shopECSPopUp']);
$basketComponent = $mockBuilder->getMock();
$basketComponent->expects($this->any())->method('getCurrentArticleInfo')->will($this->returnValue($articleInfo));
$basketComponent->expects($this->any())->method('shopECSPopUp')->will($this->returnValue($showECSPopUp));
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Component\Widget\ArticleDetails::class);
$mockBuilder->setMethods(['oePayPalGetRequest', 'getComponent']);
$details = $mockBuilder->getMock();
$details->expects($this->any())->method('getComponent')->will($this->returnValue($basketComponent));
return $details;
}
public function providerOePayPalGetArticleAmount()
{
return array(
// Given amount 5
array(array('am' => 5), 5),
// Not given any amount
array('', 1)
);
}
/**
* Tests if returns correct amount
*
* @param $articleInfo
* @param $expectedResult
*
* @dataProvider providerOePayPalGetArticleAmount
*/
public function testOePayPalGetArticleAmount($articleInfo, $expectedResult)
{
$details = $this->createDetailsMock($articleInfo);
$this->assertEquals($expectedResult, $details->oePayPalGetArticleAmount());
}
public function providerOePayPalShowECSPopup()
{
return array(
array(true, true),
array(false, false),
array('', false),
);
}
/**
* Tests if function gets parameter and returns correct result
*
* @param $showPopUp
* @param $expectedResult
*
* @dataProvider providerOePayPalShowECSPopup
*/
public function testOePayPalShowECSPopup($showPopUp, $expectedResult)
{
$details = $this->createDetailsMock(array(), $showPopUp);
$this->assertEquals($expectedResult, $details->oePayPalShowECSPopup());
}
public function providerOePayPalGetPersistentParam()
{
return array(
array(array('persparam' => array('details' => 'aa')), 'aa'),
array(array('persparam' => null), null),
);
}
/**
* Tests if function returns correct persistent param
*
* @param $articleInfo
* @param $expectedResult
*
* @dataProvider providerOePayPalGetPersistentParam
*/
public function testOePayPalGetPersistentParam($articleInfo, $expectedResult)
{
$details = $this->createDetailsMock($articleInfo);
$this->assertEquals($expectedResult, $details->oePayPalGetPersistentParam());
}
public function providerOePayPalGetSelection()
{
return array(
array(array('sel' => array(1, 0)), array(1, 0)),
array(array('sel' => null), null),
);
}
/**
* Tests if returns correct selection lists values
*
* @param $articleInfo
* @param $expectedResult
*
* @dataProvider providerOePayPalGetSelection
*/
public function testOePayPalGetSelection($articleInfo, $expectedResult)
{
$details = $this->createDetailsMock($articleInfo);
$this->assertEquals($expectedResult, $details->oePayPalGetSelection());
}
}

View File

@@ -0,0 +1,174 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Controller\Admin;
class DeliverySetMainTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
protected function tearDown(): void
{
parent::tearDown();
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute("delete from oxconfig where oxvarname = 'sOEPayPalMECDefaultShippingId' and oxmodule = 'module:oepaypal'");
}
/**
* Provides with different shipping ids to be set as already stored and result if match current shipment.
*/
public function providerRender_DefaultShippingSet()
{
return array(
// Same delivery stored as current.
array('standard', true),
// Different delivery stored as current.
array('standard2', false),
);
}
/**
* Test if checkbox value for PayPal mobile delivery set has correct value.
*
* @dataProvider providerRender_DefaultShippingSet
*/
public function testRender_DefaultShippingSet($mobileECDefaultShippingId, $markAsDefaultPaymentExpected)
{
$deliverySetId = 'standard';
$payPalModuleId = 'module:oepaypal';
$this->getConfig()->saveShopConfVar('string', 'sOEPayPalMECDefaultShippingId', $mobileECDefaultShippingId, null, $payPalModuleId);
$payPalDeliverySet_Main = oxNew(\OxidEsales\Eshop\Application\Controller\Admin\DeliverySetMain::class);
$payPalDeliverySet_Main->setEditObjectId($deliverySetId);
$payPalDeliverySet_Main->render();
$viewData = $payPalDeliverySet_Main->getViewData();
$this->assertEquals($markAsDefaultPaymentExpected, $viewData['isPayPalDefaultMobilePayment']);
}
/**
*/
public function testSave_SameShippingIdExistsDeliverySetMarkedAsSet_ShippingIdSame()
{
$this->setRequestParameter('isPayPalDefaultMobilePayment', true);
$payPalDeliverySet_Main = $this->getDeliverySet();
$deliverySetId1 = $payPalDeliverySet_Main->getEditObjectId();
$payPalModuleId = 'module:oepaypal';
$this->getConfig()->saveShopConfVar('string', 'sOEPayPalMECDefaultShippingId', $deliverySetId1, null, $payPalModuleId);
$payPalDeliverySet_Main = $this->getDeliverySet($deliverySetId1);
$payPalConfig = new \OxidEsales\PayPalModule\Core\Config();
$mobileECDefaultShippingId = $payPalConfig->getMobileECDefaultShippingId();
$this->assertEquals($deliverySetId1, $mobileECDefaultShippingId);
}
/**
*/
public function testSave_NotSameShippingIdExistsDeliverySetMarkedAsSet_ShippingIdNew()
{
$this->setRequestParameter('isPayPalDefaultMobilePayment', true);
$payPalModuleId = 'module:oepaypal';
$this->getConfig()->saveShopConfVar('string', 'sOEPayPalMECDefaultShippingId', 'standard', null, $payPalModuleId);
$payPalDeliverySet_Main = $this->getDeliverySet();
$deliverySetId2 = $payPalDeliverySet_Main->getEditObjectId();
$payPalConfig = new \OxidEsales\PayPalModule\Core\Config();
$mobileECDefaultShippingId = $payPalConfig->getMobileECDefaultShippingId();
$this->assertEquals($deliverySetId2, $mobileECDefaultShippingId);
}
/**
*/
public function testSave_ShippingIdDoNotExistsDeliverySetMarkedAsSet_ShippingIdNew()
{
$this->setRequestParameter('isPayPalDefaultMobilePayment', true);
$payPalDeliverySet_Main = $this->getDeliverySet();
$deliverySetId2 = $payPalDeliverySet_Main->getEditObjectId();
$payPalConfig = new \OxidEsales\PayPalModule\Core\Config();
$mobileECDefaultShippingId = $payPalConfig->getMobileECDefaultShippingId();
$this->assertEquals($deliverySetId2, $mobileECDefaultShippingId);
}
/**
*/
public function testSave_SameShippingIdExistsDeliverySetNotMarkedAsSet_ShippingIdCleared()
{
$payPalDeliverySet_Main = $this->getDeliverySet();
$deliverySetId1 = $payPalDeliverySet_Main->getEditObjectId();
$payPalModuleId = 'module:oepaypal';
$this->getConfig()->saveShopConfVar('string', 'sOEPayPalMECDefaultShippingId', $deliverySetId1, null, $payPalModuleId);
$payPalDeliverySet_Main = $this->getDeliverySet($deliverySetId1);
$payPalConfig = new \OxidEsales\PayPalModule\Core\Config();
$mobileECDefaultShippingId = $payPalConfig->getMobileECDefaultShippingId();
$this->assertEquals('', $mobileECDefaultShippingId);
}
/**
*/
public function testSave_NotSameShippingIdExistsDeliverySetNotMarkedAsSet_ShippingIdSame()
{
$payPalModuleId = 'module:oepaypal';
$this->getConfig()->saveShopConfVar('string', 'sOEPayPalMECDefaultShippingId', 'standard', null, $payPalModuleId);
$payPalDeliverySet_Main = $this->getDeliverySet();
$deliverySetId2 = $payPalDeliverySet_Main->getEditObjectId();
$payPalConfig = new \OxidEsales\PayPalModule\Core\Config();
$mobileECDefaultShippingId = $payPalConfig->getMobileECDefaultShippingId();
$this->assertEquals('standard', $mobileECDefaultShippingId);
}
/**
*/
public function testSave_ShippingIdDoNotExistsDeliverySetNotMarkedAsSet_ShippingIdEmpty()
{
$payPalDeliverySet_Main = $this->getDeliverySet();
$payPalConfig = new \OxidEsales\PayPalModule\Core\Config();
$mobileECDefaultShippingId = $payPalConfig->getMobileECDefaultShippingId();
$this->assertEquals('', $mobileECDefaultShippingId);
}
/**
*/
protected function getDeliverySet($deliverySetid = -1)
{
$payPalDeliverySet_Main = oxNew(\OxidEsales\PayPalModule\Controller\Admin\DeliverySetMain::class);
$payPalDeliverySet_Main->setEditObjectId($deliverySetid);
$payPalDeliverySet_Main->save();
return $payPalDeliverySet_Main;
}
}

View File

@@ -0,0 +1,128 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Controller\Admin;
use OxidEsales\Eshop\Application\Model\Order;
class OrderPayPalTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Setup: Prepare data - create need tables
*/
protected function setUp(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_order`');
}
/**
* Adds order to oepaypal_order and oxorder tables and checks if order is created using current PayPal module.
* Expected result- true
*/
public function testIsNewPayPalOrder_True()
{
$soxId = '_testOrderId';
$payPalOrderModel = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$payPalOrderModel->setOrderId($soxId);
$payPalOrderModel->save();
$payPalOrderModel->load();
$mockBuilder = $this->getMockBuilder(Order::class);
$mockBuilder->setMethods(['getPayPalOrder']);
$payPalOxOrder = $mockBuilder->getMock();
$payPalOxOrder->expects($this->any())->method('getPayPalOrder')->will($this->returnValue($payPalOrderModel));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Controller\Admin\OrderController::class);
$mockBuilder->setMethods(['getEditObject', 'isPayPalOrder']);
$payPalOrder = $mockBuilder->getMock();
$payPalOrder->expects($this->any())->method('getEditObject')->will($this->returnValue($payPalOxOrder));
$payPalOrder->expects($this->once())->method('isPayPalOrder')->will($this->returnValue(true));
$this->assertTrue($payPalOrder->isNewPayPalOrder());
}
/**
* Checks if order is created using current PayPal module.
* Expected result- false
*/
public function testIsNewPayPalOrder_False()
{
$soxId = '_testOrderId';
$payPalOrderModel = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$payPalOrderModel->setOrderId($soxId);
$payPalOrderModel->save();
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Order::class);
$mockBuilder->setMethods(['getPayPalOrder']);
$payPalOxOrder = $mockBuilder->getMock();
$payPalOxOrder->expects($this->any())->method('getPayPalOrder')->will($this->returnValue($payPalOrderModel));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Controller\Admin\OrderController::class);
$mockBuilder->setMethods(['getEditObject', 'isPayPalOrder']);
$payPalOrder = $mockBuilder->getMock();
$payPalOrder->expects($this->any())->method('getEditObject')->will($this->returnValue($payPalOxOrder));
$payPalOrder->expects($this->once())->method('isPayPalOrder')->will($this->returnValue(false));
$this->assertFalse($payPalOrder->isNewPayPalOrder());
}
/**
* Checks if order was made using PayPal payment method.
* Expected result- true
*/
public function testIsPayPalOrder_True()
{
$payPalOrder = new \OxidEsales\PayPalModule\Controller\Admin\OrderController();
$soxId = '_testOrderId';
$session = oxNew(\OxidEsales\Eshop\Core\Session::class);
$session->setVariable('saved_oxid', $soxId);
$order = oxNew(\OxidEsales\Eshop\Application\Model\Order::class);
$order->setId($soxId);
$order->oxorder__oxpaymenttype = new \OxidEsales\Eshop\Core\Field('oxidpaypal');
$order->save();
$this->assertTrue($payPalOrder->isPayPalOrder());
}
/**
* Checks if order was made using PayPal payment method.
* Expected result- false
*/
public function testIsPayPalOrder_False()
{
$payPalOrder = new \OxidEsales\PayPalModule\Controller\Admin\OrderController();
$soxId = '_testOrderId';
$session = oxNew(\OxidEsales\Eshop\Core\Session::class);
$session->setVariable('saved_oxid', $soxId);
$order = oxNew(\OxidEsales\Eshop\Application\Model\Order::class);
$order->setId($soxId);
$order->oxorder__oxpaymenttype = new \OxidEsales\Eshop\Core\Field('other');
$order->save();
$this->assertFalse($payPalOrder->isPayPalOrder());
}
}

View File

@@ -0,0 +1,93 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Controller;
/**
* Testing OxidEsales\PayPalModule\Controller\FrontendController class.
*/
class FrontendControllerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Test case for \OxidEsales\PayPalModule\Controller\FrontendController::getRequest()
*/
public function testGetRequest()
{
$controller = new \OxidEsales\PayPalModule\Controller\FrontendController();
$this->assertTrue($controller->getRequest() instanceof \OxidEsales\PayPalModule\Core\Request);
}
/**
* Test case for \OxidEsales\PayPalModule\Controller\FrontendController::getLogger()
*/
public function testGetLogger()
{
$controller = new \OxidEsales\PayPalModule\Controller\FrontendController();
$this->assertTrue($controller->getLogger() instanceof \OxidEsales\PayPalModule\Core\Logger);
}
/**
* Test case for \OxidEsales\PayPalModule\Controller\FrontendController::getPayPalConfig()
*/
public function testGetPayPalConfig()
{
$controller = new \OxidEsales\PayPalModule\Controller\FrontendController();
$this->assertTrue($controller->getPayPalConfig() instanceof \OxidEsales\PayPalModule\Core\Config);
}
/**
* Test case for \OxidEsales\PayPalModule\Controller\FrontendController::log()
*/
public function testLog_LoggingEnabled()
{
$this->getConfig()->setConfigParam('blPayPalLoggerEnabled', true);
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Logger::class);
$mockBuilder->setMethods(['log']);
$payPalLogger = $mockBuilder->getMock();
$payPalLogger->expects($this->once())->method('log');
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Controller\FrontendController::class);
$mockBuilder->setMethods(['getLogger']);
$controller = $mockBuilder->getMock();
$controller->expects($this->once())->method('getLogger')->will($this->returnValue($payPalLogger));
$controller->log('logMessage');
}
/**
* Test case for \OxidEsales\PayPalModule\Controller\FrontendController::log()
*/
public function testLog_LoggingDisabled()
{
$this->getConfig()->setConfigParam('blPayPalLoggerEnabled', false);
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Logger::class);
$mockBuilder->setMethods(['log']);
$payPalLogger = $mockBuilder->getMock();
$payPalLogger->expects($this->never())->method('log');
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Controller\FrontendController::class);
$mockBuilder->setMethods(['getLogger']);
$controller = $mockBuilder->getMock();
$controller->expects($this->never())->method('getLogger')->will($this->returnValue($payPalLogger));
$controller->log('logMessage');
}
}

View File

@@ -0,0 +1,51 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Controller;
/**
* Testing \OxidEsales\PayPalModule\Controller\IPNHandler class.
*/
class IPNHandlerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function testGetPayPalRequest()
{
$payPalHandler = new \OxidEsales\PayPalModule\Controller\IPNHandler();
$payPalRequest = $payPalHandler->getPayPalRequest();
$this->assertTrue(is_a($payPalRequest, \OxidEsales\PayPalModule\Core\Request::class));
}
/**
* Test case for \OxidEsales\PayPalModule\Controller\IPNHandler::handleRequest()
* Handler should return false if called without PayPal request data.
*/
public function testHandleRequest_emptyData_false()
{
$payPalIPNHandler = new \OxidEsales\PayPalModule\Controller\IPNHandler();
$payPalIPNHandler->handleRequest();
$logHelper = new \OxidEsales\PayPalModule\Tests\Unit\PayPalLogHelper();
$logData = $logHelper->getLogData();
$lastLogItem = end($logData);
$requestHandled = $lastLogItem->data['Result'] == 'true';
$this->assertEquals(false, $requestHandled);
}
}

View File

@@ -0,0 +1,141 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Controller;
use OxidEsales\Eshop\Application\Controller\OrderController;
use OxidEsales\PayPalModule\Tests\Unit\AdminUserTrait;
if (!class_exists('oePayPalOrder_parent')) {
class oePayPalOrder_parent extends \OxidEsales\Eshop\Application\Controller\OrderController
{
}
}
/**
* Testing oePayPaleOrder class.
*/
class OrderControllerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
use AdminUserTrait;
/**
* Tear down the fixture.
*/
protected function tearDown(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDB()->execute("delete from oxpayments where OXID = 'oxidpaypal' ");
$this->cleanUpTable('oxuser', 'oxid');
parent::tearDown();
}
/**
* Test case for OrderController::isPayPal()
*/
public function testIsPayPal()
{
$view = oxNew(OrderController::class);
$this->getSession()->setVariable("paymentid", "oxidpaypal");
$this->assertTrue($view->isPayPal());
$this->getSession()->setVariable("paymentid", "testPayment");
$this->assertFalse($view->isPayPal());
}
/**
* Data provider for getUser test
*
* @return array
*/
public function providerGetUser()
{
return array(
array('oxidpaypal', '_testPayPalUser', 'oxdefaultadmin', '_testPayPalUser'),
array('oxidpaypal', null, 'oxdefaultadmin', 'oxdefaultadmin'),
array('nonpaypalpayment', '_testPayPalUser', 'oxdefaultadmin', 'oxdefaultadmin'),
);
}
/**
* PayPal active, PayPal user is set, PayPal user loaded
*
* @dataProvider providerGetUser
*/
public function testGetUser($paymentId, $payPalUserId, $defaultUserId, $expectedUserId)
{
$user = oxNew(\OxidEsales\Eshop\Application\Model\User::class);
$user->setId($payPalUserId);
$user->save();
$this->getSession()->setVariable("paymentid", $paymentId);
$this->getSession()->setVariable("oepaypal-userId", $payPalUserId);
$this->getSession()->setVariable('usr', $defaultUserId);
$order = oxNew(\OxidEsales\Eshop\Application\Controller\OrderController::class);
$order->setUser(null);
$user = $order->getUser();
$this->assertEquals($expectedUserId, $user->oxuser__oxid->value);
}
/**
* PayPal active, PayPal user is set, PayPal user loaded
*
* @dataProvider providerGetUser
*/
public function testGetUser_NonExistingPayPalUser_DefaultUserReturned()
{
$this->getSession()->setVariable("paymentid", 'oxidpaypal');
$this->getSession()->setVariable("oepaypal-userId", 'nonExistingUser');
$this->getSession()->setVariable('usr', 'oxdefaultadmin');
$order = oxNew(\OxidEsales\Eshop\Application\Controller\OrderController::class);
$user = $order->getUser();
$this->assertEquals('oxdefaultadmin', $user->oxuser__oxid->value);
}
/**
* Test case for OrderController::getPayment()
*/
public function testGetPayment()
{
$this->getSession()->setVariable("oepaypal", "0");
$view = oxNew(\OxidEsales\Eshop\Application\Controller\OrderController::class);
$payment = $view->getPayment();
$this->assertFalse($payment);
$this->getSession()->setVariable("paymentid", "oxidpaypal");
$query = "INSERT INTO `oxpayments` (`OXID`, `OXACTIVE`, `OXDESC`) VALUES ('oxidpaypal', 1, 'PayPal')";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query);
$view = oxNew(\OxidEsales\Eshop\Application\Controller\OrderController::class);
$payment = $view->getPayment();
$this->assertNotNull($payment);
$this->assertEquals("oxidpaypal", $payment->getId());
}
}

View File

@@ -0,0 +1,93 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Controller;
use OxidEsales\Eshop\Application\Controller\PaymentController;
/**
* Testing PaymentController class.
*/
class PaymentControllerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Test case for PaymentController::validatePayment()
* Test validatePayment
*/
public function testValidatePayment()
{
// forcing payment id
$this->setRequestParameter("paymentid", null);
$view = oxNew(PaymentController::class);
$this->assertNull($view->validatePayment());
// forcing payment id
$this->setRequestParameter("paymentid", "oxidpaypal");
$this->setRequestParameter("displayCartInPayPal", 1);
$view = new \OxidEsales\PayPalModule\Controller\PaymentController();
$this->assertEquals("oepaypalstandarddispatcher?fnc=setExpressCheckout&displayCartInPayPal=1", $view->validatePayment());
$this->assertEquals("oxidpaypal", $this->getSession()->getVariable("paymentid"));
}
/**
* Test, that the method validatePayment if the order was already checked by paypal.
*/
public function testValidatePaymentIfCheckedByPayPal()
{
// forcing payment id
$this->setRequestParameter("paymentid", "oxidpaypal");
$this->setRequestParameter("displayCartInPayPal", 1);
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Controller\PaymentController::class);
$mockBuilder->setMethods(['isConfirmedByPayPal']);
$view = $mockBuilder->getMock();
$view->expects($this->once())->method("isConfirmedByPayPal")->will($this->returnValue(true));
$this->assertNull($view->validatePayment());
$this->assertNull($this->getSession()->getVariable("paymentid"));
}
/**
* Test case for PaymentController::isConfirmedByPayPal()
* Test isConfirmedByPayPal
*/
public function testIsConfirmedByPayPal()
{
// forcing payment id
$this->setRequestParameter("paymentid", "oxidpaypal");
$this->getSession()->setVariable("oepaypal-basketAmount", 129.00);
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Price::class);
$mockBuilder->setMethods(['getBruttoPrice']);
$price = $mockBuilder->getMock();
$price->expects($this->once())->method("getBruttoPrice")->will($this->returnValue(129.00));
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Basket::class);
$mockBuilder->setMethods(['getPrice']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method("getPrice")->will($this->returnValue($price));
$view = new \OxidEsales\PayPalModule\Controller\PaymentController();
$this->assertTrue($view->isConfirmedByPayPal($basket));
}
}

View File

@@ -0,0 +1,212 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Controller;
class StandardDispatcherTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Set up
*/
protected function setUp(): void
{
parent::setUp();
// fix for state ID compatability between editions
$sqlState = "REPLACE INTO `oxstates` (`OXID`, `OXCOUNTRYID`, `OXTITLE`, `OXISOALPHA2`, `OXTITLE_1`, `OXTITLE_2`, `OXTITLE_3`, `OXTIMESTAMP`) " .
"VALUES ('333', '8f241f11096877ac0.98748826', 'USA last state', 'SS', 'USA last state', '', '', CURRENT_TIMESTAMP);";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($sqlState);
}
public function testSetGetPayPalCheckoutService()
{
$payPalCheckoutService = new \OxidEsales\PayPalModule\Core\PayPalService();
$payPalStandardDispatcher = new \OxidEsales\PayPalModule\Controller\StandardDispatcher();
$payPalStandardDispatcher->setPayPalCheckoutService($payPalCheckoutService);
$this->assertEquals($payPalCheckoutService, $payPalStandardDispatcher->getPayPalCheckoutService(), 'Getter should return what is set in setter.');
}
public function testGetPayPalCheckoutService()
{
$payPalStandardDispatcher = new \OxidEsales\PayPalModule\Controller\StandardDispatcher();
$this->assertTrue(
$payPalStandardDispatcher->getPayPalCheckoutService() instanceof \OxidEsales\PayPalModule\Core\PayPalService,
'Getter should create correct type of object.'
);
}
/**
* Test case for oepaypalstandarddispatcher::getExpressCheckoutDetails()
*/
public function testGetExpressCheckoutDetails()
{
// preparing session, inputs etc.
$session = $this->getSession();
$session->setVariable("oepaypal-token", "111");
$detailsData = ["PAYERID" => "111"];
$details = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$details->setData($detailsData);
// preparing config
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Config::class);
$mockBuilder->setMethods(['finalizeOrderOnPayPalSide']);
$payPalConfig = $mockBuilder->getMock();
$payPalConfig->expects($this->once())->method('finalizeOrderOnPayPalSide')->will($this->returnValue(true));
// preparing service
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
$mockBuilder->setMethods(['getExpressCheckoutDetails']);
$payPalService = $mockBuilder->getMock();
$payPalService->expects($this->once())->method("getExpressCheckoutDetails")->will($this->returnValue($details));
// prepare user
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\User::class);
$mockBuilder->setMethods(['getEncodedDeliveryAddress']);
$user = $mockBuilder->getMock();
$user->expects($this->once())->method("getEncodedDeliveryAddress")->will($this->returnValue("encodeddeliveryaddress123"));
// preparing
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Controller\StandardDispatcher::class);
$mockBuilder->setMethods(["getPayPalCheckoutService", "getPayPalConfig", "getUser"]);
$dispatcher = $mockBuilder->getMock();
$dispatcher->expects($this->once())->method("getPayPalCheckoutService")->will($this->returnValue($payPalService));
$dispatcher->expects($this->once())->method("getPayPalConfig")->will($this->returnValue($payPalConfig));
$dispatcher->expects($this->once())->method("getUser")->will($this->returnValue($user));
// testing
$this->assertEquals("order?fnc=execute&sDeliveryAddressMD5=encodeddeliveryaddress123&stoken=" . $session->getSessionChallengeToken(), $dispatcher->getExpressCheckoutDetails());
$this->assertEquals("111", $session->getVariable("oepaypal-payerId"));
}
/**
* Test case for oepaypalstandarddispatcher::getExpressCheckoutDetails()
*/
public function testGetExpressCheckoutDetailsError()
{
$excp = oxNew(\OxidEsales\Eshop\Core\Exception\StandardException::class);
// preparing config
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Config::class);
$mockBuilder->setMethods(['finalizeOrderOnPayPalSide']);
$payPalConfig = $mockBuilder->getMock();
$payPalConfig->expects($this->never())->method('finalizeOrderOnPayPalSide');
// preparing paypal service
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
$mockBuilder->setMethods(['getExpressCheckoutDetails']);
$payPalService = $mockBuilder->getMock();
$payPalService->expects($this->once())->method("getExpressCheckoutDetails")->will($this->throwException($excp));
// preparing utils view
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\UtilsView::class);
$mockBuilder->setMethods(['addErrorToDisplay']);
$utilsView = $mockBuilder->getMock();
$utilsView->expects($this->once())->method("addErrorToDisplay")->with($this->equalTo($excp));
// preparing
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Controller\StandardDispatcher::class);
$mockBuilder->setMethods(['getPayPalCheckoutService', 'getPayPalConfig', 'getUtilsView']);
$dispatcher = $mockBuilder->getMock();
$dispatcher->expects($this->once())->method("getPayPalCheckoutService")->will($this->returnValue($payPalService));
$dispatcher->expects($this->once())->method("getUtilsView")->will($this->returnValue($utilsView));
$dispatcher->expects($this->never())->method("getPayPalConfig");
// testing
$this->assertEquals("payment", $dispatcher->getExpressCheckoutDetails());
}
/**
* Test case for \OxidEsales\PayPalModule\Controller\Dispatcher::setExpressCheckout()
* Main functionality
*/
public function testSetExpressCheckout_onSuccess()
{
$result = new \OxidEsales\PayPalModule\Model\Response\ResponseSetExpressCheckout();
$result->setData(array('TOKEN' => 'token'));
$url = "https://www.sandbox.paypal.com/cgi-bin/webscr&cmd=_express-checkout&token=token";
//utils
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Utils::class);
$mockBuilder->setMethods(['redirect']);
$utils = $mockBuilder->getMock();
$utils->expects($this->once())->method("redirect")->with($this->equalTo($url), $this->equalTo(false));
//config
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Config::class);
$mockBuilder->setMethods(['getPayPalCommunicationUrl']);
$payPalConfig = $mockBuilder->getMock();
$payPalConfig->expects($this->once())->method("getPayPalCommunicationUrl")->with($this->equalTo($result->getToken()))->will($this->returnValue($url));
// preparing service
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
$mockBuilder->setMethods(['setExpressCheckout', 'setParameter']);
$payPalService = $mockBuilder->getMock();
$payPalService->expects($this->once())->method("setExpressCheckout")->will($this->returnValue($result));
// preparing
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Controller\StandardDispatcher::class);
$mockBuilder->setMethods(['getPayPalCheckoutService', 'getUtils', 'getPayPalConfig']);
$dispatcher = $mockBuilder->getMock();
$dispatcher->expects($this->once())->method("getPayPalCheckoutService")->will($this->returnValue($payPalService));
$dispatcher->expects($this->any())->method("getPayPalConfig")->will($this->returnValue($payPalConfig));
$dispatcher->expects($this->once())->method("getUtils")->will($this->returnValue($utils));
// testing
$dispatcher->setExpressCheckout();
}
/**
* Test case for \OxidEsales\PayPalModule\Controller\Dispatcher::setExpressCheckout()
* On error
*/
public function testSetExpressCheckout_onError()
{
$excp = oxNew(\OxidEsales\Eshop\Core\Exception\StandardException::class);
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Config::class);
$mockBuilder->setMethods(['getPaypalUrl']);
$payPalConfig = $mockBuilder->getMock();
$payPalConfig->expects($this->never())->method("getPaypalUrl");
// preparing paypal service
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
$mockBuilder->setMethods(['setExpressCheckout']);
$payPalService= $mockBuilder->getMock();
$payPalService->expects($this->once())->method("setExpressCheckout")->will($this->throwException($excp));
// preparing utils view
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\UtilsView::class);
$mockBuilder->setMethods(['addErrorToDisplay']);
$utilsView = $mockBuilder->getMock();
$utilsView->expects($this->once())->method("addErrorToDisplay")->with($this->equalTo($excp));
// preparing
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Controller\StandardDispatcher::class);
$mockBuilder->setMethods(['getPayPalCheckoutService', 'getUtilsView']);
$dispatcher = $mockBuilder->getMock();
$dispatcher->expects($this->once())->method("getPayPalCheckoutService")->will($this->returnValue($payPalService));
$dispatcher->expects($this->once())->method("getUtilsView")->will($this->returnValue($utilsView));
// testing
$this->assertEquals("basket", $dispatcher->setExpressCheckout());
}
}

View File

@@ -0,0 +1,82 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Controller;
/**
* Testing WrappingController class.
*/
class WrappingControllerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Test case for WrappingController::isPayPal()
*/
public function testIsPayPal()
{
$view = oxNew(\OxidEsales\Eshop\Application\Controller\WrappingController::class);
$this->getSession()->setVariable("paymentid", "oxidpaypal");
$this->assertTrue($view->isPayPal());
$this->getSession()->setVariable("paymentid", "notoxidpaypal");
$this->assertFalse($view->isPayPal());
}
/**
* Test case for WrappingController::changeWrapping() - express chekcout
*/
public function testChangeWrapping_expressCheckout()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Controller\WrappingController::class);
$mockBuilder->setMethods(['isPayPal']);
$view = $mockBuilder->getMock();
$view->expects($this->once())->method("isPayPal")->will($this->returnValue(true));
$this->getSession()->setVariable("oepaypal", "2");
$this->assertEquals("basket", $view->changeWrapping());
}
/**
* Test case for WrappingController::changeWrapping() - standart chekout
*/
public function testChangeWrapping_standardCheckout()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Controller\WrappingController::class);
$mockBuilder->setMethods(['isPayPal']);
$view = $mockBuilder->getMock();
$view->expects($this->once())->method("isPayPal")->will($this->returnValue(true));
$this->getSession()->setVariable("oepaypal", "1");
$this->assertEquals("payment", $view->changeWrapping());
}
/**
* Test case for WrappingController::changeWrapping() - PayPal not active
*/
public function testChangeWrapping_PayPalNotActive()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Controller\WrappingController::class);
$mockBuilder->setMethods(['isPayPal']);
$view = $mockBuilder->getMock();
$view->expects($this->once())->method("isPayPal")->will($this->returnValue(false));
$this->assertEquals("order", $view->changeWrapping());
}
}

View File

@@ -0,0 +1,361 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
use OxidEsales\PayPalModule\Core\Caller;
use OxidEsales\PayPalModule\Core\Exception\PayPalResponseException;
use OxidEsales\PayPalModule\Core\Logger;
/**
* Testing PayPal caller class.
*/
class CallerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::setParameter()
*/
public function testSetParameter_setParameter_addedToSetOfParameters()
{
$service = new \OxidEsales\PayPalModule\Core\Caller();
$service->setParameter("testParam", "testValue");
$parameters = array("testParam" => "testValue");
$this->assertEquals($parameters, $service->getParameters());
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::setParameters()
*/
public function testSetParameters_setOneOrMoreParameters_addedToSetOfParameters()
{
$service = new \OxidEsales\PayPalModule\Core\Caller();
$service->setParameter("testParam", "testValue");
$service->setParameters(array("testParam" => "testValue2", "testParam3" => "testValue3", "testParam4" => "testValue4"));
$service->setParameter("testParam4", "testValue5");
$result["testParam"] = "testValue2";
$result["testParam3"] = "testValue3";
$result["testParam4"] = "testValue5";
$this->assertEquals($result, $service->getParameters());
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::call()
*/
public function testCall_withMethodSuccessful_returnResponseArray()
{
$params = array();
$params["testParam"] = "testValue";
$curlParams = $params;
$curlParams["METHOD"] = "testMethod";
$url = 'http://url.com';
$charset = 'latin';
$response = array('parameter', 'value');
$caller = new \OxidEsales\PayPalModule\Core\Caller();
$caller->setParameters($params);
$caller->setCurl($this->prepareCurl($response, $curlParams, $url, $charset));
$this->assertEquals($response, $caller->call("testMethod"));
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::call()
*/
public function testCall_withoutMethod_returnResponseArray()
{
$params = array();
$params["testParam"] = "testValue";
$curlParams = $params;
$url = 'http://url.com';
$charset = 'latin';
$response = array('parameter', 'value');
$caller = new \OxidEsales\PayPalModule\Core\Caller();
$caller->setParameters($params);
$caller->setCurl($this->prepareCurl($response, $curlParams, $url, $charset));
$this->assertEquals($response, $caller->call());
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::call()
*
* @dataProvider callMethodNotSuccessfulProvider
*/
public function testCall_withMethodNotSuccessful_throwException(string $status)
{
$this->expectException(PayPalResponseException::class);
$response = [
'ACK' => $status,
'L_LONGMESSAGE0' => 'message',
'L_ERRORCODE0' => 1
];
$caller = $this->prepareCaller($response);
$this->assertEquals($response, $caller->call());
}
public function callMethodNotSuccessfulProvider(): array
{
return [
['status' => 'Failure'],
['status' => 'FailureWithWarning']
];
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::call()
*
* @dataProvider callMethodWithWarningProvider
*/
public function testCall_withWarning(string $status, bool $expectException)
{
if ($expectException) {
$this->expectException(PayPalResponseException::class);
}
$response = [
'ACK' => $status,
'L_LONGMESSAGE0' => 'message',
'L_ERRORCODE0' => 1
];
$caller = $this->prepareCaller($response);
$logger = $this
->getMockBuilder(Logger::class)
->getMock();
$logger
->expects($this->at(4))
->method('setTitle')
->with('Response with warning from PayPal');
$logger
->expects($this->at(5))
->method('log')
->with($response);
$caller->setLogger($logger);
$this->assertEquals($response, $caller->call());
}
public function callMethodWithWarningProvider(): array
{
return [
[
'status' => 'SuccessWithWarning',
'expectException' => false
],
[
'status' => 'FailureWithWarning',
'expectException' => true
]
];
}
private function prepareCaller(array $response): Caller
{
$params = [
'testParam' => 'testValue'
];
$caller = new Caller();
$caller->setParameters($params);
$caller->setCurl($this->prepareCurl($response, $params, 'http://url.com', 'latin'));
return $caller;
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::getCallBackResponse()
*/
public function testGetCallBackResponse_setParameters_getResponse()
{
$params = array(
'param1' => 'value1',
'param2' => 'value2',
);
$caller = new \OxidEsales\PayPalModule\Core\Caller();
$caller->setParameters($params);
$params['METHOD'] = 'CallbackResponse';
$params = http_build_query($params);
$this->assertEquals($params, $caller->getCallBackResponse('CallbackResponse'));
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::getPayPalCurl()
*/
public function testGetCurl_notSet_returnedNewCreated()
{
$payPalCaller = new \OxidEsales\PayPalModule\Core\Caller();
$payPalCurl = $payPalCaller->getCurl();
$this->assertTrue(is_a($payPalCurl, \OxidEsales\PayPalModule\Core\Curl::class), 'Getter should create PayPal Curl object on request.');
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::getCurl()
*/
public function testSetCurl_setCurl_returnedSet()
{
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$curl->setConnectionCharset('latin');
$caller = new \OxidEsales\PayPalModule\Core\Caller();
$caller->setCurl($curl);
$curl = $caller->getCurl();
$this->assertTrue($curl instanceof \OxidEsales\PayPalModule\Core\Curl);
$this->assertEquals('latin', $curl->getConnectionCharset());
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::getPayPalCurl()
*/
public function testSetRequest_RequestDataSetAsParameters()
{
$request = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest();
$request->setData(array('param' => 'data'));
$caller = new \OxidEsales\PayPalModule\Core\Caller();
$caller->setRequest($request);
$this->assertEquals(array('param' => 'data'), $caller->getParameters());
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::getCharset()
*/
public function testGetLogger_notSet_null()
{
$caller = new \OxidEsales\PayPalModule\Core\Caller();
$this->assertNull($caller->getLogger());
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::getCharset()
*/
public function testGetLogger_setLogger_Logger()
{
$caller = new \OxidEsales\PayPalModule\Core\Caller();
$caller->setLogger(new \OxidEsales\PayPalModule\Core\Logger());
$this->assertTrue($caller->getLogger() instanceof \OxidEsales\PayPalModule\Core\Logger);
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::log()
*/
public function testLog_notSetLogger_LoggerNotUsed()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Caller::class);
$mockBuilder->setMethods(['getLogger']);
$caller = $mockBuilder->getMock();
$caller->expects($this->once())->method('getLogger')->will($this->returnValue(null));
$caller->log('logMassage');
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::log()
*/
public function testLog_setLogger_LoggerUsed()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Logger::class);
$mockBuilder->setMethods(['log']);
$logger = $mockBuilder->getMock();
$logger->expects($this->once())->method('log')->with($this->equalTo('logMassage'));
$caller = new \OxidEsales\PayPalModule\Core\Caller();
$caller->setLogger($logger);
$caller->log('logMassage');
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::log() usage in oePayPalCaller::call()
*/
public function testLogUsage_onCallMethod_atLeastOnce()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Logger::class);
$mockBuilder->setMethods(['log']);
$logger = $mockBuilder->getMock();
$logger->expects($this->atLeastOnce())->method('log');
$caller = new \OxidEsales\PayPalModule\Core\Caller();
$caller->setLogger($logger);
$caller->setParameters(array('k' => 'val'));
$caller->setCurl($this->prepareCurl(array(), array('k' => 'val'), 'http://url.com', 'utf8'));
$caller->call();
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Caller::log() usage in oePayPalCaller::getCallBackResponse()
*/
public function testLogUsage_onGetCallBackResponseMethod_atLeastOnce()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Logger::class);
$mockBuilder->setMethods(['log']);
$logger = $mockBuilder->getMock();
$logger->expects($this->atLeastOnce())->method('log');
$caller = new \OxidEsales\PayPalModule\Core\Caller();
$caller->setLogger($logger);
$caller->setParameters(array('k' => 'val'));
$caller->setCurl($this->prepareCurl(array(), array('k' => 'val'), 'http://url.com', 'utf8'));
$caller->call();
}
/**
* Prepare curl stub
*
* @param array $response response
* @param array $paramsCurl params
* @param string $url url
* @param string $charset charset
*
* @return \OxidEsales\PayPalModule\Core\Curl
*/
protected function prepareCurl($response, $paramsCurl, $url, $charset)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Curl::class);
$mockBuilder->setMethods(['execute', 'setUrlToCall', 'setParameters', 'setDataCharset']);
$curl = $mockBuilder->getMock();
$curl->expects($this->once())->method("execute")->will($this->returnValue($response));
$curl->setDataCharset($charset);
$curl->setParameters($paramsCurl);
$curl->setUrlToCall($url);
return $curl;
}
}

View File

@@ -0,0 +1,762 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
use OxidEsales\Eshop\Core\Language;
use OxidEsales\Eshop\Core\Utils;
/**
* Testing \OxidEsales\PayPalModule\Core\Config class.
*/
class ConfigTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Cleans oxConfig table and calls parent::tearDown();
*/
protected function tearDown(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute("delete from oxconfig where oxvarname like 'paypal_%'");
parent::tearDown();
}
/**
* Cleans out the images that are created before image tests
*/
protected function cleanUp()
{
$imgDir = $this->getConfig()->getImageDir();
if (!$shopLogo = $this->getConfig()->getConfigParam('sShopLogo')) {
return;
}
$logoDir = $imgDir . "resized_$shopLogo";
if (!file_exists($logoDir)) {
return;
}
unlink($logoDir);
}
/**
* Check if gets correct module id.
*/
public function testGetModuleId()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$PayPalId = $config->getModuleId();
$this->assertEquals('oepaypal', $PayPalId, 'PayPal module should be oepaypal not ' . $PayPalId);
}
public function providerGetBrandName()
{
return array(
array('', '', ''),
array('', 'testShopName', 'testShopName'),
array('testPayPalShopName', 'testBrandName', 'testPayPalShopName'),
array('testPayPalShopName', '', 'testPayPalShopName'),
);
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Config::getBrandName()
*
* @dataProvider providerGetBrandName
*
* @param string $paramName
* @param string $shopName
* @param string $resultName
*/
public function testGetBrandName($paramName, $shopName, $resultName)
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('sOEPayPalBrandName', $paramName);
$shop = $this->getConfig()->getActiveShop();
$shop->oxshops__oxname = new \OxidEsales\Eshop\Core\Field($shopName);
$shop->save();
$this->assertEquals($resultName, $config->getBrandName());
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Config::sendOrderInfoToPayPal()
*/
public function testSendOrderInfoToPayPal()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('blOEPayPalSendToPayPal', true);
$this->assertTrue($config->sendOrderInfoToPayPal());
$this->getConfig()->setConfigParam('blOEPayPalSendToPayPal', false);
$this->assertFalse($config->sendOrderInfoToPayPal());
}
/**
* Test case for Config::isGuestBuyEnabled()
*/
public function testIsGuestBuyEnabled()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('blOEPayPalGuestBuyRole', true);
$this->assertTrue($config->isGuestBuyEnabled());
$this->getConfig()->setConfigParam('blOEPayPalGuestBuyRole', false);
$this->assertFalse($config->isGuestBuyEnabled());
}
/**
* Test case for Config::isGiroPayEnabled()
*/
public function testIsGiroPayEnabled()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertFalse($config->isGiroPayEnabled());
}
/**
* Test case for Config::isSandboxEnabled()
*/
public function testIsSandboxEnabled()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', true);
$this->assertTrue($config->isSandboxEnabled());
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', false);
$this->assertFalse($config->isSandboxEnabled());
}
public function providerGetPayPalHost()
{
return array(
// Default PayPal sandbox host
array(true, null, null, 'api-3t.sandbox.paypal.com'),
// Default PayPal host.
array(false, null, null, 'api-3t.paypal.com'),
// Sandbox on; PayPal sandbox host NOT set; PayPal host set; Sandbox default host return.
array(true, null, 'paypalApiUrl', 'api-3t.sandbox.paypal.com'),
// Sandbox off; PayPal sandbox host set; PayPal host NOT set; PayPal default host return.
array(false, 'sandboxApiUrl', null, 'api-3t.paypal.com'),
// Sandbox on; PayPal sandbox host set; PayPal host set; PayPal set sandbox host return.
array(true, 'sandboxApiUrl', 'paypalApiUrl', 'sandboxApiUrl'),
// Sandbox off; PayPal sandbox host set; PayPal host set; PayPal set host return.
array(false, 'sandboxApiUrl', 'paypalApiUrl', 'paypalApiUrl'),
);
}
/**
* Test if return what is set in setter.
* Test ir return default value if not set in setter.
*
* @dataProvider providerGetPayPalHost
*/
public function testGetHost($sandboxEnabled, $payPalSandboxHost, $payPalHost, $result)
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', $sandboxEnabled);
if (!empty($payPalSandboxHost)) {
$config->setPayPalSandboxHost($payPalSandboxHost);
}
if (!empty($payPalHost)) {
$config->setPayPalHost($payPalHost);
}
$this->assertEquals($result, $config->getHost());
}
public function testGetPayPalHost_setWithSetter_setValue()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$config->setPayPalHost('PayPalHost');
$this->assertEquals('PayPalHost', $config->getPayPalHost(), 'Getter must return what is set in setter.');
}
public function testGetPayPalHost_default_definedClassAttribute()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals('api-3t.paypal.com', $config->getPayPalHost());
}
public function testGetPayPalHost_overrideWithConfig_configValue()
{
$this->getConfig()->setConfigParam('sPayPalHost', 'configHost');
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals('configHost', $config->getPayPalHost());
}
public function testGetPayPalSandboxHost_setWithSetter_setValue()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$config->setPayPalSandboxHost('PayPalSandboxHost');
$this->assertEquals('PayPalSandboxHost', $config->getPayPalSandboxHost());
}
public function testGetPayPalSandboxHost_default_definedClassAttribute()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals('api-3t.sandbox.paypal.com', $config->getPayPalSandboxHost());
}
public function testGetPayPalSandboxHost_overrideWithConfig_configValue()
{
$this->getConfig()->setConfigParam('sPayPalSandboxHost', 'configHost');
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals('configHost', $config->getPayPalSandboxHost());
}
public function providerGetApiUrl()
{
return array(
array(true, null, null, 'https://api-3t.sandbox.paypal.com/nvp'),
array(false, null, null, 'https://api-3t.paypal.com/nvp'),
array(true, null, 'paypalApiUrl', 'https://api-3t.sandbox.paypal.com/nvp'),
array(false, 'sandboxApiUrl', null, 'https://api-3t.paypal.com/nvp'),
array(true, 'sandboxApiUrl', 'paypalApiUrl', 'sandboxApiUrl'),
array(false, 'sandboxApiUrl', 'paypalApiUrl', 'paypalApiUrl'),
);
}
/**
* Test case for Config::getEndPointUrl()
*
* @dataProvider providerGetApiUrl
*/
public function testApiUrl($sandBoxEnabled, $sandBoxApiUrl, $apiUrl, $result)
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', $sandBoxEnabled);
if (!empty($sandBoxApiUrl)) {
$config->setPayPalSandboxApiUrl($sandBoxApiUrl);
}
if (!empty($apiUrl)) {
$config->setPayPalApiUrl($apiUrl);
}
$this->assertEquals($result, $config->getApiUrl());
}
public function testGetPayPalSandboxApiUrl_setWithSetter_setValue()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$config->setPayPalSandboxApiUrl('ApiPayPalSandboxHost');
$this->assertEquals('ApiPayPalSandboxHost', $config->getPayPalSandboxApiUrl());
}
public function testGetPayPalSandboxApiUrl_default_definedClassAttribute()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals('https://api-3t.sandbox.paypal.com/nvp', $config->getPayPalSandboxApiUrl());
}
public function testGetPayPalSandboxApiUrl_overrideWithConfig_configValue()
{
$this->getConfig()->setConfigParam('sPayPalSandboxApiUrl', 'apiConfigHost');
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals('apiConfigHost', $config->getPayPalSandboxApiUrl());
}
public function testGetPayPalApiUrl_setWithSetter_setValue()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$config->setPayPalApiUrl('ApiPayPalSandboxHost');
$this->assertEquals('ApiPayPalSandboxHost', $config->getPayPalApiUrl());
}
public function testGetPayPalApiUrl_default_definedClassAttribute()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals('https://api-3t.paypal.com/nvp', $config->getPayPalApiUrl());
}
public function testGetPayPalApiUrl_overrideWithConfig_configValue()
{
$this->getConfig()->setConfigParam('sPayPalApiUrl', 'apiConfigHost');
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals('apiConfigHost', $config->getPayPalApiUrl());
}
public function testGetPayPalSandboxUrl_setWithSetter_setValue()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$config->setPayPalSandboxUrl('ApiPayPalSandboxHost');
$this->assertEquals('ApiPayPalSandboxHost', $config->getPayPalSandboxUrl());
}
public function testGetPayPalSandboxUrl_default_definedClassAttribute()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals('https://www.sandbox.paypal.com/cgi-bin/webscr', $config->getPayPalSandboxUrl());
}
public function testGetPayPalSandboxUrl_overrideWithConfig_configValue()
{
$this->getConfig()->setConfigParam('sPayPalSandboxUrl', 'ConfigHost');
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals('ConfigHost', $config->getPayPalSandboxUrl());
}
public function testGetPayPalUrl_setWithSetter_setValue()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$config->setPayPalUrl('ApiPayPalSandboxHost');
$this->assertEquals('ApiPayPalSandboxHost', $config->getPayPalUrl());
}
public function testGetPayPalUrl_default_definedClassAttribute()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals('https://www.paypal.com/cgi-bin/webscr', $config->getPayPalUrl());
}
public function testGetPayPalUrl_overrideWithConfig_configValue()
{
$this->getConfig()->setConfigParam('sPayPalUrl', 'ConfigUrl');
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals('ConfigUrl', $config->getPayPalUrl());
}
public function providerGetPayPalCommunicationUrl()
{
return array(
array(true, null, null, 'TestToken', 'continue', 'https://www.sandbox.paypal.com/cgi-bin/webscr&cmd=_express-checkout&token=TestToken&useraction=continue'),
array(false, null, null, 'TestToken', 'commit', 'https://www.paypal.com/cgi-bin/webscr&cmd=_express-checkout&token=TestToken&useraction=commit'),
array(true, null, 'paypalApiUrl', 'TestToken1', 'commit', 'https://www.sandbox.paypal.com/cgi-bin/webscr&cmd=_express-checkout&token=TestToken1&useraction=commit'),
array(false, 'sandboxApiUrl', null, 'TestToken1', 'continue', 'https://www.paypal.com/cgi-bin/webscr&cmd=_express-checkout&token=TestToken1&useraction=continue'),
array(true, 'sandboxApiUrl', 'paypalApiUrl', 'TestToken2', 'action', 'sandboxApiUrl&cmd=_express-checkout&token=TestToken2&useraction=action'),
array(false, 'sandboxApiUrl', 'paypalApiUrl', 'TestToken2', 'action', 'paypalApiUrl&cmd=_express-checkout&token=TestToken2&useraction=action'),
);
}
/**
* Test case for Config::getUrl()
*
* @dataProvider providerGetPayPalCommunicationUrl
*/
public function testGetPayPalCommunicationUrl($sandBoxEnabled, $sandBoxApiUrl, $apiUrl, $token, $userAction, $result)
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', $sandBoxEnabled);
if (!empty($sandBoxApiUrl)) {
$config->setPayPalSandboxUrl($sandBoxApiUrl);
}
if (!empty($apiUrl)) {
$config->setPayPalUrl($apiUrl);
}
$this->assertEquals($result, $config->getPayPalCommunicationUrl($token, $userAction));
}
public function providerGetTextConfig()
{
return array(
array(true, 'text1', 'text2', 'text1'),
array(false, 'text1', 'text2', 'text2'),
);
}
/**
* Test case for Config::getPassword()
*
* @dataProvider providerGetTextConfig
*/
public function testGetPassword($sandBoxEnabled, $sandBoxPassword, $password, $result)
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', $sandBoxEnabled);
$this->getConfig()->setConfigParam('sOEPayPalSandboxPassword', $sandBoxPassword);
$this->getConfig()->setConfigParam('sOEPayPalPassword', $password);
$this->assertEquals($result, $config->getPassword());
}
/**
* Test case for Config::getUserName()
*
* @dataProvider providerGetTextConfig
*/
public function testGetUserName($sandBoxEnabled, $sandBoxUsername, $username, $result)
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', $sandBoxEnabled);
$this->getConfig()->setConfigParam('sOEPayPalSandboxUsername', $sandBoxUsername);
$this->getConfig()->setConfigParam('sOEPayPalUsername', $username);
$this->assertEquals($result, $config->getUserName());
}
/**
* Test case for Config::getSignature()
*
* @dataProvider providerGetTextConfig
*/
public function testGetSignature($sandBoxEnabled, $sandBoxSignature, $signature, $result)
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', $sandBoxEnabled);
$this->getConfig()->setConfigParam('sOEPayPalSandboxSignature', $sandBoxSignature);
$this->getConfig()->setConfigParam('sOEPayPalSignature', $signature);
$this->assertEquals($result, $config->getSignature());
}
/**
* Test case for Config::getTransactionMode()
*/
public function testGetTransactionMode()
{
$transMode = 'Sale';
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('sOEPayPalTransactionMode', $transMode);
$this->assertEquals($transMode, $config->getTransactionMode());
}
/**
* Test case for Config::isLoggingEnabled()
*/
public function testIsLoggingEnabled()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('blPayPalLoggerEnabled', true);
$this->assertTrue($config->isLoggingEnabled());
$this->getConfig()->setConfigParam('blPayPalLoggerEnabled', false);
$this->assertFalse($config->isLoggingEnabled());
}
/**
* Test case for Config::isLoggingEnabled()
*/
public function testIsExpressCheckoutInMiniBasketEnabled()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('blOEPayPalECheckoutInMiniBasket', true);
$this->assertTrue($config->isExpressCheckoutInMiniBasketEnabled());
$this->getConfig()->setConfigParam('blOEPayPalECheckoutInMiniBasket', false);
$this->assertFalse($config->isExpressCheckoutInMiniBasketEnabled());
}
public function providerGetShopLogoUrl()
{
$shopImageLocation = $this->getConfig()->getImageUrl();
return array(
array("noLogo", "logo.png", "", false),
array("shopLogo", "logo.png", "logo_ee.png", $shopImageLocation . "resized_logo.png"),
array("customLogo", "logo.png", "logo.png", $shopImageLocation . "resized_logo.png"),
array("shopLogo", "login-fb.png", "logo.png", $shopImageLocation . "login-fb.png"),
array("customLogo", "logo.png", "login-fb.png", $shopImageLocation . "login-fb.png"),
);
}
/**
* Checks if correct shop logo is returned with various options
*
* @dataProvider providerGetShopLogoUrl
*
* @param string $option
* @param string $shopLogoImage
* @param string $customLogoImage
* @param string $expected
*/
public function testGetShopLogoUrl($option, $shopLogoImage, $customLogoImage, $expected)
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam("sOEPayPalLogoImageOption", $option);
$this->getConfig()->setConfigParam("sOEPayPalCustomShopLogoImage", $customLogoImage);
$this->getConfig()->setConfigParam("sShopLogo", $shopLogoImage);
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\UtilsPic::class);
$mockBuilder->setMethods(['resizeImage']);
$utilsUrl = $mockBuilder->getMock();
$utilsUrl->expects($this->any())->method('resizeImage')->will($this->returnValue(true));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\UtilsPic::class, $utilsUrl);
$this->assertEquals($expected, $config->getLogoUrl());
$this->cleanUp();
}
/**
* Incorrect file name provider
*
* @return array
*/
public function providerGetShopLogoUrlIncorrectFilename()
{
return array(
array("shopLogo", "", "notexisting.png"),
array("customLogo", "notexisting.png", ""),
);
}
/**
* Checks that getLogoUrl returns false when filename is incorrect
*
* @dataProvider providerGetShopLogoUrlIncorrectFilename
*/
public function testGetShopLogoUrlIncorrectFilename($option, $shopLogoImage, $customLogoImage)
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam("sOEPayPalLogoImageOption", $option);
$this->getConfig()->setConfigParam("sOEPayPalCustomShopLogoImage", $customLogoImage);
$this->getConfig()->setConfigParam("sShopLogo", $shopLogoImage);
$this->assertFalse($config->getLogoUrl());
$this->cleanUp();
}
/**
* Test case for Config::getIPNCallbackUrl
*/
public function testGetIPNCallbackUrl()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$callbackBaseUrl = $config->getIPNCallbackUrl();
$this->assertEquals($callbackBaseUrl, $this->getConfig()->getCurrentShopUrl() . "index.php?cl=oepaypalipnhandler&fnc=handleRequest&shp=" . $this->getConfig()->getShopId());
}
/**
* Test case for Config::getIPNUrl()
*/
public function testGetIPNResponseUrl_sandboxOFF_usePayPalUrl()
{
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', false);
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals($config->getIPNResponseUrl(), 'https://www.paypal.com/cgi-bin/webscr&cmd=_notify-validate');
}
/**
* Test case for Config::getIPNUrl()
*/
public function testGetIPNResponseUrl_sandboxON_useSandboxUrl()
{
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', true);
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals($config->getIPNResponseUrl(), 'https://www.sandbox.paypal.com/cgi-bin/webscr&cmd=_notify-validate');
}
/**
* Test case for Config::getIPNUrl()
*/
public function testGetUrl_sandboxOFF_returnPayPalUrl()
{
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', false);
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals($config->getUrl(), 'https://www.paypal.com/cgi-bin/webscr');
}
/**
* Test case for Config::getIPNUrl()
*/
public function testGetUrl_sandboxON_returnSandboxUrl()
{
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', true);
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals($config->getUrl(), 'https://www.sandbox.paypal.com/cgi-bin/webscr');
}
/**
* Test case for Config::getShopUrl
*/
public function testGetShopUrl()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$shopUrl = $config->getShopUrl();
$this->assertEquals($shopUrl, $this->getConfig()->getCurrentShopUrl());
}
/**
* Test case for Config::getLang
*/
public function testGetLang()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$lang = $config->getLang();
$this->assertTrue(is_a($lang, Language::class), 'Method getLang() should return language object.');
}
/**
* Test case for Config::getUtils
*/
public function testGetUtils()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$utils = $config->getUtils();
$this->assertTrue(is_a($utils, Utils::class), 'Method getUtils() should return utils object.');
}
public function providerIsExpressCheckoutInDetailsPage()
{
return array(
array(true),
array(false)
);
}
/**
* Test blOEPayPalECheckoutInDetails config
*
* @dataProvider providerIsExpressCheckoutInDetailsPage
*/
public function testIsExpressCheckoutInDetailsPage($oEPayPalECheckoutInDetails)
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('blOEPayPalECheckoutInDetails', $oEPayPalECheckoutInDetails);
$this->assertEquals($oEPayPalECheckoutInDetails, $config->isExpressCheckoutInDetailsPage());
}
/**
* Checks if method returns current URL
*/
public function testGetCurrentUrl()
{
$currentUrl = 'http://oxideshop.com/test';
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\UtilsUrl::class);
$mockBuilder->setMethods(['getCurrentUrl']);
$utilsUrl = $mockBuilder->getMock();
$utilsUrl->expects($this->any())->method('getCurrentUrl')->will($this->returnValue($currentUrl));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\UtilsUrl::class, $utilsUrl);
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals($currentUrl, $config->getCurrentUrl());
}
public function providerGetMaxPayPalDeliveryAmount()
{
return array(
array(40.5, 40.5),
array(-0.51, -0.51)
);
}
/**
* Checks max delivery amount setting.
*
* @dataProvider providerGetMaxPayPalDeliveryAmount
*/
public function testGetMaxPayPalDeliveryAmount_configSetWithProperValues_configValue($maxAmount, $expectedAmount)
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('dMaxPayPalDeliveryAmount', $maxAmount);
$this->assertEquals($expectedAmount, $config->getMaxPayPalDeliveryAmount());
}
public function providerGetMaxPayPalDeliveryAmountBadConfigs()
{
return array(
array(null, 30),
array(0, 30),
array(false, 30),
);
}
/**
* Checks max delivery amount setting.
*
* @dataProvider providerGetMaxPayPalDeliveryAmountBadConfigs
*/
public function testGetMaxPayPalDeliveryAmount_configSetWithFalseValues_30($maxAmount, $expectedAmount)
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('dMaxPayPalDeliveryAmount', $maxAmount);
$this->assertEquals($expectedAmount, $config->getMaxPayPalDeliveryAmount());
}
/**
* Checks max delivery amount setting.
*
* @dataProvider providerGetMaxPayPalDeliveryAmount
*/
public function testGetMaxPayPalDeliveryAmount_default_30()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals(30, $config->getMaxPayPalDeliveryAmount());
}
/**
* Tests if partner code is returned correct.
* Testing non-shortcut partner codes here.
*/
public function testGetPartnerCode()
{
$config = $this->getConfig();
$result = 'O3SHOP_Cart_CommunityECS';
$payPalConfig = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals($result, $payPalConfig->getPartnerCode());
}
/**
* Tests if partner code is returned correct in case the shortcut was used.
*/
public function testGetShortcutPartnerCode()
{
\OxidEsales\Eshop\Core\Registry::getSession()->setVariable(\OxidEsales\PayPalModule\Core\Config::OEPAYPAL_TRIGGER_NAME,
\OxidEsales\PayPalModule\Core\Config::OEPAYPAL_SHORTCUT);
$expected = 'O3SHOP_Cart_ECS_Shortcut';
$payPalConfig = new \OxidEsales\PayPalModule\Core\Config();
$this->assertEquals($expected, $payPalConfig->getPartnerCode());
}
public function testGetMobileECDefaultShippingId_notSet_null()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertNull($config->getMobileECDefaultShippingId());
}
public function testGetMobileECDefaultShippingId_setPayment_paymentId()
{
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->getConfig()->setConfigParam('sOEPayPalMECDefaultShippingId', 'shippingId');
$this->assertEquals('shippingId', $config->getMobileECDefaultShippingId());
}
public function testIsMobile_mobileDevice_true()
{
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3';
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertTrue($config->isDeviceMobile());
}
public function testIsMobile_notMobileDevice_false()
{
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0';
$config = new \OxidEsales\PayPalModule\Core\Config();
$this->assertFalse($config->isDeviceMobile());
}
}

View File

@@ -0,0 +1,309 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
/**
* Testing curl class.
*/
class CurlTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Checks if function returns null when nothing is set.
*/
public function testGetHost_notSet_null()
{
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$this->assertNull($curl->getHost(), 'Default value must be null.');
}
/**
* Check if getter returns what is set in setter.
*/
public function testGetHost_setHost_host()
{
$host = 'someHost';
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$curl->setHost($host);
$this->assertEquals($host, $curl->getHost(), 'Check if getter returns what is set in setter.');
}
/**
* Checks if returned header is correct when header was not set and host was set.
*/
public function testGetHeader_headerNotSetAndHostSet_headerWithHost()
{
$host = 'someHost';
$expectedHeader = array(
'POST /cgi-bin/webscr HTTP/1.1',
'Content-Type: application/x-www-form-urlencoded',
'Host: ' . $host,
'Connection: close'
);
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$curl->setHost($host);
$this->assertEquals($expectedHeader, $curl->getHeader(), 'Header must be formed from set host.');
}
/**
* Checks if returned header is correct when header was not set and host was not set.
*/
public function testGetHeader_headerNotSetAndHostNotSet_headerWithoutHost()
{
$expectedHeader = array(
'POST /cgi-bin/webscr HTTP/1.1',
'Content-Type: application/x-www-form-urlencoded',
'Connection: close'
);
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$this->assertEquals($expectedHeader, $curl->getHeader(), 'Header must be without host as host not set.');
}
/**
* Checks if returned header is correct when header was set and host was set.
*/
public function testGetHeader_headerSetAndHostSet_headerFromSet()
{
$host = 'someHost';
$header = array('Test header');
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$curl->setHost($host);
$curl->setHeader($header);
$this->assertEquals($header, $curl->getHeader(), 'Header must be same as set header.');
}
/**
* Checks if returned header is correct when header was set and host was not set.
*/
public function testGetHeader_headerSetAndHostNotSet_headerWithoutHost()
{
$header = array('Test header');
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$curl->setHeader($header);
$this->assertEquals($header, $curl->getHeader(), 'Header must be same as set header.');
}
/**
* Test Curl::setConnectionCharset()
*/
public function testSetConnectionCharset_set_get()
{
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$curl->setConnectionCharset('ISO-8859-1');
$this->assertEquals('ISO-8859-1', $curl->getConnectionCharset());
}
/**
* Test Curl::getConnectionCharset()
*/
public function testGetConnectionCharset_notSet_UTF()
{
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$this->assertEquals('UTF-8', $curl->getConnectionCharset());
}
/**
* Test Curl::setDataCharset()
*/
public function testSetDataCharset_set_get()
{
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$curl->setDataCharset('ISO-8859-1');
$this->assertEquals('ISO-8859-1', $curl->getDataCharset());
}
/**
* Test Curl::getDataCharset()
*/
public function testGetDataCharset_notSet_UTF()
{
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$this->assertEquals('UTF-8', $curl->getDataCharset());
}
/**
* Test Curl::setEnvironmentParameter()
*/
public function testSetEnvironmentParameter_setParameter_addedToParameterSet()
{
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$curl->setEnvironmentParameter('param', 'value');
$expectedParameters = array(
'CURLOPT_VERBOSE' => 0,
'CURLOPT_SSL_VERIFYPEER' => false,
'CURLOPT_SSL_VERIFYHOST' => false,
'CURLOPT_SSLVERSION' => 6,
'CURLOPT_RETURNTRANSFER' => 1,
'CURLOPT_POST' => 1,
'CURLOPT_HTTP_VERSION' => 2,
'param' => 'value'
);
$this->assertEquals($expectedParameters, $curl->getEnvironmentParameters());
}
/**
* Test Curl::getEnvironmentParameters()
*/
public function testGetEnvironmentParameters_default_returnDefaultSet()
{
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$expectedParameters = array(
'CURLOPT_VERBOSE' => 0,
'CURLOPT_SSL_VERIFYPEER' => false,
'CURLOPT_SSL_VERIFYHOST' => false,
'CURLOPT_SSLVERSION' => 6,
'CURLOPT_RETURNTRANSFER' => 1,
'CURLOPT_POST' => 1,
'CURLOPT_HTTP_VERSION' => 2,
);
$this->assertEquals($expectedParameters, $curl->getEnvironmentParameters());
}
/**
* Test Curl::getParameters()
*/
public function testGetParameters_default_null()
{
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$this->assertNull($curl->getParameters());
}
/**
* Test Curl::getParameters()
*/
public function testGetParameters_set_returnSet()
{
$parameters = array('parameter' => 'value');
$curl = new \OxidEsales\PayPalModule\Core\Curl();
$curl->setParameters($parameters);
$this->assertEquals($parameters, $curl->getParameters());
}
/**
* Test Curl::setUrlToCall()
* Test Curl::getUrlToCall()
*/
public function testGetUrlToCall_urlSet_setReturned()
{
$endpointUrl = 'http://www.oxid-esales.com/index.php?anid=article';
$payPalCurl = new \OxidEsales\PayPalModule\Core\Curl();
$payPalCurl->setUrlToCall($endpointUrl);
$urlToCall = $payPalCurl->getUrlToCall();
$this->assertEquals($endpointUrl, $urlToCall, 'Url should be same as provided from config.');
}
/**
* Test Curl::getUrlToCall()
*/
public function testGetUrlToCall_notSet_null()
{
$payPalCurl = new \OxidEsales\PayPalModule\Core\Curl();
$this->assertNull($payPalCurl->getUrlToCall());
}
/**
* Test Curl::setUrlToCall()
* Test Curl::getUrlToCall()
*/
public function testGetUrlToCall_badUrlSet_Exception()
{
$this->expectException(\OxidEsales\PayPalModule\Core\Exception\PayPalException::class);
$endpointUrl = 'url';
$payPalCurl = new \OxidEsales\PayPalModule\Core\Curl();
$payPalCurl->setUrlToCall($endpointUrl);
$this->assertEquals($endpointUrl, $payPalCurl->getUrlToCall());
}
/**
* Test Curl::setQuery()
*/
public function testSetQuery_set_get()
{
$payPalCurl = new \OxidEsales\PayPalModule\Core\Curl();
$payPalCurl->setQuery('param1=value1&param2=values2');
$this->assertEquals('param1=value1&param2=values2', $payPalCurl->getQuery());
}
/**
* Test Curl::getQuery()
*/
public function testGetQuery_setParameter_getQueryFromParameters()
{
$payPalCurl = new \OxidEsales\PayPalModule\Core\Curl();
$payPalCurl->setParameters(array('param1' => 'value1', 'param2' => 'values2'));
$this->assertEquals('param1=value1&param2=values2', $payPalCurl->getQuery());
}
/**
* Test Curl::getQuery()
*/
public function testGetQuery_setParameterNotUtf_getQueryFromParameters()
{
$payPalCurl = new \OxidEsales\PayPalModule\Core\Curl();
$payPalCurl->setDataCharset('ISO-8859-1');
$payPalCurl->setParameters(array('param1' => 'J<>ger', 'param2' => 'values2'));
$pramsUtf = array('param1' => utf8_encode('J<>ger'), 'param2' => 'values2');
$this->assertEquals(http_build_query($pramsUtf), $payPalCurl->getQuery());
}
/**
* Test Curl::execute()
*/
public function testExecute_setParameters_getResponseArray()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Curl::class);
$mockBuilder->setMethods(['curlExecute', 'setOption', 'parseResponse', 'close']);
$payPalCurl = $mockBuilder->getMock();
$payPalCurl->expects($this->any())->method('setOption');
$payPalCurl->expects($this->once())->method('curlExecute')->will($this->returnValue('rParam1=rValue1'));
$payPalCurl->expects($this->once())->method('parseResponse')
->with($this->equalTo('rParam1=rValue1'))
->will($this->returnValue(array('rParam1' => 'rValue1')));
$payPalCurl->expects($this->once())->method('close');
$payPalCurl->setParameters(array('param1' => 'value1', 'param2' => 'values2'));
$payPalCurl->setUrlToCall('http://url');
$this->assertEquals(array('rParam1' => 'rValue1'), $payPalCurl->execute());
}
// public function testExecute_getParameters
}

View File

@@ -0,0 +1,78 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
/**
* Testing \OxidEsales\PayPalModule\Core\Escape class.
*/
class EscapeTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Testing input processor. Checking 3 cases - passing object, array, string.
*/
public function testCheckParamSpecialChars()
{
$object = new \stdClass();
$object->xxx = 'yyy';
$array = array('&\\o<x>i"\'d' . chr(0));
$string = '&\\o<x>i"\'d' . chr(0);
$payPalRequest = new \OxidEsales\PayPalModule\Core\Request();
// object must came back the same
$this->assertEquals($object, $payPalRequest->escapeSpecialChars($object));
// array items comes fixed
$this->assertEquals(array('&amp;&#092;o&lt;x&gt;i&quot;&#039;d'), $payPalRequest->escapeSpecialChars($array));
// string comes fixed
$this->assertEquals('&amp;&#092;o&lt;x&gt;i&quot;&#039;d', $payPalRequest->escapeSpecialChars($string));
}
/**
* Data provider for testCheckParamSpecialCharsAlsoFixesArrayKeys()
*
* @return array
*/
public function providerCheckParamSpecialCharsAlsoFixesArrayKeys()
{
return array(
array(
array('asd&' => 'a%&'),
array('asd&amp;' => 'a%&amp;'),
),
array(
'asd&',
'asd&amp;',
)
);
}
/**
* Test if checkParamSpecialChars also can fix arrays
*
* @dataProvider providerCheckParamSpecialCharsAlsoFixesArrayKeys
*/
public function testCheckParamSpecialCharsAlsoFixesArrayKeys($checkData, $checkExpectedResult)
{
$payPalRequest = new \OxidEsales\PayPalModule\Core\Request();
$this->assertEquals($checkExpectedResult, $payPalRequest->escapeSpecialChars($checkData));
}
}

View File

@@ -0,0 +1,225 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
/**
* Testing \OxidEsales\PayPalModule\Core\Events class.
*/
class EventsTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Tear down the fixture.
*/
protected function setUp(): void
{
// Dropping order payments table
\OxidEsales\Eshop\Core\DatabaseProvider::getDB()->execute("DROP TABLE IF EXISTS `oepaypal_orderpayments`");
\OxidEsales\Eshop\Core\DatabaseProvider::getDB()->execute("DROP TABLE IF EXISTS `oepaypal_order`");
\OxidEsales\Eshop\Core\DatabaseProvider::getDB()->execute("DROP TABLE IF EXISTS `oepaypal_orderpaymentcomments`");
// Deleting PayPal payment method
$payment = oxNew(\OxidEsales\Eshop\Application\Model\Payment::class);
$payment->load('oxidpaypal');
$payment->delete();
// Deleting enabled PayPal RDFA
$query = "DELETE FROM `oxobject2payment` WHERE `OXID` = 'oepaypalrdfa'";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query);
parent::setUp();
}
protected function tearDown(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('DROP TABLE IF EXISTS `oepaypal_orderpaymentcomments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('DROP TABLE IF EXISTS `oepaypal_orderpayments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('DROP TABLE IF EXISTS `oepaypal_order`');
\OxidEsales\PayPalModule\Core\Events::addOrderPaymentsCommentsTable();
\OxidEsales\PayPalModule\Core\Events::addOrderPaymentsTable();
\OxidEsales\PayPalModule\Core\Events::addOrderTable();
parent::tearDown();
}
/**
* \OxidEsales\PayPalModule\Core\Events::onActivate()
*/
public function testOnActivate()
{
\OxidEsales\PayPalModule\Core\Events::onActivate();
$dbMetaDataHandler = oxNew(\OxidEsales\Eshop\Core\DbMetaDataHandler::class);
// PayPal order table extends \OxidEsales\Eshop\Application\Model\Order table
$this->assertTrue($dbMetaDataHandler->tableExists('oepaypal_order'));
// Payment history table created
$this->assertTrue($dbMetaDataHandler->tableExists('oepaypal_orderpayments'));
// Payment comments table created
$this->assertTrue($dbMetaDataHandler->tableExists('oepaypal_orderpaymentcomments'));
// Payment method exist and enabled
$payment = oxNew(\OxidEsales\Eshop\Application\Model\Payment::class);
$payment->load('oxidpaypal');
$this->assertEquals(1, $payment->oxpayments__oxactive->value);
//Enabled PayPal RDFa
$this->assertTrue($this->getPayPalRDFaFromOxObject2PaymentTable());
}
/**
* \OxidEsales\PayPalModule\Core\Events::onActivate()
*/
public function testOnActivateAddMissingFields()
{
$this->createTables();
\OxidEsales\PayPalModule\Core\Events::onActivate();
$dbMetaDataHandler = oxNew(\OxidEsales\Eshop\Core\DbMetaDataHandler::class);
// PayPal order table extends \OxidEsales\Eshop\Application\Model\Order table
$this->assertTrue($dbMetaDataHandler->tableExists('oepaypal_order'));
// Payment history table created
$this->assertTrue($dbMetaDataHandler->tableExists('oepaypal_orderpayments'));
// Payment comments table created
$this->assertTrue($dbMetaDataHandler->tableExists('oepaypal_orderpaymentcomments'));
$tableFields = array(
'oepaypal_order' => 'OEPAYPAL_TIMESTAMP',
'oepaypal_orderpayments' => 'OEPAYPAL_TIMESTAMP',
'oepaypal_orderpaymentcomments' => 'OEPAYPAL_TIMESTAMP',
);
$dbMetaDataHandler = oxNew(\OxidEsales\Eshop\Core\DbMetaDataHandler::class);
foreach ($tableFields as $tableName => $fieldName) {
$this->assertTrue($dbMetaDataHandler->fieldExists($fieldName, $tableName));
}
// Payment method exist and enabled
$payment = oxNew(\OxidEsales\Eshop\Application\Model\Payment::class);
$payment->load('oxidpaypal');
$this->assertEquals(1, $payment->oxpayments__oxactive->value);
//Enabled PayPal RDFa
$this->assertTrue($this->getPayPalRDFaFromOxObject2PaymentTable());
}
protected function createTables()
{
$query = "CREATE TABLE IF NOT EXISTS `oepaypal_orderpayments` (
`OEPAYPAL_PAYMENTID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`OEPAYPAL_ACTION` enum('capture', 'authorization', 're-authorization', 'refund', 'void') NOT NULL DEFAULT 'capture',
`OEPAYPAL_ORDERID` char(32) NOT NULL,
`OEPAYPAL_TRANSACTIONID` varchar(32) NOT NULL,
`OEPAYPAL_CORRELATIONID` varchar(32) NOT NULL,
`OEPAYPAL_AMOUNT` decimal(9,2) NOT NULL,
`OEPAYPAL_CURRENCY` varchar(3) NOT NULL,
`OEPAYPAL_REFUNDEDAMOUNT` decimal(9,2) NOT NULL,
`OEPAYPAL_DATE` datetime NOT NULL,
`OEPAYPAL_STATUS` varchar(20) NOT NULL,
PRIMARY KEY (`OEPAYPAL_PAYMENTID`),
KEY `OEPAYPAL_ORDERID` (`OEPAYPAL_ORDERID`),
KEY `OEPAYPAL_DATE` (`OEPAYPAL_DATE`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query);
$query = "CREATE TABLE IF NOT EXISTS `oepaypal_orderpaymentcomments` (
`OEPAYPAL_COMMENTID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`OEPAYPAL_PAYMENTID` int(11) unsigned NOT NULL,
`OEPAYPAL_COMMENT` varchar(256) NOT NULL,
`OEPAYPAL_DATE` datetime NOT NULL,
PRIMARY KEY (`OEPAYPAL_COMMENTID`),
KEY `OEPAYPAL_ORDERID` (`OEPAYPAL_PAYMENTID`),
KEY `OEPAYPAL_DATE` (`OEPAYPAL_DATE`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query);
$query = "CREATE TABLE IF NOT EXISTS `oepaypal_order` (
`OEPAYPAL_ORDERID` char(32) character set latin1 collate latin1_general_ci NOT NULL,
`OEPAYPAL_PAYMENTSTATUS` enum('pending','completed','failed','canceled') NOT NULL DEFAULT 'pending',
`OEPAYPAL_CAPTUREDAMOUNT` decimal(9,2) NOT NULL,
`OEPAYPAL_REFUNDEDAMOUNT` decimal(9,2) NOT NULL,
`OEPAYPAL_VOIDEDAMOUNT` decimal(9,2) NOT NULL,
`OEPAYPAL_TOTALORDERSUM` decimal(9,2) NOT NULL,
`OEPAYPAL_CURRENCY` varchar(32) NOT NULL,
`OEPAYPAL_TRANSACTIONMODE` enum('Sale','Authorization') NOT NULL DEFAULT 'Sale',
PRIMARY KEY (`OEPAYPAL_ORDERID`),
KEY `OEPAYPAL_PAYMENTSTATUS` (`OEPAYPAL_PAYMENTSTATUS`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query);
}
/**
* \OxidEsales\PayPalModule\Core\Events::onActivate()
*/
public function testOnDeactivate()
{
\OxidEsales\PayPalModule\Core\Events::onActivate();
\OxidEsales\PayPalModule\Core\Events::onDeactivate();
$payment = oxNew(\OxidEsales\Eshop\Application\Model\Payment::class);
$payment->load('oxidpaypal');
$this->assertEquals(0, $payment->oxpayments__oxactive->value);
//Check RDFa
$this->assertFalse($this->getPayPalRDFaFromOxObject2PaymentTable());
}
/**
* Checks if method inserts additional row.
*/
public function testEnablePayPalRDFA()
{
\OxidEsales\PayPalModule\Core\Events::enablePayPalRDFA();
$this->assertTrue($this->getPayPalRDFaFromOxObject2PaymentTable());
}
/**
* Checks if method deletes row.
*/
public function testDisablePayPalRDFA()
{
\OxidEsales\PayPalModule\Core\Events::enablePayPalRDFA();
\OxidEsales\PayPalModule\Core\Events::disablePayPalRDFA();
$this->assertFalse($this->getPayPalRDFaFromOxObject2PaymentTable());
}
/**
* Check if record for RDF setting is inserted
*
* @return mixed
*/
protected function getPayPalRDFaFromOxObject2PaymentTable()
{
$query = "SELECT 1 FROM `oxobject2payment` WHERE `OXID` = 'oepaypalrdfa' LIMIT 1";
return (bool) \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getOne($query);
}
}

View File

@@ -0,0 +1,125 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
/**
* Testing \OxidEsales\PayPalModule\Core\ExtensionChecker class.
*/
class ExtensionCheckerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Shop id setter and getter test
*/
public function testSetGetShopId_withGivenShopId()
{
$checker = new \OxidEsales\PayPalModule\Core\ExtensionChecker();
$checker->setShopId('testShopId');
$this->assertEquals('testShopId', $checker->getShopId());
}
/**
* Shop id getter test, if not defined use active shop id
*/
public function testSetGetShopId_useActiveShopId()
{
$checker = new \OxidEsales\PayPalModule\Core\ExtensionChecker();
$this->assertEquals($this->getConfig()->getShopId(), $checker->getShopId());
}
/**
* Extension id setter and getter test
*/
public function testSetGeExtensionId_withGivenExtensionId()
{
$checker = new \OxidEsales\PayPalModule\Core\ExtensionChecker();
$checker->setExtensionId('testExtensionId');
$this->assertEquals('testExtensionId', $checker->getExtensionId());
}
/**
* Testing extension not given
*/
public function testIsActive_extensionNotSet()
{
$checker = new \OxidEsales\PayPalModule\Core\ExtensionChecker();
$this->assertFalse($checker->isActive());
}
/**
* Data provider for testIsActive_extensionIsSet()
*
* @return array
*/
public function getExtendedClassDataProvider()
{
$extendedClasses = array(
\OxidEsales\Eshop\Application\Controller\Admin\OrderList::class => 'oe/oepaypal/controllers/admin/oepaypalorder_list',
\OxidEsales\Eshop\Application\Controller\OrderController::class => \OxidEsales\PayPalModule\Controller\OrderController::class
);
$extendedClassesWith = array(
\OxidEsales\Eshop\Application\Controller\Admin\OrderList::class => 'oe/testExtension/controllers/admin/oepaypalorder_list',
\OxidEsales\Eshop\Application\Controller\OrderController::class => \OxidEsales\PayPalModule\Controller\OrderController::class
);
$disabledModules = array(
0 => 'invoicepdf',
1 => 'oepaypal'
);
$disabledModulesWith = array(
0 => 'invoicepdf',
1 => 'testExtension'
);
return array(
array(false, array(), array()),
array(false, array(), $disabledModules),
array(false, array(), $disabledModulesWith),
array(false, $extendedClasses, array()),
array(false, $extendedClasses, $disabledModules),
array(false, $extendedClasses, $disabledModulesWith),
array(true, $extendedClassesWith, array()),
array(true, $extendedClassesWith, $disabledModules),
array(false, $extendedClassesWith, $disabledModulesWith),
);
}
/**
* Testing is given extension active in many scenarios
*
* @dataProvider getExtendedClassDataProvider
*/
public function testIsActive_extensionIsSet($isActive, $extendedClasses, $disabledModules)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\ExtensionChecker::class);
$mockBuilder->setMethods(['getExtendedClasses', 'getDisabledModules']);
$checker = $mockBuilder->getMock();
$checker->expects($this->any())->method("getExtendedClasses")->will($this->returnValue($extendedClasses));
$checker->expects($this->any())->method("getDisabledModules")->will($this->returnValue($disabledModules));
$checker->setExtensionId('testExtension');
$this->assertEquals($isActive, $checker->isActive());
}
}

View File

@@ -0,0 +1,51 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
/**
* Tests for oeThemeSwitcherUserAgent class
*/
class FullNameTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* @dataProvider providerSplitNames
*/
public function testSplitName($fullName, $firstName, $lastName)
{
$payPalFullName = new \OxidEsales\PayPalModule\Core\FullName($fullName);
$this->assertEquals($firstName, $payPalFullName->getFirstName());
$this->assertEquals($lastName, $payPalFullName->getLastName());
}
public function providerSplitNames()
{
return array(
array('Jonas Petraitis', 'Jonas', 'Petraitis'),
array('', '', ''),
array('Ona Egle Petraitis', 'Ona', 'Egle Petraitis'),
array('Ona', 'Ona', ''),
array(' Antanas, smoriginas ', 'Antanas,', 'smoriginas'),
array(null, '', ''),
);
}
}

View File

@@ -0,0 +1,135 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
/**
* Class IpnConfigTest
*
* @package OxidEsales\PayPalModule\Tests\Unit\Core
*/
class IpnConfigTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function providerGetPayPalIpnHost()
{
return [
// Default PayPal IPN sandbox host
'default_IPN_sandbox_host' =>
[true, null, null, \OxidEsales\PayPalModule\Core\IpnConfig::OEPAYPAL_IPN_SANDBOX_HOST],
// Default PayPal IPN host.
'default_IPN_host' =>
[false, null, null, \OxidEsales\PayPalModule\Core\IpnConfig::OEPAYPAL_IPN_HOST],
// Sandbox on; PayPal IPN sandbox host NOT set; PayPal IPN host set; Sandbox default host return.
'sandbox_on_default_IPN_sandbox_host' =>
[true, null, 'testSandboxIpnHost', \OxidEsales\PayPalModule\Core\IpnConfig::OEPAYPAL_IPN_SANDBOX_HOST],
// Sandbox off; PayPal IPN sandbox host set; PayPal IPN host NOT set; PayPal default host return.
'sandbox_off_default_IPN_host' =>
[false, 'testSandboxIpnHost', null, \OxidEsales\PayPalModule\Core\IpnConfig::OEPAYPAL_IPN_HOST],
// Sandbox on; PayPal IPN sandbox host set; PayPal IPN host set; PayPal set sandbox host return.
'sandbox_on_set_IPN_sandbox_host' =>
[true, 'testSandboxIpnHost', 'testIpnHost', 'testSandboxIpnHost'],
// Sandbox off; PayPal IPN sandbox host set; PayPal IPN host set; PayPal set host return.
'sandbox_off_set_IPN_host' =>
[false, 'testSandboxIpnHost', 'testIpnHost', 'testIpnHost']
];
}
/**
* Test setter/getter depending on module configuration.
*
* @dataProvider providerGetPayPalIpnHost
*/
public function testGetIpnHost($sandboxEnabled, $payPalSandboxIpnHost, $payPalIpnHost, $expected)
{
$IpnConfig = new \OxidEsales\PayPalModule\Core\IpnConfig();
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', $sandboxEnabled);
if (!empty($payPalSandboxIpnHost)) {
$IpnConfig->setPayPalSandboxIpnHost($payPalSandboxIpnHost);
}
if (!empty($payPalIpnHost)) {
$IpnConfig->setPayPalIpnHost($payPalIpnHost);
}
$this->assertEquals($expected, $IpnConfig->getIpnHost());
}
public function providerGetPayPalIpnCallbackUrl()
{
return [
// Default PayPal IPN sandbox url
'default_IPN_sandbox_url' =>
[true, null, null, \OxidEsales\PayPalModule\Core\IpnConfig::OEPAYPAL_SANDBOX_IPN_CALLBACK_URL],
// Default PayPal IPN url.
'default_IPN_url' =>
[false, null, null, \OxidEsales\PayPalModule\Core\IpnConfig::OEPAYPAL_IPN_CALLBACK_URL],
// Sandbox on; PayPal IPN sandbox url NOT set; PayPal IPN url set; Sandbox default url return.
'sandbox_on_default_IPN_sandbox_url' =>
[true, null, 'testSandboxIpnUrl', \OxidEsales\PayPalModule\Core\IpnConfig::OEPAYPAL_SANDBOX_IPN_CALLBACK_URL],
// Sandbox off; PayPal IPN sandbox url set; PayPal IPN url NOT set; PayPal default url return.
'sandbox_off_default_IPN_url' =>
[false, 'testSandboxIpnUrl', null, \OxidEsales\PayPalModule\Core\IpnConfig::OEPAYPAL_IPN_CALLBACK_URL],
// Sandbox on; PayPal IPN sandbox url set; PayPal IPN url set; PayPal set sandbox url return.
'sandbox_on_set_IPN_sandbox_url' =>
[true, 'testSandboxIpnUrl', 'testIpnUrl', 'testSandboxIpnUrl'],
// Sandbox off; PayPal IPN sandbox url set; PayPal IPN url set; PayPal set url return.
'sandbox_off_set_IPN_url' =>
[false, 'testSandboxIpnUrl', 'testIpnUrl', 'testIpnUrl']
];
}
/**
* Test setter/getter depending on module configuration.
*
* @dataProvider providerGetPayPalIpnCallbackUrl
*/
public function testGetIpnCallbackUrl($sandboxEnabled, $payPalSandboxIpnUrl, $payPalIpnUrl, $expected)
{
$IpnConfig = new \OxidEsales\PayPalModule\Core\IpnConfig();
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', $sandboxEnabled);
if (!empty($payPalSandboxIpnUrl)) {
$IpnConfig->setPayPalSandboxIpnUrl($payPalSandboxIpnUrl);
}
if (!empty($payPalIpnUrl)) {
$IpnConfig->setPayPalIpnUrl($payPalIpnUrl);
}
$this->assertEquals($expected, $IpnConfig->getIpnUrl());
}
/**
* Test case for Config::getIPNUrl()
*/
public function testGetIpnResponseUrl()
{
$url = 'http://mypaypal.local/webscr';
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\IpnConfig::class);
$mockBuilder->setMethods(['getIpnUrl']);
$ipnConfig = $mockBuilder->getMock();
$ipnConfig->expects($this->once())
->method('getIpnUrl')
->will($this->returnValue($url));
$this->assertEquals($ipnConfig->getIPNResponseUrl(), $url . '&cmd=_notify-validate');
}
}

View File

@@ -0,0 +1,111 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
/**
* Testing Model class.
*/
class ModelTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Loading of data by id, returned by getId method
*/
public function testLoad_LoadByGetId_DataLoaded()
{
$id = 'RecordIdToLoad';
$data = array('testkey' => 'testValue');
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\DbGateways\OrderPaymentDbGateway::class);
$mockBuilder->setMethods(['load']);
$gateway = $mockBuilder->getMock();
$gateway->expects($this->any())->method('load')->with($id)->will($this->returnValue($data));
$model = $this->getPayPalModel($gateway, $id);
$this->assertTrue($model->load());
$this->assertEquals($data, $model->getData());
}
/**
* Loading of data by passed id
*/
public function testLoad_LoadByPassedId_DataLoaded()
{
$id = 'RecordIdToLoad';
$data = array('testkey' => 'testValue');
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\DbGateways\OrderPaymentDbGateway::class);
$mockBuilder->setMethods(['load']);
$gateway = $mockBuilder->getMock();
$gateway->expects($this->any())->method('load')->with($id)->will($this->returnValue($data));
$model = $this->getPayPalModel($gateway, $id, $id);
$this->assertTrue($model->load($id));
$this->assertEquals($data, $model->getData());
}
/**
* Is loaded method returns false when record does not exists in database
*/
public function testIsLoaded_DatabaseRecordNotFound()
{
$gateway = $this->_createStub(\OxidEsales\PayPalModule\Model\DbGateways\OrderPaymentDbGateway::class, array('load' => null));
$model = $this->getPayPalModel($gateway);
$model->load();
$this->assertFalse($model->isLoaded());
}
/**
* Is loaded method returns false when record does not exists in database
*/
public function testIsLoaded_DatabaseRecordFound()
{
$gateway = $this->_createStub(\OxidEsales\PayPalModule\Model\DbGateways\OrderPaymentDbGateway::class, array('load' => array('oePayPalId' => 'testId')));
$model = $this->getPayPalModel($gateway);
$model->load();
$this->assertTrue($model->isLoaded());
}
/**
* Creates model with mocked abstract methods
*
* @param object $gateway
* @param string $getId
* @param string $setId
*
* @return \OxidEsales\PayPalModule\Core\Model
*/
protected function getPayPalModel($gateway, $getId = null, $setId = null)
{
$model = $this->_createStub(\OxidEsales\PayPalModule\Core\Model::class, array('getDbGateway' => $gateway, 'getId' => $getId), array('setId'));
if ($setId) {
$model->expects($this->any())->method('setId')->with($setId);
}
return $model;
}
}

View File

@@ -0,0 +1,79 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
/**
* Testing \OxidEsales\PayPalModule\Core\PayPalCheckValidator class.
*/
class PayPalCheckValidatorTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Data provider for testIsPayPalCheckValid()
*
* @return array
*/
public function isIsPayPalCheckValid_dataProvider()
{
return array(
array(200, 220, true), //if new value is less
array(50, 50, true), //if new and old values are the same
array(620, 600, false), //if new value is bigger
array(26.55, '26.55', true), //if old value is string
array(600, 620, true), //if new value is smaller
);
}
/**
* Test \OxidEsales\PayPalModule\Core\PayPalCheckValidator::isPayPalCheckValid()
*
* @dataProvider isIsPayPalCheckValid_dataProvider
*/
public function testIsPayPalCheckValid($newAmount, $oldAmount, $result)
{
$checkValidator = new \OxidEsales\PayPalModule\Core\PayPalCheckValidator();
$checkValidator->setNewBasketAmount($newAmount);
$checkValidator->setOldBasketAmount($oldAmount);
$this->assertEquals($result, $checkValidator->isPayPalCheckValid());
}
/**
* Test case for \OxidEsales\PayPalModule\Core\PayPalCheckValidator::getOldBasketAmount()
*/
public function testSetGetOldBasketAmount()
{
$validator = new \OxidEsales\PayPalModule\Core\PayPalCheckValidator();
$validator->setOldBasketAmount('3.5');
$this->assertEquals(3.5, $validator->getOldBasketAmount());
}
/**
* Test case for \OxidEsales\PayPalModule\Core\PayPalCheckValidator::getNewBasketAmount()
*/
public function testSetGetNewBasketAmount()
{
$validator = new \OxidEsales\PayPalModule\Core\PayPalCheckValidator();
$validator->setNewBasketAmount('3.5');
$this->assertEquals(3.5, $validator->getNewBasketAmount());
}
}

View File

@@ -0,0 +1,513 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
/**
* Testing PayPal service class.
*/
class PayPalServiceTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* \OxidEsales\PayPalModule\Core\Config setter getter test
*/
public function testGetConfig_configSet_config()
{
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$service->setPayPalConfig(new \OxidEsales\PayPalModule\Core\Config());
$this->assertTrue($service->getPayPalConfig() instanceof \OxidEsales\PayPalModule\Core\Config);
}
/**
* \OxidEsales\PayPalModule\Core\Config getter test
*/
public function testGetConfig_notSet_config()
{
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$this->assertTrue($service->getPayPalConfig() instanceof \OxidEsales\PayPalModule\Core\Config);
}
/**
* \OxidEsales\PayPalModule\Core\Caller setter getter test
*/
public function testGetCaller_callerSet_definedCaller()
{
$caller = new \OxidEsales\PayPalModule\Core\Caller();
$caller->setParameter('parameter', 'value');
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$service->setCaller($caller);
$this->assertTrue($service->getCaller() instanceof \OxidEsales\PayPalModule\Core\Caller);
$parameters = $service->getCaller()->getParameters();
$this->assertEquals('value', $parameters['parameter']);
$this->assertNull($parameters['notDefinedParameter']);
}
/**
* \OxidEsales\PayPalModule\Core\Caller setter getter test
*/
public function testGetCaller_defaultCaller_callerWithPreparedData()
{
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', false);
$this->getConfig()->setConfigParam('sOEPayPalPassword', 'pwd');
$this->getConfig()->setConfigParam('sOEPayPalUsername', 'usr');
$this->getConfig()->setConfigParam('sOEPayPalSignature', 'signature');
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$this->assertTrue($service->getCaller() instanceof \OxidEsales\PayPalModule\Core\Caller);
$parameters = $service->getCaller()->getParameters();
$this->assertEquals('84.0', $parameters['VERSION']);
$this->assertEquals('pwd', $parameters['PWD']);
$this->assertEquals('usr', $parameters['USER']);
$this->assertEquals('signature', $parameters['SIGNATURE']);
$this->assertNull($parameters['notDefinedParameter']);
$curl = $service->getCaller()->getCurl();
$this->assertTrue($curl instanceof \OxidEsales\PayPalModule\Core\Curl);
$this->assertEquals('api-3t.paypal.com', $curl->getHost());
$this->assertEquals('https://api-3t.paypal.com/nvp', $curl->getUrlToCall());
}
/**
* \OxidEsales\PayPalModule\Core\Caller setter getter test
*/
public function testGetCallerWithLogger_LoggingOff_loggerNotSet()
{
$this->getConfig()->setConfigParam('blPayPalLoggerEnabled', false);
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$this->assertTrue($service->getCaller() instanceof \OxidEsales\PayPalModule\Core\Caller);
$this->assertNull($service->getCaller()->getLogger());
}
/**
* \OxidEsales\PayPalModule\Core\Caller setter getter test
*/
public function testGetCallerWithLogger_LoggingOn_loggerIsSet()
{
$this->getConfig()->setConfigParam('blPayPalLoggerEnabled', true);
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$this->assertTrue($service->getCaller() instanceof \OxidEsales\PayPalModule\Core\Caller);
$this->assertTrue($service->getCaller()->getLogger() instanceof \OxidEsales\PayPalModule\Core\Logger);
}
/**
* \OxidEsales\PayPalModule\Core\Caller setter getter test
*/
public function testSetExpressCheckout_setRequest_getResponse()
{
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$service->setCaller($this->prepareCallerMock($this->prepareRequest(), 'SetExpressCheckout'));
$response = $service->setExpressCheckout($this->prepareRequest());
$this->assertTrue($response instanceof \OxidEsales\PayPalModule\Model\Response\ResponseSetExpressCheckout);
$this->assertEquals(array('parameter' => 'value'), $response->getData());
}
/**
* Request setter getter test
*/
public function testGetExpressCheckoutDetails_setRequest_getResponse()
{
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$service->setCaller($this->prepareCallerMock($this->prepareRequest(), 'GetExpressCheckoutDetails'));
$response = $service->getExpressCheckoutDetails($this->prepareRequest());
$this->assertTrue($response instanceof \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails);
$this->assertEquals(array('parameter' => 'value'), $response->getData());
}
/**
* Request/Response setter getter test
*/
public function testDoExpressCheckoutPayment_setRequest_getResponse()
{
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$service->setCaller($this->prepareCallerMock($this->prepareRequest(), 'DoExpressCheckoutPayment'));
$response = $service->doExpressCheckoutPayment($this->prepareRequest());
$this->assertTrue($response instanceof \OxidEsales\PayPalModule\Model\Response\ResponseDoExpressCheckoutPayment);
$this->assertEquals(array('parameter' => 'value'), $response->getData());
}
/**
* Request/Response setter getter test
*/
public function testDoVoid_setRequest_getResponse()
{
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$service->setCaller($this->prepareCallerMock($this->prepareRequest(), 'DoVoid'));
$response = $service->doVoid($this->prepareRequest());
$this->assertTrue($response instanceof \OxidEsales\PayPalModule\Model\Response\ResponseDoVoid);
$this->assertEquals(array('parameter' => 'value'), $response->getData());
}
/**
* \OxidEsales\PayPalModule\Core\Caller setter getter test
*/
public function testRefundTransaction_setRequest_getResponse()
{
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$service->setCaller($this->prepareCallerMock($this->prepareRequest(), 'RefundTransaction'));
$response = $service->refundTransaction($this->prepareRequest());
$this->assertTrue($response instanceof \OxidEsales\PayPalModule\Model\Response\ResponseDoRefund);
$this->assertEquals(array('parameter' => 'value'), $response->getData());
}
/**
* \OxidEsales\PayPalModule\Core\Caller setter getter test
*/
public function testDoReAuthorization_setRequest_getResponse()
{
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$service->setCaller($this->prepareCallerMock($this->prepareRequest(), 'DoReauthorization'));
$response = $service->doReAuthorization($this->prepareRequest());
$this->assertTrue($response instanceof \OxidEsales\PayPalModule\Model\Response\ResponseDoReAuthorize);
$this->assertEquals(array('parameter' => 'value'), $response->getData());
}
/**
* setter getter test
*/
public function testDoCapture_setRequest_getResponse()
{
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$service->setCaller($this->prepareCallerMock($this->prepareRequest(), 'DoCapture'));
$response = $service->doCapture($this->prepareRequest());
$this->assertTrue($response instanceof \OxidEsales\PayPalModule\Model\Response\ResponseDoCapture);
$this->assertEquals(array('parameter' => 'value'), $response->getData());
}
/**
* setter getter test
*/
public function testDoVerifyWithPayPal_setRequest_getResponse()
{
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$service->setCaller($this->prepareCallerMock($this->prepareRequest(), null));
$response = $service->doVerifyWithPayPal($this->prepareRequest(), 'UTF-8');
$this->assertTrue($response instanceof \OxidEsales\PayPalModule\Model\Response\ResponseDoVerifyWithPayPal);
$this->assertEquals(array('parameter' => 'value'), $response->getData());
}
/**
* Test url and header of IPN postback call.
*/
public function testDoVerifyWithPayPalCurl()
{
//switch on sandbox more
$this->getConfig()->setConfigParam('blOEPayPalSandboxMode', true);
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Curl::class);
$mockBuilder->setMethods(['setHost', 'setUrlToCall']);
$mockedCurl = $mockBuilder->getMock();
$mockedCurl->expects($this->once())
->method('setHost')
->with($this->equalTo(\OxidEsales\PayPalModule\Core\IpnConfig::OEPAYPAL_IPN_SANDBOX_HOST));
$mockedCurl->expects($this->once())
->method('setUrlToCall')
->with($this->equalTo(\OxidEsales\PayPalModule\Core\IpnConfig::OEPAYPAL_SANDBOX_IPN_CALLBACK_URL . '&cmd=_notify-validate'));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Caller::class);
$mockBuilder->setMethods(['call', 'getCurl']);
$mockedCaller = $mockBuilder->getMock();
$mockedCaller->expects($this->once())
->method('getCurl')
->will($this->returnValue($mockedCurl));
$service = new \OxidEsales\PayPalModule\Core\PayPalService();
$service->setCaller($mockedCaller);
$response = $service->doVerifyWithPayPal($this->prepareRequest(), 'UTF-8');
$this->assertTrue($response instanceof \OxidEsales\PayPalModule\Model\Response\ResponseDoVerifyWithPayPal);
}
/**
* data provider
*
* @return array
*/
public function ipnPostbackEncodingProvider()
{
$data = array();
$data['ascii_IPN'][0]['ipn'] = array(
'payment_type' => 'instant',
'payment_date' => 'Tue_May_26_2015_21:57:49_GMT_0200_(CEST)',
'payment_status' => 'Completed',
'payer_status' => 'verified',
'first_name' => 'Bla',
'last_name' => 'Foo',
'payer_email' => 'buyer@paypalsandbox_com',
'payer_id' => 'TESTBUYERID01',
'address_name' => 'Bla_Foo',
'address_city' => 'Hamburg',
'address_street' => 'meinestrasse_123',
'charset' => 'ISO-8859-1'
);
$expectedPostback = 'payment_type=instant&payment_date=Tue_May_26_2015_21%3A57%3A49_GMT_0200_%28CEST%29&' .
'payment_status=Completed&payer_status=verified&first_name=Bla&last_name=Foo&payer_email=' .
'buyer%40paypalsandbox_com&payer_id=TESTBUYERID01&address_name=Bla_Foo&address_city=' .
'Hamburg&address_street=meinestrasse_123&charset=ISO-8859-1';
$data['ascii_IPN'][0]['expected_postback'] = $expectedPostback;
$data['ascii_IPN'][0]['expected_data_encoding'] = 'ascii';
$data['utf8_IPN'][0]['ipn'] = array(
'payment_type' => 'instant',
'payment_date' => 'Tue_May_26_2015_21:57:49_GMT_0200_(CEST)',
'payment_status' => 'Completed',
'payer_status' => 'verified',
'first_name' => 'Bla',
'last_name' => 'Foo',
'payer_email' => 'buyer@paypalsandbox_com',
'payer_id' => 'TESTBUYERID01',
'address_name' => 'Bla_Foo',
'address_city' => 'Литовские',
'address_street' => 'Blafööstraße_123',
'charset' => 'UTF-8'
);
$expectedPostback = 'payment_type=instant&payment_date=Tue_May_26_2015_21%3A57%3A49_GMT_0200_%28CEST%29&' .
'payment_status=Completed&payer_status=verified&first_name=Bla&last_name=Foo&payer_email=' .
'buyer%40paypalsandbox_com&payer_id=TESTBUYERID01&address_name=Bla_Foo&address_city=' .
'%D0%9B%D0%B8%D1%82%D0%BE%D0%B2%D1%81%D0%BA%D0%B8%D0%B5&address_street=' .
'Blaf%C3%B6%C3%B6stra%C3%9Fe_123&charset=UTF-8';
$data['utf8_IPN'][0]['expected_postback'] = $expectedPostback;
$data['utf8_IPN'][0]['expected_data_encoding'] = 'utf-8';
//see http://en.wikipedia.org/wiki/Windows-1252
$data['windows-1252_IPN'][0]['ipn'] = array(
'payment_type' => 'instant',
'payment_date' => 'Tue_May_26_2015_21:57:49_GMT_0200_(CEST)',
'payment_status' => 'Completed',
'payer_status' => 'verified',
'first_name' => 'Bla',
'last_name' => 'Foo',
'payer_email' => 'buyer@paypalsandbox_com',
'payer_id' => 'TESTBUYERID01',
'address_name' => 'Bla_Foo',
'address_city' => 'Hamburg',
'address_street' => 'Blafööstraße_123',
'charset' => 'windows-1252'
);
$expectedPostback = 'payment_type=instant&payment_date=Tue_May_26_2015_21%3A57%3A49_GMT_0200_%28CEST%29&' .
'payment_status=Completed&payer_status=verified&first_name=Bla&last_name=Foo&payer_email=' .
'buyer%40paypalsandbox_com&payer_id=TESTBUYERID01&address_name=Bla_Foo&address_city=' .
'Hamburg&address_street=Blaf%C3%B6%C3%B6stra%C3%9Fe_123&charset=windows-1252';
$data['windows-1252_IPN'][0]['expected_postback'] = $expectedPostback;
$data['windows-1252_IPN'][0]['expected_data_encoding'] = 'windows-1252';
return $data;
}
/**
* Check encoding of test data.
* Test data will be reused later.
*
* @dataProvider ipnPostbackEncodingProvider
*/
public function testTestDataEncoding($data)
{
foreach ($data['ipn'] as $key => $value) {
$this->assertTrue(mb_check_encoding($value, $data['expected_data_encoding']));
}
}
/**
* Test PayPal caller service for IPN verification.
* Verify that charsets are set as required.
*
* @dataProvider ipnPostbackEncodingProvider
*/
public function testPayPalIPNConnectionCharset($data)
{
$curl = $this->prepareCurlDoVerifyWithPayPal($data);
$this->assertEquals($data['charset'], $curl->getConnectionCharset());
}
/**
* Test PayPal caller service for IPN verification.
* Verify that charsets are set as required.
*
* @dataProvider ipnPostbackEncodingProvider
*/
public function testPayPalIPNDataCharset($data)
{
$curl = $this->prepareCurlDoVerifyWithPayPal($data);
$this->assertEquals($data['charset'], $curl->getDataCharset());
}
/**
* Test PayPal caller service for IPN verification.
* Have a look what the curl object does with parameters,
* data should not have been changed so far
*
* @dataProvider ipnPostbackEncodingProvider
*/
public function testPayPalIPNCurlParameters($data)
{
$curl = $this->prepareCurlDoVerifyWithPayPal($data);
$curlParameters = $curl->getParameters();
$this->assertEquals($data['ipn'], $curlParameters );
}
/**
* Test PayPal caller service for IPN verification.
* \OxidEsales\PayPalModule\Core\PayPalService::doVerifyWithPayPal
*
* @dataProvider ipnPostbackEncodingProvider
*/
public function testPayPalIPNPostbackEncoding($data)
{
//Rule for PayPal IPN verification is to give them back whatever comes in and prepend
//cmd=_notify-validate. As long as the shop does not try to reencode the original
//request, all is well.
//The encoding in PayPal backend should be set according to shop nevertheless.
//see http://blog.scrobbld.com/paypal/change-encoding-in-your-paypal-account/
//As the address data from IPN requests is not used for shop currently, wrong encoding
// does not matter here. It might matter for PayPalExpress checkout, as that one sets the
// delivery address that's stored at PayPal.
$curl = $this->prepareCurlDoVerifyWithPayPal($data);
$query = $curl->getQuery();
$this->assertEquals($data['expected_postback'], $query);
}
/**
* Prepare \OxidEsales\PayPalModule\Core\Caller stub
*
* @param \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest $request request
* @param string $methodName method name
*
* @return \OxidEsales\PayPalModule\Core\Caller
*/
protected function prepareCallerMock($request, $methodName = null)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Caller::class);
$mockBuilder->setMethods(['setRequest', 'call']);
$caller = $mockBuilder->getMock();
$caller->expects($this->once())->method("setRequest")->with($this->equalTo($request));
if (!is_null($methodName)) {
$caller->expects($this->once())->method("call")
->with($this->equalTo($methodName))
->will($this->returnValue(array('parameter' => 'value')));
} else {
$caller->expects($this->once())->method("call")
->will($this->returnValue(array('parameter' => 'value')));
}
return $caller;
}
/**
* Prepare PayPal request
*
* @return \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest
*/
protected function prepareRequest()
{
$request = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest();
$request->setData(array('rParameter' => 'rValue'));
return $request;
}
/**
* Provide a mocked \OxidEsales\PayPalModule\Core\Config
*
* @return \PHPUnit_Framework_MockObject_MockObject
*/
protected function getPayPalConfigMock()
{
$mocks = array( 'getUserEmail' => 'devbiz_api1.oxid-efire.com',
'isExpressCheckoutInMiniBasketEnabled' => '1',
'isStandardCheckoutEnabled' => '1',
'isExpressCheckoutEnabled' => '1',
'isLoggingEnabled' => '1',
'finalizeOrderOnPayPalSide' => '1',
'isSandboxEnabled' => '1',
'getPassword' => '1382082575',
'getSignature' => 'AoRXRr2UPUu8BdpR8rbnhMMeSk9rAmMNTW2T1o9INg0KUgsqW4qcuhS5',
'getTransactionMode' => 'AUTHORIZATION',
);
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Config::class);
$mockBuilder->setMethods(array_keys($mocks));
$paypalConfig = $mockBuilder->getMock();
foreach ($mocks as $method => $returnValue) {
$paypalConfig->expects($this->any())->method($method)->will($this->returnValue($returnValue));
}
return $paypalConfig;
}
/**
* Test helper for preparing curl object that
* ran IPN verification with PayPal.
*
* @param $data
*
* @return mixed
*/
private function prepareCurlDoVerifyWithPayPal($data)
{
$paypalPayPalRequest = oxNew(\OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest::class);
foreach ($data['ipn'] as $key => $value) {
$paypalPayPalRequest->setParameter($key, $value);
}
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Caller::class);
$mockBuilder->setMethods(['call']);
$caller = $mockBuilder->getMock();
$caller->expects($this->once())->method('call')->will($this->returnValue(array()));
$caller->setRequest($paypalPayPalRequest);
$curl = $caller->getCurl();
$curl->setParameters($caller->getParameters());
$paypalService = oxNew(\OxidEsales\PayPalModule\Core\PayPalService::class);
$paypalService->setCaller($caller);
$paypalService->setPayPalConfig($this->getPayPalConfigMock());
$paypalService->doVerifyWithPayPal($paypalPayPalRequest, $data['charset']);
return $curl;
}
}

View File

@@ -0,0 +1,130 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
/**
* Testing \OxidEsales\PayPalModule\Core\Request class.
*/
class RequestTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Data provider for testGetPost()
*
* @return array
*/
public function providerGetPost()
{
return array(
array(
array('asd&' => 'a%&'),
array('asd&' => 'a%&'),
),
array(
null,
array(),
)
);
}
/**
* Test if return POST.
*
* @param array $post
* @param array $postExpected
*
* @dataProvider providerGetPost
*/
public function testGetPost($post, $postExpected)
{
$_POST = $post;
$_GET = array('zzz' => 'yyyy');
$payPalRequest = new \OxidEsales\PayPalModule\Core\Request();
$this->assertEquals($postExpected, $payPalRequest->getPost());
}
/**
* Data provider for testGetGet()
*
* @return array
*/
public function providerGetGet()
{
return array(
array(
array('asd&' => 'a%&'),
array('asd&' => 'a%&'),
),
array(
null,
array(),
)
);
}
/**
* Test if return Get.
*
* @param array $get
* @param array $getExpected
*
* @dataProvider providerGetGet
*/
public function testGetGet($get, $getExpected)
{
$_GET = $get;
$_POST = array('zzz' => 'yyyy');
$payPalRequest = new \OxidEsales\PayPalModule\Core\Request();
$this->assertEquals($getExpected, $payPalRequest->getGet());
}
/**
* Data provider for testGetRequestParameter()
*
* @return array
*/
public function providerGetRequestParameter()
{
return array(
array(array('zzz' => 'yyy'), array('zzz' => 'iii'), 'zzz', false, 'yyy'),
array(array('zzz' => 'yyy'), array('zzz' => 'yyy'), 'zzz', false, 'yyy'),
array(array('zzz' => 'iii'), array('zzz' => 'yyy'), 'zzz', false, 'iii'),
array(array('zzz' => 'yyy&'), null, 'zzz', true, 'yyy&'),
array(null, array('zzz' => 'yyy&'), 'zzz', true, 'yyy&'),
array(array('zzz' => 'yyy&'), null, 'zzz', false, 'yyy&amp;'),
array(null, array('zzz' => 'yyy&'), 'zzz', false, 'yyy&amp;'),
);
}
/**
* Test case for \OxidEsales\PayPalModule\Core\Request::getRequestParameter()
* Test case for \OxidEsales\PayPalModule\Core\Request::getGetParameter()
* Test case for \OxidEsales\PayPalModule\Core\Request::getPostParameter()
*
* @dataProvider providerGetRequestParameter
*/
public function testGetRequestParameter($post, $get, $parameterName, $raw, $expectedRequestParameter)
{
$_POST = $post;
$_GET = $get;
$payPalRequest = new \OxidEsales\PayPalModule\Core\Request();
$this->assertEquals($expectedRequestParameter, $payPalRequest->getRequestParameter($parameterName, $raw));
}
}

View File

@@ -0,0 +1,171 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
class ShopLogoTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Tests default width getter, which is set to 190
*/
public function testGetWidthDefault()
{
$logo = new \OxidEsales\PayPalModule\Core\ShopLogo();
$this->assertEquals(190, $logo->getWidth());
}
/**
* Tests width getter, when setting
*/
public function testGetWidthIsSet()
{
$logo = new \OxidEsales\PayPalModule\Core\ShopLogo();
$logo->setWidth(200);
$this->assertEquals(200, $logo->getWidth());
}
/**
* Tests default height getter, which is set to 60
*/
public function testGetHeightDefault()
{
$logo = new \OxidEsales\PayPalModule\Core\ShopLogo();
$this->assertEquals(160, $logo->getHeight());
}
/**
* Tests height getter, when setting
*/
public function testGetHeightIsSet()
{
$logo = new \OxidEsales\PayPalModule\Core\ShopLogo();
$logo->setHeight(200);
$this->assertEquals(200, $logo->getHeight());
}
/**
* Tests getImageName when value is not set
*/
public function testGetImageNameNotSet()
{
$logo = new \OxidEsales\PayPalModule\Core\ShopLogo();
$this->assertNull($logo->getImageName());
}
/**
* Tests getImageName when value is set
*/
public function testGetImageNameIsSet()
{
$logo = new \OxidEsales\PayPalModule\Core\ShopLogo();
$logo->setImageName("name.png");
$this->assertEquals("name.png", $logo->getImageName());
}
/**
* Tests getImageDir when value is not set
*/
public function testGetImageDirNotSet()
{
$logo = new \OxidEsales\PayPalModule\Core\ShopLogo();
$this->assertNull($logo->getImageDir());
}
/**
* Tests getImageDir when value is set
*/
public function testGetImageDirIsSet()
{
$logo = new \OxidEsales\PayPalModule\Core\ShopLogo();
$logo->setImageDir("/var/www");
$this->assertEquals("/var/www", $logo->getImageDir());
}
/**
* Data provider for testGetShopLogoUrl
*
* @return array
*/
public function getShopLogoUrlProvider()
{
$defaultImageDir = $this->getConfig()->getImageDir();
$defaultImageDirUrl = $this->getConfig()->getImageUrl();
$defaultImageName = "logo.png";
$defaultWidth = 40;
$defaultHeight = 30;
$defaultImageHandler = \OxidEsales\Eshop\Core\Registry::getUtilsPic();
$expectedResized = $defaultImageDirUrl . "resized_logo.png";
$expectedOriginal = $defaultImageDirUrl . $defaultImageName;
return array(
array($defaultImageDir, $defaultImageDirUrl, $defaultImageName, 30, 30, $defaultWidth, $defaultHeight, $defaultImageHandler, $expectedOriginal),
array($defaultImageDir, $defaultImageDirUrl, $defaultImageName, 50, 50, $defaultWidth, $defaultHeight, $defaultImageHandler, $expectedResized),
array(null, $defaultImageDirUrl, $defaultImageName, 40, 40, $defaultWidth, $defaultHeight, $defaultImageHandler, false),
array($defaultImageDir, $defaultImageDirUrl, null, 50, 50, $defaultWidth, $defaultHeight, $defaultImageHandler, false),
array($defaultImageDir, $defaultImageDirUrl, $defaultImageName, 60, 60, $defaultWidth, $defaultHeight, null, $expectedOriginal),
array($defaultImageDir . "donotexist", $defaultImageDirUrl, $defaultImageName, 60, 60, $defaultWidth, $defaultHeight, $defaultImageHandler, false),
array($defaultImageDir, $defaultImageDirUrl, "donotexist.png", 60, 60, $defaultWidth, $defaultHeight, $defaultImageHandler, false),
array($defaultImageDir, $defaultImageDirUrl, $defaultImageName, 60, 60, 2000, 1000, $defaultImageHandler, $expectedOriginal),
array($defaultImageDir, $defaultImageDirUrl, $defaultImageName, 2000, 1000, 60, 60, $defaultImageHandler, $expectedResized),
);
}
/**
* Checks getShopLogo with all possible ways to pass parameters
*
* @dataProvider getShopLogoUrlProvider
*/
public function testGetShopLogoUrl($imageDir, $imageDirUrl, $imageName, $imgWidth, $imgHeight, $width, $height, $imageHandler, $result)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\ShopLogo::class);
$mockBuilder->setMethods(['resizeImage', 'getImageSize']);
$logo = $mockBuilder->getMock();
$logo->expects($this->any())->method('resizeImage')->will($this->returnValue(!empty($imageHandler)));
$logo->expects($this->any())->method('getImageSize')->will($this->returnValue(array('width' => $imgWidth, 'height' => $imgHeight)));
$logo->setImageDir($imageDir);
$logo->setImageDirUrl($imageDirUrl);
$logo->setImageName($imageName);
$logo->setWidth($width);
$logo->setHeight($height);
$logo->setImageHandler($imageHandler);
$this->assertEquals($result, $logo->getShopLogoUrl());
$this->cleanUp($imageName);
}
/**
* Cleans out the images that are created before image tests
*/
protected function cleanUp($imageName)
{
$imgDir = $this->getConfig()->getImageDir();
$logoDir = $imgDir . "resized_$imageName";
if (!file_exists($logoDir)) {
return;
}
unlink($logoDir);
}
}

View File

@@ -0,0 +1,83 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
/**
* Tests for oeThemeSwitcherUserAgent class
*/
class UserAgentTest extends BaseUnitTest
{
public function providerIsMobile()
{
return array(
array('Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3', 'mobile'),
array('Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C)', 'desktop'),
array('Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3A100a Safari/419.3', 'mobile'),
array('Mozilla/5.0 (webOS/1.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/1.0', 'mobile'),
array('Mozilla/4.0 (compatible; MSIE 8.0; AOL 9.1; AOLBuild 4334.34; Windows NT 5.1; SV1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322)', 'desktop'),
array('Mozilla/5.0 (Linux; U; Android 0.5; en-us) AppleWebKit/522+ (KHTML, like Gecko) Safari/419.3', 'mobile'),
array('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0', 'desktop')
);
}
/**
* Check if given device type is mobile
*
* @dataProvider providerIsMobile
*/
public function testDeviceType_Detect($userAgent, $type)
{
$_SERVER['HTTP_USER_AGENT'] = $userAgent;
$userAgent = new \OxidEsales\PayPalModule\Core\UserAgent();
$this->assertEquals($type, $userAgent->getDeviceType());
}
/**
* Tests getter if it is not null and if there is separators
*/
public function testGetMobileDevicesTypes_NotNullAndWithSeparators()
{
$userAgent = new \OxidEsales\PayPalModule\Core\UserAgent();
$mobileDevicesTypes = $userAgent->getMobileDeviceTypes();
$this->doAssertStringContainsString('iphone|', $mobileDevicesTypes);
}
/**
* Tests for mobile device types setter and getter
*/
public function testGetMobileDevicesTypes_SetAndGet()
{
$userAgent = new \OxidEsales\PayPalModule\Core\UserAgent();
$userAgent->setMobileDeviceTypes('testDevice1|testDevice2');
$this->assertEquals('testDevice1|testDevice2', $userAgent->getMobileDeviceTypes());
}
/**
* Tests device type for setter and getter
*/
public function testGetDeviceType_SetAndGet()
{
$userAgent = new \OxidEsales\PayPalModule\Core\UserAgent();
$userAgent->setDeviceType('mobile');
$this->assertEquals('mobile', $userAgent->getDeviceType());
}
}

View File

@@ -0,0 +1,431 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Core;
use OxidEsales\Eshop\Application\Model\Payment;
use OxidEsales\Eshop\Core\ViewConfig;
/**
* Testing \OxidEsales\PayPalModule\Core\ViewConfig class.
*/
class ViewConfigTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Tear down the fixture.
*/
protected function tearDown(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDB()->execute("delete from oxpayments where OXID = 'oxidpaypal' ");
parent::tearDown();
}
/**
* Test case for ViewConfig::isStandardCheckoutEnabled()
*/
public function testIsStandardCheckoutEnabled()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Config::class);
$mockBuilder->setMethods(['isStandardCheckoutEnabled']);
$payPalConfig = $mockBuilder->getMock();
$payPalConfig->expects($this->once())->method("isStandardCheckoutEnabled")->will($this->returnValue(true));
$mockBuilder = $this->getMockBuilder(ViewConfig::class);
$mockBuilder->setMethods(['getPayPalConfig']);
$mockBuilder->setConstructorArgs([$payPalConfig, null, null]);
$view = $mockBuilder->getMock();
$view->expects($this->once())->method("getPayPalConfig")->will($this->returnValue($payPalConfig));
$this->assertTrue($view->isStandardCheckoutEnabled());
}
/**
* Test case for ViewConfig::isExpressCheckoutEnabledInDetails()
*/
public function testIsExpressCheckoutEnabledCheckoutIsEnabledTrue()
{
$this->getConfig()->setConfigParam('blOEPayPalExpressCheckout', true);
$view = oxNew(\OxidEsales\Eshop\Core\ViewConfig::class);
$validator = $this->_createStub(\OxidEsales\PayPalModule\Model\PaymentValidator::class, array('isPaymentValid' => true));
$view->setPaymentValidator($validator);
$this->assertTrue($view->isExpressCheckoutEnabled());
}
/**
* Test case for ViewConfig::isExpressCheckoutEnabledInDetails()
*/
public function testIsExpressCheckoutEnabledWhenCheckoutIsDisabled()
{
$this->getConfig()->setConfigParam('blOEPayPalExpressCheckout', false);
$view = oxNew(\OxidEsales\Eshop\Core\ViewConfig::class);
$validator = $this->_createStub(\OxidEsales\PayPalModule\Model\PaymentValidator::class, array('isPaymentValid' => true));
$view->setPaymentValidator($validator);
$this->assertFalse($view->isExpressCheckoutEnabled());
}
/**
* Test case for ViewConfig::isExpressCheckoutEnabledInDetails()
*/
public function testIsExpressCheckoutEnabledWhenPaymentNotValid()
{
$this->getConfig()->setConfigParam('blOEPayPalExpressCheckout', true);
$view = oxNew(\OxidEsales\PayPalModule\Core\ViewConfig::class);
$validator = $this->_createStub(\OxidEsales\PayPalModule\Model\PaymentValidator::class, array('isPaymentValid' => false));
$view->setPaymentValidator($validator);
$this->assertFalse($view->isExpressCheckoutEnabled());
}
/**
* Test case for ViewConfig::isExpressCheckoutEnabledInDetails()
*/
public function testIsExpressCheckoutEnabledInDetailsWhenExpressCheckoutIsEnabled()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\ViewConfig::class);
$mockBuilder->setMethods(['isExpressCheckoutEnabled']);
$view = $mockBuilder->getMock();
$view->expects($this->exactly(2))->method("isExpressCheckoutEnabled")->will($this->returnValue(true));
$this->getConfig()->setConfigParam('blOEPayPalECheckoutInDetails', true);
$this->assertTrue($view->isExpressCheckoutEnabledInDetails());
$this->getConfig()->setConfigParam('blOEPayPalECheckoutInDetails', false);
$this->assertFalse($view->isExpressCheckoutEnabledInDetails());
}
/**
* Test case for ViewConfig::isExpressCheckoutEnabledInDetails()
*/
public function testIsExpressCheckoutEnabledInDetailsWhenExpressCheckoutIsDisabled()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\ViewConfig::class);
$mockBuilder->setMethods(['isExpressCheckoutEnabled']);
$view = $mockBuilder->getMock();
$view->expects($this->exactly(2))->method("isExpressCheckoutEnabled")->will($this->returnValue(false));
$this->getConfig()->setConfigParam('blOEPayPalECheckoutInDetails', true);
$this->assertFalse($view->isExpressCheckoutEnabledInDetails());
$this->getConfig()->setConfigParam('blOEPayPalECheckoutInDetails', false);
$this->assertFalse($view->isExpressCheckoutEnabledInDetails());
}
/**
* Test case for ViewConfig::isExpressCheckoutEnabledInMiniBasket()
*/
public function testIsExpressCheckoutEnabledInMiniBasketWhenExpressCheckoutIsEnabled()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\ViewConfig::class);
$mockBuilder->setMethods(['isExpressCheckoutEnabled']);
$view = $mockBuilder->getMock();
$view->expects($this->exactly(2))->method("isExpressCheckoutEnabled")->will($this->returnValue(true));
$this->getConfig()->setConfigParam('blOEPayPalECheckoutInMiniBasket', true);
$this->assertTrue($view->isExpressCheckoutEnabledInMiniBasket());
$this->getConfig()->setConfigParam('blOEPayPalECheckoutInMiniBasket', false);
$this->assertFalse($view->isExpressCheckoutEnabledInMiniBasket());
}
/**
* Test case for ViewConfig::isExpressCheckoutEnabledInMiniBasket()
*/
public function testIsExpressCheckoutEnabledInMiniBasketWhenExpressCheckoutIsDisabled()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\ViewConfig::class);
$mockBuilder->setMethods(['isExpressCheckoutEnabled']);
$view = $mockBuilder->getMock();
$view->expects($this->exactly(2))->method("isExpressCheckoutEnabled")->will($this->returnValue(false));
$this->getConfig()->setConfigParam('blOEPayPalECheckoutInMiniBasket', true);
$this->assertFalse($view->isExpressCheckoutEnabledInMiniBasket());
$this->getConfig()->setConfigParam('blOEPayPalECheckoutInMiniBasket', false);
$this->assertFalse($view->isExpressCheckoutEnabledInMiniBasket());
}
/**
* Test case for ViewConfig::getPayPalPaymentDescription()
*/
public function testGetPayPalPaymentDescription()
{
$query = "INSERT INTO `oxpayments` (`OXID`, `OXACTIVE`, `OXDESC`, `OXLONGDESC`) VALUES ('oxidpaypal', 1, 'PayPal', 'testLongDesc')";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query);
$view = oxNew(\OxidEsales\Eshop\Core\ViewConfig::class);
$this->assertEquals('testLongDesc', $view->getPayPalPaymentDescription());
}
/**
* Test case for ViewConfig::getPayPalPayment()
*/
public function testGetPayPalPayment()
{
$query = "INSERT INTO `oxpayments` (`OXID`, `OXACTIVE`, `OXDESC`, `OXLONGDESC`) VALUES ('oxidpaypal', 1, 'PayPal', 'testLongDesc')";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query);
$view = oxNew(\OxidEsales\Eshop\Core\ViewConfig::class);
$payment = $view->getPayPalPayment();
$this->assertTrue($payment instanceof Payment);
$this->assertEquals("oxidpaypal", $payment->getId());
}
/**
* Test case for ViewConfig::sendOrderInfoToPayPal()
*/
public function testSendOrderInfoToPayPal()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Config::class);
$mockBuilder->setMethods(['sendOrderInfoToPayPal']);
$payPalConfig = $mockBuilder->getMock();
$payPalConfig->expects($this->once())->method("sendOrderInfoToPayPal")->will($this->returnValue(true));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\ViewConfig::class);
$mockBuilder->setMethods(['getPayPalConfig']);
$mockBuilder->setConstructorArgs([$payPalConfig, null, null]);
$view = $mockBuilder->getMock();
$view->expects($this->once())->method("getPayPalConfig")->will($this->returnValue($payPalConfig));
$this->assertTrue($view->sendOrderInfoToPayPal());
}
/**
* Test case for ViewConfig::sendOrderInfoToPayPal()
*/
public function testSendOrderInfoToPayPalWhenFractionQuantityArticleIsInBasket()
{
$this->getConfig()->setConfigParam('blOEPayPalSendToPayPal', true);
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Article::class);
$mockBuilder->setMethods(['getAmount']);
$article = $mockBuilder->getMock();
$article->expects($this->any())->method('getAmount')->will($this->returnValue(5.6));
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Basket::class);
$mockBuilder->setMethods(['getContents']);
$basket = $mockBuilder->getMock();
$basket->expects($this->any())->method('getContents')->will($this->returnValue(array($article)));
$this->getSession()->setBasket($basket);
$view = oxNew(\OxidEsales\Eshop\Core\ViewConfig::class);
$this->assertFalse($view->sendOrderInfoToPayPal());
}
/**
* Test case for ViewConfig::sendOrderInfoToPayPal()
*/
public function testSendOrderInfoToPayPalWhenNoFractionQuantityArticleIsInBasket()
{
$this->getConfig()->setConfigParam('blOEPayPalSendToPayPal', true);
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Article::class);
$mockBuilder->setMethods(['getAmount']);
$article = $mockBuilder->getMock();
$article->expects($this->any())->method('getAmount')->will($this->returnValue(5));
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Basket::class);
$mockBuilder->setMethods(['getContents']);
$basket = $mockBuilder->getMock();
$basket->expects($this->any())->method('getContents')->will($this->returnValue(array($article)));
$this->getSession()->setBasket($basket);
$view = oxNew(\OxidEsales\Eshop\Core\ViewConfig::class);
$this->assertTrue($view->sendOrderInfoToPayPal());
}
/**
* Test case for ViewConfig::sendOrderInfoToPayPal()
*/
public function testSendOrderInfoToPayPalWhenBasketIsEmpty()
{
$this->getConfig()->setConfigParam('blOEPayPalSendToPayPal', true);
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Basket::class);
$mockBuilder->setMethods(['getContents']);
$basket = $mockBuilder->getMock();
$basket->expects($this->any())->method('getContents')->will($this->returnValue(array()));
$this->getSession()->setBasket($basket);
$view = oxNew(\OxidEsales\Eshop\Core\ViewConfig::class);
$this->assertTrue($view->sendOrderInfoToPayPal());
}
/**
* Checks if method returns correct current URL.
*/
public function testGetCurrentUrl()
{
$cancelURL = 'http://oxid-esales.com/test';
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Config::class);
$mockBuilder->setMethods(['getCurrentUrl']);
$payPalConfig = $mockBuilder->getMock();
$payPalConfig->expects($this->any())->method("getCurrentUrl")->will($this->returnValue($cancelURL));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\ViewConfig::class);
$mockBuilder->setMethods(['getPayPalConfig']);
$viewPayPalConfig = $mockBuilder->getMock();
$viewPayPalConfig->expects($this->any())->method("getPayPalConfig")->will($this->returnValue($payPalConfig));
$this->assertEquals($cancelURL, $viewPayPalConfig->getCurrentUrl());
}
/**
* Test case for ViewConfig::getPayPalClientId()
*/
public function testGetPayPalClientIdId()
{
$view = oxNew(\OxidEsales\Eshop\Core\ViewConfig::class);
$this->getConfig()->setConfigParam('oePayPalClientId', 'PayPalClientId');
$this->assertEquals('PayPalClientId', $view->getPayPalClientId());
}
/**
* Test case for ViewConfig::showPayPalBannerOnStartPage()
*/
public function testShowBannersStartPage()
{
$view = oxNew(\OxidEsales\Eshop\Core\ViewConfig::class);
$this->getConfig()->setConfigParam('oePayPalBannersHideAll', false);
$this->getConfig()->setConfigParam('oePayPalBannersStartPage', true);
$this->assertTrue($view->showPayPalBannerOnStartPage());
$this->getConfig()->setConfigParam('oePayPalBannersHideAll', true);
$this->assertFalse($view->showPayPalBannerOnStartPage());
}
/**
* Test case for ViewConfig::showPayPalBannerOnCategoryPage()
*/
public function testShowPayPalBannerOnCategoryPage()
{
$view = oxNew(\OxidEsales\Eshop\Core\ViewConfig::class);
$this->getConfig()->setConfigParam('oePayPalBannersHideAll', false);
$this->getConfig()->setConfigParam('oePayPalBannersCategoryPage', true);
$this->assertTrue($view->showPayPalBannerOnCategoryPage());
$this->getConfig()->setConfigParam('oePayPalBannersHideAll', true);
$this->assertFalse($view->showPayPalBannerOnCategoryPage());
}
/**
* Test case for ViewConfig::showPayPalBannerOnSearchResultsPage()
*/
public function testShowPayPalBannerOnSearchResultsPage()
{
$view = oxNew(\OxidEsales\Eshop\Core\ViewConfig::class);
$this->getConfig()->setConfigParam('oePayPalBannersHideAll', false);
$this->getConfig()->setConfigParam('oePayPalBannersSearchResultsPage', true);
$this->assertTrue($view->showPayPalBannerOnSearchResultsPage());
$this->getConfig()->setConfigParam('oePayPalBannersHideAll', true);
$this->assertFalse($view->showPayPalBannerOnSearchResultsPage());
}
/**
* Test case for ViewConfig::showPayPalBannerOnProductDetailsPage()
*/
public function testShowPayPalBannerOnProductDetailsPage()
{
$view = oxNew(\OxidEsales\Eshop\Core\ViewConfig::class);
$this->getConfig()->setConfigParam('oePayPalBannersHideAll', false);
$this->getConfig()->setConfigParam('oePayPalBannersProductDetailsPage', true);
$this->assertTrue($view->showPayPalBannerOnProductDetailsPage());
$this->getConfig()->setConfigParam('oePayPalBannersHideAll', true);
$this->assertFalse($view->showPayPalBannerOnProductDetailsPage());
}
/**
* Test case for ViewConfig::showPayPalBannerOnCheckoutPage()
*
* @dataProvider providerBannerCheckoutPage
*
* @param string $actionClassName
* @param string $selectorSetting
*/
public function showPayPalBannerOnCheckoutPage(string $actionClassName, string $selectorSetting)
{
$viewMock = $this
->getMockBuilder(\OxidEsales\PayPalModule\Core\ViewConfig::class)
->setMethods(['getActionClassName'])
->getMock();
$viewMock->expects($this->once())->method('getActionClassName')->will($this->returnValue($actionClassName));
$this->getConfig()->setConfigParam('oePayPalBannersHideAll', false);
$this->getConfig()->setConfigParam('oePayPalBannersCheckoutPage', true);
$this->assertTrue($viewMock->showPayPalBannerOnCheckoutPage());
$this->getConfig()->setConfigParam('oePayPalBannersHideAll', true);
$this->assertFalse($viewMock->showPayPalBannerOnCheckoutPage());
$this->getConfig()->setConfigParam('oePayPalBannersHideAll', false);
$this->getConfig()->setConfigParam($selectorSetting, '');
$this->assertFalse($viewMock->showPayPalBannerOnCheckoutPage());
}
public function providerBannerCheckoutPage()
{
return [
['basket', 'oePayPalBannersCartPageSelector'],
['payment', 'oePayPalBannersPaymentPageSelector']
];
}
/**
* Test case for ViewConfig::getPayPalBannersColorScheme()
*
* @dataProvider providerGetPayPalColorScheme
*/
public function testPayPalBannerColorScheme($colorScheme)
{
$view = oxNew(\OxidEsales\Eshop\Core\ViewConfig::class);
$this->getConfig()->setConfigParam('oePayPalBannersColorScheme', $colorScheme);
$this->assertEquals($colorScheme, $view->getPayPalBannersColorScheme());
}
public function providerGetPayPalColorScheme()
{
return [
['blue'],
['black'],
['white'],
['white-no-border'],
];
}
}

View File

@@ -0,0 +1,78 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Action\Data;
use OxidEsales\Eshop\Application\Model\Order;
/**
* Testing \OxidEsales\PayPalModule\Model\Action\Data\OrderActionData class.
*/
class OrderActionDataTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
*/
public function testGetAuthorizationId()
{
$request = $this->getRequest(array());
$order = $this->getOrder();
$order->oxorder__oxtransid = new \OxidEsales\Eshop\Core\Field('authorizationId');
$actionData = new \OxidEsales\PayPalModule\Model\Action\Data\OrderActionData($request, $order);
$this->assertEquals('authorizationId', $actionData->getAuthorizationId());
}
/**
*/
public function testGetAmount()
{
$request = $this->getRequest(array('action_comment' => 'comment'));
$order = $this->getOrder();
$actionData = new \OxidEsales\PayPalModule\Model\Action\Data\OrderActionData($request, $order);
$this->assertEquals('comment', $actionData->getComment());
}
/**
* Returns Request object with given parameters
*
* @param $params
*
* @return mixed
*/
protected function getRequest($params)
{
$request = $this->_createStub(\OxidEsales\PayPalModule\Core\Request::class, array('getGet' => $params));
return $request;
}
/**
*
*/
protected function getOrder()
{
$order = oxNew(Order::class);
return $order;
}
}

View File

@@ -0,0 +1,104 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Action\Data;
/**
* Testing \OxidEsales\PayPalModule\Model\Action\Data\OrderCaptureActionData class.
*/
class OrderCaptureActionDataTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function providerCaptureAmount()
{
return [
['59,92', '59.92'],
['59.92', '59.92'],
['1000,33', '1000.33'],
['10,000,33', '10,000.33']
];
}
/**
* Tests setting parameters from request
*
* @dataProvider providerCaptureAmount
*
* @param string $captureAmount
*/
public function testSettingParameters_FromRequest($captureAmount, $calculatedAmount)
{
$type = 'Full';
$params = array(
'capture_amount' => $captureAmount,
'capture_type' => $type,
);
$request = $this->_createStub(\OxidEsales\PayPalModule\Core\Request::class, array('getPost' => $params));
$order = $this->getOrder();
$actionData = new \OxidEsales\PayPalModule\Model\Action\Data\OrderCaptureActionData($request, $order);
$this->assertEquals($calculatedAmount, $actionData->getAmount());
$this->assertEquals($type, $actionData->getType());
}
/**
* Tests getting amount when amount is not set and no amount is passed with request. Should be taken from order
*/
public function testGetAmount_AmountNotSet_TakenFromOrder()
{
$remainingOrderSum = 59.67;
$payPalOrder = $this->_createStub(\OxidEsales\PayPalModule\Model\PayPalOrder::class, array('getRemainingOrderSum' => $remainingOrderSum));
$order = $this->_createStub(\OxidEsales\PayPalModule\Model\Order::class, array('getPayPalOrder' => $payPalOrder));
$request = $this->_createStub(\OxidEsales\PayPalModule\Core\Request::class, array('getPost' => array()));
$actionData = new \OxidEsales\PayPalModule\Model\Action\Data\OrderCaptureActionData($request, $order);
$this->assertEquals($remainingOrderSum, $actionData->getAmount());
}
/**
* Returns Request object with given parameters
*
* @param $params
*
* @return mixed
*/
protected function getRequest($params)
{
$request = $this->_createStub(\OxidEsales\PayPalModule\Core\Request::class, array('getGet' => $params));
return $request;
}
/**
* Returns PayPal order object
*
* @return \OxidEsales\PayPalModule\Model\PayPalOrder
*/
protected function getOrder()
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
return $order;
}
}

View File

@@ -0,0 +1,67 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Action\Data;
/**
* Testing \OxidEsales\PayPalModule\Model\Action\Data\OrderReauthorizeActionData class.
*/
class OrderReauthorizeActionDataTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Tests getting amount when amount is not set and no amount is passed with request. Should be taken from order
*/
public function testGetAmount_AmountNotSet_TakenFromOrder()
{
$remainingOrderSum = 59.67;
$payPalOrder = $this->_createStub(\OxidEsales\PayPalModule\Model\PayPalOrder::class, array('getRemainingOrderSum' => $remainingOrderSum));
$order = $this->_createStub(\OxidEsales\PayPalModule\Model\Order::class, array('getPayPalOrder' => $payPalOrder));
$request = $this->_createStub(\OxidEsales\PayPalModule\Core\Request::class, array('getPost' => array()));
$actionData = new \OxidEsales\PayPalModule\Model\Action\Data\OrderReauthorizeActionData($request, $order);
$this->assertEquals($remainingOrderSum, $actionData->getAmount());
}
/**
* Returns Request object with given parameters
*
* @param $params
*
* @return mixed
*/
protected function getRequest($params)
{
$request = $this->_createStub(\OxidEsales\PayPalModule\Core\Request::class, array('getGet' => $params));
return $request;
}
/**
*
*/
protected function getOrder()
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
return $order;
}
}

View File

@@ -0,0 +1,134 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Action\Data;
/**
* Testing \OxidEsales\PayPalModule\Model\Action\Data\OrderRefundActionData class.
*/
class OrderRefundActionDataTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function providerRefundAmount()
{
return [
['59,92', '59.92'],
['59.92', '59.92'],
['1000,33', '1000.33'],
['10,000,33', '10,000.33']
];
}
/**
* Tests setting parameters from request
*
* @dataProvider providerRefundAmount
*
* @param string $refundAmount
*/
public function testSettingParameters_FromRequest($refundAmount, $calculatedAmount)
{
$transactionId = '123456';
$type = 'Full';
$params = array(
'transaction_id' => $transactionId,
'refund_amount' => $refundAmount,
'refund_type' => $type,
);
$request = $this->_createStub(\OxidEsales\PayPalModule\Core\Request::class, array('getPost' => $params));
$order = $this->getOrder();
$actionData = new \OxidEsales\PayPalModule\Model\Action\Data\OrderRefundActionData($request, $order);
$this->assertEquals($transactionId, $actionData->getTransactionId());
$this->assertEquals($calculatedAmount, $actionData->getAmount());
$this->assertEquals($type, $actionData->getType());
}
/**
* Tests getting amount when amount is not set and no amount is passed with request. Should be taken from order
*/
public function testGetAmount_AmountNotSet_TakenFromOrderPayment()
{
$remainingRefundSum = 59.67;
$payment = $this->_createStub('oePayPalPayPalOrderPayment', array('getRemainingRefundAmount' => $remainingRefundSum));
$request = $this->_createStub(\OxidEsales\PayPalModule\Core\Request::class, array('getPost' => array()));
$order = $this->getOrder();
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Action\Data\OrderRefundActionData::class);
$mockBuilder->setMethods(['getPaymentBeingRefunded']);
$mockBuilder->setConstructorArgs([$request, $order]);
$actionData = $mockBuilder->getMock();
$actionData->expects($this->any())->method('getPaymentBeingRefunded')->will($this->returnValue($payment));
$this->assertEquals($remainingRefundSum, $actionData->getAmount());
}
/**
* Test loading of payment by transaction id
*/
public function testGetPaymentBeingRefunded_LoadedByTransactionId_TransactionIdSet()
{
$transactionId = 'test_transId';
$payment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$payment->setTransactionId($transactionId);
$payment->setOrderId('_testOrderId');
$payment->save();
$params = array('transaction_id' => $transactionId);
$request = $this->_createStub(\OxidEsales\PayPalModule\Core\Request::class, array('getPost' => $params));
$order = $this->getOrder();
$actionData = new \OxidEsales\PayPalModule\Model\Action\Data\OrderRefundActionData($request, $order);
$payment = $actionData->getPaymentBeingRefunded();
$this->assertEquals($transactionId, $payment->getTransactionId());
}
/**
* Returns Request object with given parameters
*
* @param $params
*
* @return mixed
*/
protected function getRequest($params)
{
$request = $this->_createStub(\OxidEsales\PayPalModule\Core\Request::class, array('getGet' => $params));
return $request;
}
/**
*
*/
protected function getOrder()
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
return $order;
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Action\Data;
/**
* Testing \OxidEsales\PayPalModule\Model\Action\Data\OrderVoidActionData class.
*/
class OrderVoidActionDataTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Tests getting amount when amount is not set and no amount is passed with request. Should be taken from order
*/
public function testGetAmount_AmountNotSet_TakenFromOrder()
{
$remainingOrderSum = 59.67;
$payPalOrder = $this->_createStub(\OxidEsales\PayPalModule\Model\PayPalOrder::class, array('getRemainingOrderSum' => $remainingOrderSum));
$order = $this->_createStub(\OxidEsales\PayPalModule\Model\Order::class, array('getPayPalOrder' => $payPalOrder));
$request = $this->_createStub(\OxidEsales\PayPalModule\Core\Request::class, array('getPost' => array()));
$action = new \OxidEsales\PayPalModule\Model\Action\Data\OrderVoidActionData($request, $order);
$this->assertEquals($remainingOrderSum, $action->getAmount());
}
/**
* Returns Request object with given parameters
*
* @param $params
*
* @return mixed
*/
protected function getRequest($params)
{
$request = $this->_createStub(\OxidEsales\PayPalModule\Core\Request::class, array('getGet' => $params));
return $request;
}
}

View File

@@ -0,0 +1,108 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Action\Handler;
/**
* Testing \OxidEsales\PayPalModule\Model\Action\Handler\OrderCaptureActionHandler class.
*/
class OrderCaptureActionHandlerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Testing building of PayPal request when request is not set
*/
public function testGetPayPalRequest_RequestIsNotSet_BuildsRequest()
{
$authId = '123456';
$amount = 59.67;
$currency = "LTU";
$type = 'Full';
$comment = 'Comment';
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequestBuilder::class);
$mockBuilder->setMethods(['setAuthorizationId', 'setAmount', 'setCompleteType', 'setComment']);
$builder = $mockBuilder->getMock();
$builder->expects($this->once())->method('setAuthorizationId')->with($this->equalTo($authId));
$builder->expects($this->once())->method('setAmount')->with($this->equalTo($amount), $this->equalTo($currency));
$builder->expects($this->once())->method('setCompleteType')->with($this->equalTo($type));
$builder->expects($this->once())->method('setComment')->with($this->equalTo($comment));
$data = $this->_createStub(
'Data', array(
'getAuthorizationId' => $authId,
'getAmount' => $amount,
'getType' => $type,
'getComment' => $comment,
'getCurrency' => $currency,
)
);
$actionHandler = $this->getActionHandler($data);
$actionHandler->setPayPalRequestBuilder($builder);
$actionHandler->getPayPalResponse();
}
/**
* Testing setting of correct request to PayPal service when creating response
*/
public function testGetPayPalResponse_SetsCorrectRequestToService()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest::class);
$payPalRequest = $mockBuilder->getMock();
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
$mockBuilder->setMethods(['doCapture']);
$checkoutService = $mockBuilder->getMock();
$checkoutService->expects($this->once())->method('doCapture')->with($this->equalTo($payPalRequest));
$action = $this->getActionHandler();
$action->setPayPalService($checkoutService);
$action->setPayPalRequest($payPalRequest);
$action->getPayPalResponse();
}
/**
* @return \OxidEsales\PayPalModule\Core\PayPalService|PHPUnit_Framework_MockObject_MockObject
*/
protected function getService()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
return $mockBuilder->getMock();
}
/**
* Returns capture action object
*
* @param $data
*
* @return \OxidEsales\PayPalModule\Model\Action\Handler\OrderCaptureActionHandler
*/
protected function getActionHandler($data = null)
{
$action = new \OxidEsales\PayPalModule\Model\Action\Handler\OrderCaptureActionHandler($data);
$action->setPayPalService($this->getService());
return $action;
}
}

View File

@@ -0,0 +1,101 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Action\Handler;
/**
* Testing \OxidEsales\PayPalModule\Model\Action\Handler\OrderReauthorizeActionHandler class.
*/
class OrderReauthorizeActionHandlerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Testing building of PayPal request when request is not set
*/
public function testGetPayPalRequest_RequestIsNotSet_BuildsRequest()
{
$authId = '123456';
$currency = 'LTU';
$amount = 59.67;
$data = $this->_createStub(
'Data', array(
'getAuthorizationId' => $authId,
'getAmount' => $amount,
'getCurrency' => $currency,
)
);
$actionHandler = $this->getActionHandler($data);
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequestBuilder::class);
$mockBuilder->setMethods(['setAuthorizationId', 'setAmount', 'setCompleteType']);
$builder= $mockBuilder->getMock();
$builder->expects($this->once())->method('setAuthorizationId')->with($this->equalTo($authId));
$builder->expects($this->once())->method('setAmount')->with($this->equalTo($amount), $this->equalTo($currency));
$actionHandler->setPayPalRequestBuilder($builder);
$this->assertTrue($actionHandler->getPayPalRequest() instanceof \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest);
}
/**
* Testing setting of correct request to PayPal service when creating response
*/
public function testGetPayPalResponse_SetsCorrectRequestToService()
{
$actionHandler = $this->getActionHandler();
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest::class);
$payPalRequest = $mockBuilder->getMock();
$actionHandler->setPayPalRequest($payPalRequest);
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
$mockBuilder->setMethods(['doReAuthorization']);
$checkoutService = $mockBuilder->getMock();
$checkoutService->expects($this->once())->method('doReAuthorization')->with($this->equalTo($payPalRequest));
$actionHandler->setPayPalService($checkoutService);
$actionHandler->getPayPalResponse();
}
/**
* @return \OxidEsales\PayPalModule\Core\PayPalService
*/
protected function getService()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
return $mockBuilder->getMock();
}
/**
* Returns reauthorize action object
*
* @param $data
*
* @return \OxidEsales\PayPalModule\Model\Action\Handler\OrderReauthorizeActionHandler
*/
protected function getActionHandler($data = null)
{
$action = new \OxidEsales\PayPalModule\Model\Action\Handler\OrderReauthorizeActionHandler($data);
$action->setPayPalService($this->getService());
return $action;
}
}

View File

@@ -0,0 +1,143 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Action\Handler;
/**
* Testing \OxidEsales\PayPalModule\Model\Action\Handler\OrderRefundActionHandler class.
*/
class OrderRefundActionHandlerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Setup: Prepare data - create need tables
*/
protected function setUp(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpaymentcomments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpayments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_order`');
}
/**
* Testing building of PayPal request when request is not set
*/
public function testGetPayPalRequest_RequestIsNotSet_BuildsRequest()
{
$transId = '123456';
$currency = 'LTU';
$amount = 59.67;
$type = 'Full';
$comment = 'Comment';
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequestBuilder::class);
$mockBuilder->setMethods(['setTransactionId', 'setAmount', 'setRefundType', 'getRequest', 'setComment']);
$builder = $mockBuilder->getMock();
$builder->expects($this->atLeastOnce())->method('setTransactionId')->with($this->equalTo($transId));
$builder->expects($this->atLeastOnce())->method('setAmount')->with($this->equalTo($amount), $this->equalTo($currency));
$builder->expects($this->atLeastOnce())->method('setRefundType')->with($this->equalTo($type));
$builder->expects($this->atLeastOnce())->method('setComment')->with($this->equalTo($comment));
$builder->expects($this->any())->method('getRequest')->will($this->returnValue(new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest()));
$data = $this->_createStub(
'Data', array(
'getTransactionId' => $transId,
'getAmount' => $amount,
'getType' => $type,
'getComment' => $comment,
'getCurrency' => $currency,
)
);
$actionHandler = $this->getActionHandler($data);
$actionHandler->setPayPalRequestBuilder($builder);
$actionHandler->getPayPalResponse();
}
/**
* Testing setting of correct request to PayPal service when creating response
*/
public function testGetPayPalResponse_SetsCorrectRequestToService()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest::class);
$payPalRequest = $mockBuilder->getMock();
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
$mockBuilder->setMethods(['refundTransaction']);
$checkoutService = $mockBuilder->getMock();
$checkoutService->expects($this->once())
->method('refundTransaction')
->with($this->equalTo($payPalRequest))
->will($this->returnValue(null));
$action = $this->getActionHandler();
$action->setPayPalService($checkoutService);
$action->setPayPalRequest($payPalRequest);
$action->getPayPalResponse();
}
/**
* Testing returning of returning response object formed by service
*/
public function testGetResponse_ReturnsResponseFromService()
{
$payPalRequest = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest();
$payPalResponse = new \OxidEsales\PayPalModule\Model\Response\ResponseDoRefund();
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
$mockBuilder->setMethods(['refundTransaction']);
$checkoutService = $mockBuilder->getMock();
$checkoutService->expects($this->once())
->method('refundTransaction')
->will($this->returnValue($payPalResponse));
$action = $this->getActionHandler();
$action->setPayPalService($checkoutService);
$action->setPayPalRequest($payPalRequest);
$this->assertEquals($payPalResponse, $action->getPayPalResponse());
}
/**
* @return \OxidEsales\PayPalModule\Core\PayPalService|\PHPUnit_Framework_MockObject_MockObject
*/
protected function getService()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
return $mockBuilder->getMock();
}
/**
* Returns capture action object
*
* @param $data
*
* @return \OxidEsales\PayPalModule\Model\Action\Handler\OrderRefundActionHandler
*/
protected function getActionHandler($data = null)
{
$action = new \OxidEsales\PayPalModule\Model\Action\Handler\OrderRefundActionHandler($data);
$action->setPayPalService($this->getService());
return $action;
}
}

View File

@@ -0,0 +1,108 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Action\Handler;
/**
* Testing \OxidEsales\PayPalModule\Model\Action\Handler\OrderVoidActionHandler class.
*/
class OrderVoidActionHandlerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Testing building of PayPal request when request is not set
*/
public function testGetPayPalRequest_RequestIsNotSet_BuildsRequest()
{
$authId = '123456';
$currency = 'LTU';
$amount = 59.67;
$comment = "Comment";
$data = $this->_createStub(
'Data', array(
'getAuthorizationId' => $authId,
'getAmount' => $amount,
'getComment' => $comment,
'getCurrency' => $currency,
)
);
$actionHandler = $this->getActionHandler($data);
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequestBuilder::class);
$mockBuilder->setMethods(['setAuthorizationId', 'setAmount', 'setCompleteType', 'getRequest', 'setComment']);
$builder = $mockBuilder->getMock();
$builder->expects($this->once())->method('setAuthorizationId')->with($this->equalTo($authId));
$builder->expects($this->once())->method('setAmount')->with($this->equalTo($amount), $this->equalTo($currency));
$builder->expects($this->once())->method('setComment')->with($this->equalTo($comment));
$builder->expects($this->once())->method('getRequest')->will($this->returnValue(new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest()));
$actionHandler->setPayPalRequestBuilder($builder);
$actionHandler->getPayPalRequest();
}
/**
* Testing setting of correct request to PayPal service when creating response
*/
public function testGetPayPalResponse_SetsCorrectRequestToService()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest::class);
$payPalRequest = $mockBuilder->getMock();
$actionHandler = $this->getActionHandler();
$actionHandler->setPayPalRequest($payPalRequest);
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
$mockBuilder->setMethods(['doVoid']);
$checkoutService = $mockBuilder->getMock();
$checkoutService->expects($this->once())
->method('doVoid')
->with($this->equalTo($payPalRequest))
->will($this->returnValue(null));
$actionHandler->setPayPalService($checkoutService);
$actionHandler->getPayPalResponse();
}
/**
* @return \OxidEsales\PayPalModule\Core\PayPalService|PHPUnit_Framework_MockObject_MockObject
*/
protected function getService()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
return $mockBuilder->getMock();
}
/**
* Returns capture action object
*
* @param $data
*
* @return \OxidEsales\PayPalModule\Model\Action\OrderCaptureAction
*/
protected function getActionHandler($data = null)
{
$action = new \OxidEsales\PayPalModule\Model\Action\Handler\OrderVoidActionHandler($data);
$action->setPayPalService($this->getService());
return $action;
}
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Action;
use \OxidEsales\PayPalModule\Core\Exception\PayPalInvalidActionException;
/**
* Testing \OxidEsales\PayPalModule\Model\Action\OrderActionFactory class.
*/
class OrderActionFactoryTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Data provider for testCreateAction
*/
public function providerCreateAction()
{
return array(
array('capture', \OxidEsales\PayPalModule\Model\Action\OrderCaptureAction::class),
array('refund', \OxidEsales\PayPalModule\Model\Action\OrderRefundAction::class),
array('void', \OxidEsales\PayPalModule\Model\Action\OrderVoidAction::class),
);
}
/**
* Test case for \OxidEsales\PayPalModule\Model\Action\OrderActionFactory::createAction
* Testing action object creation with correct actions
*
* @dataProvider providerCreateAction
*/
public function testCreateAction($action, $class)
{
$order = oxNew(\OxidEsales\PayPalModule\Model\Order::class);
$request = new \OxidEsales\PayPalModule\Core\Request();
$actionFactory = new \OxidEsales\PayPalModule\Model\Action\OrderActionFactory($request, $order);
$this->assertTrue($actionFactory->createAction($action) instanceof $class);
}
/**
* Test case for \OxidEsales\PayPalModule\Model\Action\OrderActionFactory::createAction
* Testing action object creation with incorrect actions
*/
public function testCreateActionWithInvalidData()
{
$this->expectException(PayPalInvalidActionException::class);
$order = oxNew(\OxidEsales\PayPalModule\Model\Order::class);
$request = new \OxidEsales\PayPalModule\Core\Request();
$actionFactory = new \OxidEsales\PayPalModule\Model\Action\OrderActionFactory($request, $order);
$actionFactory->createAction('some_non_existing_action');
}
}

View File

@@ -0,0 +1,43 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Action;
/**
* Testing \OxidEsales\PayPalModule\Model\Action\OrderAction class.
*/
class OrderActionTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Tests setting and getting of request object
*/
public function testSetGetDependencies()
{
$order = new \stdClass();
$handler = new \stdClass();
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Action\OrderAction::class);
$mockBuilder->setMethods(['process']);
$mockBuilder->setConstructorArgs([$handler, $order]);
$action = $mockBuilder->getMock();
$this->assertSame($order, $action->getOrder());
$this->assertSame($handler, $action->getHandler());
}
}

View File

@@ -0,0 +1,310 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Action;
use stdClass;
/**
* Testing \OxidEsales\PayPalModule\Model\Action\OrderCaptureAction class.
*/
class OrderCaptureActionTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Testing addition of captured amount to order
*/
public function testProcess_CapturedAmountAddedToOrder()
{
$amount = 59.67;
$payPalResponse = $this->getPayPalResponse(array('getCapturedAmount'));
$payPalResponse->expects($this->any())->method('getCapturedAmount')->will($this->returnValue($amount));
$order = $this->getOrder(array('addCapturedAmount'));
$order->expects($this->once())->method('addCapturedAmount')->with($this->equalTo($amount));
$action = $this->getAction($payPalResponse, $order);
$action->process();
}
/**
* Testing new payment creation with correct data after PayPal request is processed
*/
public function testProcess_NewPaymentCreated_WithCorrectData()
{
$transactionId = 'transactionId';
$correlationId = 'correlationId';
$status = 'Completed';
$amount = 59.67;
$currency = 'EUR';
$date = 'date';
$payPalResponseMethods = array(
'getTransactionId' => $transactionId,
'getCorrelationId' => $correlationId,
'getPaymentStatus' => $status,
'getCapturedAmount' => $amount,
'getCurrency' => $currency,
);
$payPalResponse = $this->_createStub(\OxidEsales\PayPalModule\Model\Response\ResponseDoCapture::class, $payPalResponseMethods);
$payment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$payment->setDate($date);
$payment->setTransactionId($transactionId);
$payment->setCorrelationId($correlationId);
$payment->setAction('capture');
$payment->setStatus($status);
$payment->setAmount($amount);
$payment->setCurrency($currency);
$paymentList = $this->getPaymentList(array('addPayment'));
$paymentList->expects($this->once())
->method('addPayment')
->with($payment)
->will($this->returnValue($payment));
$order = $this->getOrder(array('getPaymentList'));
$order->expects($this->once())
->method('getPaymentList')
->will($this->returnValue($paymentList));
$action = $this->getAction($payPalResponse, $order);
$action->process();
}
/**
* Testing saving of order after updating it
*/
public function testProcess_ProcessingOfServiceResponse_OrderSaved()
{
$payPalResponse = $this->getPayPalResponse();
$order = $this->getOrder(array('save'));
$order->expects($this->atLeastOnce())
->method('save')
->will($this->returnValue(null));
$action = $this->getAction($payPalResponse, $order);
$action->process();
}
/**
* Testing addition of comment after PayPal request processing
*/
public function testProcess_ProcessingOfServiceResponse_CommentAdded()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\UtilsDate::class);
$mockBuilder->setMethods(['getTime']);
$utilsDate = $mockBuilder->getMock();
$utilsDate->expects($this->any())->method('getTime')->will($this->returnValue(1410431540));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\UtilsDate::class, $utilsDate);
$commentContent = 'testComment';
$comment = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$comment->setComment($commentContent);
$payPalResponse = $this->getPayPalResponse();
$payment = $this->getPayment();
$payment->expects($this->once())->method('addComment')->with($this->equalTo($comment));
$paymentList = $this->getPaymentList(array('addPayment'));
$paymentList->expects($this->any())->method('addPayment')->will($this->returnValue($payment));
$order = $this->getOrder(array('getPaymentList'));
$order->expects($this->any())->method('getPaymentList')->will($this->returnValue($paymentList));
$data = $this->getData();
$data->expects($this->any())->method('getComment')->will($this->returnValue($commentContent));
$action = $this->getAction($payPalResponse, $order, $data);
$action->process();
}
/**
* Testing reauthorizing
*/
public function testProcess_Reauthorizing_FirstCapture()
{
$payPalResponse = $this->getPayPalResponse();
$order = $this->getOrder(array('getCapturedAmount'));
$order->expects($this->any())->method('getCapturedAmount')->will($this->returnValue(0));
$reauthorizePayPalResponse = $this->getPayPalResponse();
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Action\Handler\OrderReauthorizeActionHandler::class);
$mockBuilder->setMethods(['getPayPalResponse']);
$mockBuilder->setConstructorArgs([new stdClass()]);
$reauthorizeHandler = $mockBuilder->getMock();
$reauthorizeHandler->expects($this->never())->method('getPayPalResponse')->will($this->returnValue($reauthorizePayPalResponse));
$action = $this->getAction($payPalResponse, $order, null, $reauthorizeHandler);
$action->process();
}
/**
* Testing reauthorizing
*/
public function testProcess_Reauthorizing_AlreadyCaptured()
{
$payPalResponse = $this->getPayPalResponse();
$order = $this->getOrder(array('getCapturedAmount'));
$order->expects($this->any())->method('getCapturedAmount')->will($this->returnValue(0.01));
$reauthorizePayPalResponse = $this->getPayPalResponse();
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Action\Handler\OrderReauthorizeActionHandler::class);
$mockBuilder->setMethods(['getPayPalResponse']);
$mockBuilder->setConstructorArgs([new stdClass()]);
$reauthorizeHandler = $mockBuilder->getMock();
$reauthorizeHandler->expects($this->once())->method('getPayPalResponse')->will($this->returnValue($reauthorizePayPalResponse));
$action = $this->getAction($payPalResponse, $order, null, $reauthorizeHandler);
$action->process();
}
/**
* Testing addition of comment after PayPal request processing
*/
public function testProcess_Reauthorizing_ExceptionThrown()
{
$payPalResponse = $this->getPayPalResponse();
$order = $this->getOrder(array('getCapturedAmount'));
$order->expects($this->any())->method('getCapturedAmount')->will($this->returnValue(0.01));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Action\Handler\OrderReauthorizeActionHandler::class);
$mockBuilder->setMethods(['getPayPalResponse']);
$mockBuilder->setConstructorArgs([new stdClass()]);
$reauthorizeHandler = $mockBuilder->getMock();
$reauthorizeHandler->expects($this->once())->method('getPayPalResponse')->will($this->throwException(new \OxidEsales\PayPalModule\Core\Exception\PayPalResponseException()));
$action = $this->getAction($payPalResponse, $order, null, $reauthorizeHandler);
$action->process();
}
/**
* Returns payment object
*
* @return \OxidEsales\PayPalModule\Model\OrderPayment
*/
protected function getPayment()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\OrderPayment::class);
$mockBuilder->setMethods(['addComment']);
return $mockBuilder->getMock();
}
/**
* Returns payment list
*
* @param array $testMethods
*
* @return \OxidEsales\PayPalModule\Model\OrderPaymentList
*/
protected function getPaymentList($testMethods = array())
{
$methods = array('addPayment' => $this->getPayment());
$paymentList = $this->_createStub(\OxidEsales\PayPalModule\Model\OrderPaymentList::class, $methods, $testMethods);
return $paymentList;
}
/**
* Returns order
*
* @param array $testMethods
*
* @return \OxidEsales\PayPalModule\Model\PayPalOrder
*/
protected function getOrder($testMethods = array())
{
$methods = array('getPaymentList' => $this->getPaymentList(), 'save' => true);
$order = $this->_createStub(\OxidEsales\PayPalModule\Model\PayPalOrder::class, $methods, $testMethods);
return $order;
}
/**
* Retruns basic PayPal response object
*
* @param array $testMethods
*
* @return \OxidEsales\PayPalModule\Model\Response\ResponseDoCapture
*/
protected function getPayPalResponse($testMethods = array())
{
$methods = array('getCapturedAmount', 'getPaymentStatus', 'getAuthorizationId', 'getCurrency');
$mockedMethods = array_unique(array_merge($methods, $testMethods));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Response\ResponseDoCapture::class);
$mockBuilder->setMethods($mockedMethods);
return $mockBuilder->getMock();
}
/**
* Returns capture action data object
*
* @param $methods
*
* @return \OxidEsales\PayPalModule\Model\Action\Data\OrderCaptureActionData
*/
protected function getData($methods = array())
{
$data = $this->_createStub(\OxidEsales\PayPalModule\Model\Action\Data\OrderCaptureActionData::class, $methods);
return $data;
}
/**
* Returns capture action object
*
* @param $payPalResponse
* @param $order
* @param $data
* @param $reauthorizeHandler
*
* @return \OxidEsales\PayPalModule\Model\Action\OrderCaptureAction
*/
protected function getAction($payPalResponse, $order, $data = null, $reauthorizeHandler = null)
{
$data = $data ? $data : $this->getData();
$handler = $this->_createStub('CaptureActionHandler', array('getPayPalResponse' => $payPalResponse, 'getData' => $data));
$reauthorizeHandler = $reauthorizeHandler ? $reauthorizeHandler : $this->_createStub(\OxidEsales\PayPalModule\Model\Action\Handler\OrderReauthorizeActionHandler::class, array());
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Action\OrderCaptureAction::class);
$mockBuilder->setMethods(['getDate']);
$mockBuilder->setConstructorArgs([$handler, $order, $reauthorizeHandler]);
$action = $mockBuilder->getMock();
$action->expects($this->any())->method('getDate')->will($this->returnValue('date'));
return $action;
}
}

View File

@@ -0,0 +1,262 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
/**
* Testing \OxidEsales\PayPalModule\Model\Action\OrderRefundAction class.
*/
class OrderRefundActionTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Setup: Prepare data - create need tables
*/
protected function setUp(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpaymentcomments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpayments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_order`');
}
/**
* Testing addition of refunded amount to order
*/
public function testProcess_AddingRefundedAmountToOrder()
{
$amount = 59.67;
$payPalResponse = $this->getPayPalResponse(array('getRefundAmount'));
$payPalResponse->expects($this->any())
->method('getRefundAmount')
->will($this->returnValue($amount));
$order = $this->getOrder(array('addRefundedAmount'));
$order->expects($this->once())
->method('addRefundedAmount')
->with($this->equalTo($amount))
->will($this->returnValue(null));
$action = $this->getAction($payPalResponse, $order);
$action->process();
}
/**
* Testing new payment creation with correct data after PayPal request is processed
*/
public function testProcess_NewPaymentCreated_WithCorrectData()
{
$transactionId = 'transactionId';
$correlationId = 'correlationId';
$status = 'Completed';
$amount = 59.67;
$currency = 'EUR';
$date = 'date';
$payPalResponseMethods = array(
'getTransactionId' => $transactionId,
'getCorrelationId' => $correlationId,
'getPaymentStatus' => $status,
'getRefundAmount' => $amount,
'getCurrency' => $currency,
);
$payPalResponse = $this->_createStub(\OxidEsales\PayPalModule\Model\Response\ResponseDoRefund::class, $payPalResponseMethods);
$payment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$payment->setDate($date);
$payment->setTransactionId($transactionId);
$payment->setCorrelationId($correlationId);
$payment->setAction('refund');
$payment->setStatus($status);
$payment->setAmount($amount);
$payment->setCurrency($currency);
$paymentList = $this->getPaymentList(array('addPayment'));
$paymentList->expects($this->once())
->method('addPayment')
->with($payment)
->will($this->returnValue($this->getPayment()));
$order = $this->getOrder(array('getPaymentList'));
$order->expects($this->once())
->method('getPaymentList')
->will($this->returnValue($paymentList));
$action = $this->getAction($payPalResponse, $order);
$action->process();
}
/**
* Testing saving of order after updating it
*/
public function testProcess_ProcessingOfServiceResponse_OrderSaved()
{
$payPalResponse = $this->getPayPalResponse();
$order = $this->getOrder(array('save'));
$order->expects($this->atLeastOnce())
->method('save')
->will($this->returnValue(null));
$action = $this->getAction($payPalResponse, $order);
$action->process();
}
/**
* Testing addition of comment after PayPal request processing
*/
public function testProcess_ProcessingOfServiceResponse_CommentAdded()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\UtilsDate::class);
$mockBuilder->setMethods(['getTime']);
$utilsDate = $mockBuilder->getMock();
$utilsDate->expects($this->any())->method('getTime')->will($this->returnValue(1410431540));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\UtilsDate::class, $utilsDate);
$comment = 'testComment';
$comment = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$comment->setComment($comment);
$payPalResponse = $this->getPayPalResponse();
$payment = $this->getPayment();
$payment->expects($this->once())
->method('addComment')
->with($this->equalTo($comment));
$paymentList = $this->getPaymentList(array('addPayment'));
$paymentList->expects($this->any())
->method('addPayment')
->will($this->returnValue($payment));
$order = $this->getOrder(array('getPaymentList'));
$order->expects($this->any())
->method('getPaymentList')
->will($this->returnValue($paymentList));
$data = $this->getData();
$data->expects($this->any())->method('getComment')->will($this->returnValue($comment));
$action = $this->getAction($payPalResponse, $order, $data);
$action->process();
}
/**
* Returns payment object
*
* @return \OxidEsales\PayPalModule\Model\OrderPayment
*/
protected function getPayment()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\OrderPayment::class);
$mockBuilder->setMethods(['addComment']);
return $mockBuilder->getMock();
}
/**
* Returns payment list
*
* @param array $testMethods
*
* @return \OxidEsales\PayPalModule\Model\OrderPaymentList
*/
protected function getPaymentList($testMethods = array())
{
$methods = array('addPayment' => $this->getPayment());
$paymentList = $this->_createStub(\OxidEsales\PayPalModule\Model\OrderPaymentList::class, $methods, $testMethods);
return $paymentList;
}
/**
* Returns order
*
* @param array $testMethods
*
* @return \OxidEsales\PayPalModule\Model\PayPalOrder
*/
protected function getOrder($testMethods = array())
{
$methods = array('getPaymentList' => $this->getPaymentList());
$order = $this->_createStub(\OxidEsales\PayPalModule\Model\PayPalOrder::class, $methods, $testMethods);
return $order;
}
/**
* Retruns basic PayPal response object
*
* @param array $testMethods
*
* @return \OxidEsales\PayPalModule\Model\Response\ResponseDoCapture
*/
protected function getPayPalResponse($testMethods = array())
{
$methods = array('getRefundAmount', 'getPaymentStatus', 'getTransactionId', 'getCurrency');
$mockedMethods = array_unique(array_merge($methods, $testMethods));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Response\ResponseDoRefund::class);
$mockBuilder->setMethods($mockedMethods);
return $mockBuilder->getMock();
}
/**
* Returns capture action data object
*
* @param $methods
*
* @return \OxidEsales\PayPalModule\Model\Action\Data\OrderCaptureActionData
*/
protected function getData($methods = array())
{
$data = $this->_createStub(\OxidEsales\PayPalModule\Model\Action\Data\OrderRefundActionData::class, $methods);
return $data;
}
/**
* Returns capture action object
*
* @param $payPalResponse
* @param $order
* @param $data
*
* @return \OxidEsales\PayPalModule\Model\Action\OrderCaptureAction
*/
protected function getAction($payPalResponse, $order, $data = null)
{
$data = $data ? $data : $this->getData();
$data->expects($this->any())->method('getPaymentBeingRefunded')->will($this->returnValue(new \OxidEsales\PayPalModule\Model\OrderPayment()));
$handler = $this->_createStub('ActionHandler', array('getPayPalResponse' => $payPalResponse, 'getData' => $data));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Action\OrderRefundAction::class);
$mockBuilder->setMethods(['getDate']);
$mockBuilder->setConstructorArgs([$handler, $order]);
$action = $mockBuilder->getMock();
$action->expects($this->any())->method('getDate')->will($this->returnValue('date'));
return $action;
}
}

View File

@@ -0,0 +1,218 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Action;
/**
* Testing \OxidEsales\PayPalModule\Model\Action\OrderVoidAction class.
*/
class OrderVoidActionTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Testing addition of voided amount to order
*/
public function testProcess_VoidedAmountAddedToOrder()
{
$payPalResponse = new \OxidEsales\PayPalModule\Model\Response\ResponseDoVoid();
$amount = 5.19;
$order = $this->getOrder(array('getRemainingOrderSum', 'setVoidedAmount'));
$order->expects($this->once())
->method('getRemainingOrderSum')
->will($this->returnValue($amount));
$order->expects($this->once())
->method('setVoidedAmount')
->with($this->equalTo($amount));
$action = $this->getAction($payPalResponse, $order);
$action->process();
}
/**
* Testing new payment creation with correct data after PayPal request is processed
*/
public function testProcess_NewPaymentCreated_WithCorrectData()
{
$authentificationId = 'authentificationId';
$correlationId = 'correlationId';
$amount = 2.99;
$date = 'date';
$payPalResponseMethods = array(
'getAuthorizationId' => $authentificationId,
'getCorrelationId' => $correlationId
);
$payPalResponse = $this->_createStub(\OxidEsales\PayPalModule\Model\Response\ResponseDoVoid::class, $payPalResponseMethods);
$payment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$payment->setDate($date);
$payment->setTransactionId($authentificationId);
$payment->setCorrelationId($correlationId);
$payment->setAction('void');
$payment->setStatus('Voided');
$payment->setAmount($amount);
$paymentList = $this->getPaymentList(array('addPayment'));
$paymentList->expects($this->once())->method('addPayment')
->with($payment)
->will($this->returnValue($this->getPayment()));
$order = $this->getOrder(array('getPaymentList', 'getRemainingOrderSum'));
$order->expects($this->once())->method('getRemainingOrderSum')->will($this->returnValue($amount));
$order->expects($this->once())->method('getPaymentList')->will($this->returnValue($paymentList));
$action = $this->getAction($payPalResponse, $order);
$action->process();
}
/**
* Testing saving of order after updating it
*/
public function testProcess_CommentAdded()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\UtilsDate::class);
$mockBuilder->setMethods(['getTime']);
$utilsDate = $mockBuilder->getMock();
$utilsDate->expects($this->any())->method('getTime')->will($this->returnValue(time()));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\UtilsDate::class, $utilsDate);
$comment = 'testComment';
$comment = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$comment->setComment($comment);
$payPalResponse = $this->getPayPalResponse();
$payment = $this->getPayment();
$payment->expects($this->once())
->method('addComment')
->with($this->equalTo($comment));
$paymentList = $this->getPaymentList(array('addPayment'));
$paymentList->expects($this->any())->method('addPayment')->will($this->returnValue($payment));
$order = $this->getOrder(array('getPaymentList', 'getRemainingOrderSum'));
$order->expects($this->once())->method('getPaymentList')->will($this->returnValue($paymentList));
$data = $this->getData();
$data->expects($this->any())->method('getComment')->will($this->returnValue($comment));
$action = $this->getAction($payPalResponse, $order, $data);
$action->process();
}
/**
* Returns payment object
*
* @return \OxidEsales\PayPalModule\Model\OrderPayment
*/
protected function getPayment()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\OrderPayment::class);
$mockBuilder->setMethods(['addComment']);
return $mockBuilder->getMock();
}
/**
* Returns payment list
*
* @param array $testMethods
*
* @return \OxidEsales\PayPalModule\Model\OrderPaymentList
*/
protected function getPaymentList($testMethods = array())
{
$methods = array('addPayment' => $this->getPayment());
$paymentList = $this->_createStub(\OxidEsales\PayPalModule\Model\OrderPaymentList::class, $methods, $testMethods);
return $paymentList;
}
/**
* Returns order
*
* @param array $testMethods
*
* @return \OxidEsales\PayPalModule\Model\PayPalOrder
*/
protected function getOrder($testMethods = array())
{
$methods = array('getPaymentList' => $this->getPaymentList());
$order = $this->_createStub(\OxidEsales\PayPalModule\Model\PayPalOrder::class, $methods, $testMethods);
return $order;
}
/**
* Retruns basic PayPal response object
*
* @param array $testMethods
*
* @return \OxidEsales\PayPalModule\Model\Response\ResponseDoCapture
*/
protected function getPayPalResponse($testMethods = array())
{
$methods = array('getRefundAmount', 'getPaymentStatus', 'getTransactionId', 'getCurrency');
$mockedMethods = array_unique(array_merge($methods, $testMethods));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Response\ResponseDoVoid::class);
$mockBuilder->setMethods($mockedMethods);
return $mockBuilder->getMock();
}
/**
* Returns capture action data object
*
* @param $methods
*
* @return \OxidEsales\PayPalModule\Model\Action\Data\OrderCaptureActionData
*/
protected function getData($methods = array())
{
$data = $this->_createStub(\OxidEsales\PayPalModule\Model\Action\Data\OrderVoidActionData::class, $methods);
return $data;
}
/**
* Returns capture action object
*
* @param $payPalResponse
* @param $order
* @param $data
*
* @return \OxidEsales\PayPalModule\Model\Action\OrderCaptureAction
*/
protected function getAction($payPalResponse, $order, $data = null)
{
$data = $data ? $data : $this->getData();
$handler = $this->_createStub('ActionHandler', array('getPayPalResponse' => $payPalResponse, 'getData' => $data));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Action\OrderVoidAction::class);
$mockBuilder->setMethods(['getDate']);
$mockBuilder->setConstructorArgs([$handler, $order]);
$action = $mockBuilder->getMock();
$action->expects($this->any())->method('getDate')->will($this->returnValue('date'));
return $action;
}
}

View File

@@ -0,0 +1,295 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing oxAccessRightException class.
*/
class AddressTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Tear down the fixture.
*
*/
protected function tearDown(): void
{
parent::tearDown();
$this->getSession()->setVariable('deladrid', null);
$delete = 'TRUNCATE TABLE `oxaddress`';
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($delete);
}
/**
* Set up
*/
protected function setUp(): void
{
parent::setUp();
// fix for state ID compatability between editions
$sqlState = "REPLACE INTO `oxstates` (`OXID`, `OXCOUNTRYID`, `OXTITLE`, `OXISOALPHA2`, `OXTITLE_1`, `OXTITLE_2`, `OXTITLE_3`, `OXTIMESTAMP`) " .
"VALUES ('333', '8f241f11096877ac0.98748826', 'USA last state', 'SS', 'USA last state', '', '', CURRENT_TIMESTAMP);";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($sqlState);
}
/**
* Prepare PayPal response data array
*
* @return array
*/
protected function getPayPalData()
{
$payPalData = array();
$payPalData['PAYMENTREQUEST_0_SHIPTONAME'] = 'testName testSurname';
$payPalData['PAYMENTREQUEST_0_SHIPTOSTREET'] = 'testStreetName str. 12';
$payPalData['PAYMENTREQUEST_0_SHIPTOSTREET2'] = 'testStreeName2 str. 123';
$payPalData['PAYMENTREQUEST_0_SHIPTOCITY'] = 'testCity';
$payPalData['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE'] = 'US';
$payPalData['PAYMENTREQUEST_0_SHIPTOSTATE'] = 'SS';
$payPalData['PAYMENTREQUEST_0_SHIPTOZIP'] = 'testZip';
$payPalData['PAYMENTREQUEST_0_SHIPTOPHONENUM'] = 'testPhoneNum';
return $payPalData;
}
/**
* Test case for oePayPalAddress::createPayPalAddress()
* Creating new address
*/
public function testCreatePayPalAddress()
{
$payPalData = $this->getPayPalData();
$expressCheckoutResponse = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$expressCheckoutResponse->setData($payPalData);
$payPalOxAddress = oxNew(\OxidEsales\Eshop\Application\Model\Address::class);
$payPalOxAddress->createPayPalAddress($expressCheckoutResponse, 'testUserId');
$addressId = $this->getSession()->getVariable('deladrid');
$address = oxNew(\OxidEsales\Eshop\Application\Model\Address::class);
$address->load($addressId);
$this->assertEquals('testUserId', $address->oxaddress__oxuserid->value);
$this->assertEquals('testName', $address->oxaddress__oxfname->value);
$this->assertEquals('testSurname', $address->oxaddress__oxlname->value);
$this->assertEquals('testStreetName str.', $address->oxaddress__oxstreet->value);
$this->assertEquals('12', $address->oxaddress__oxstreetnr->value);
$this->assertEquals('testStreeName2 str. 123', $address->oxaddress__oxaddinfo->value);
$this->assertEquals('testCity', $address->oxaddress__oxcity->value);
$this->assertEquals('8f241f11096877ac0.98748826', $address->oxaddress__oxcountryid->value);
$this->assertEquals('333', $address->oxaddress__oxstateid->value);
$this->assertEquals('testZip', $address->oxaddress__oxzip->value);
$this->assertEquals('testPhoneNum', $address->oxaddress__oxfon->value);
$this->assertEquals($this->getSession()->getVariable('deladrid'), $addressId);
// street no in first position
$payPalData['PAYMENTREQUEST_0_SHIPTOSTREET'] = '12 testStreetNameNext str.';
$expressCheckoutResponse->setData($payPalData);
$payPalAddress = oxNew(\OxidEsales\Eshop\Application\Model\Address::class);
$payPalAddress->createPayPalAddress($expressCheckoutResponse, 'testUserId');
$this->assertEquals('testStreetNameNext str.', $payPalAddress->oxaddress__oxstreet->value);
$this->assertEquals('12', $payPalAddress->oxaddress__oxstreetnr->value);
}
/**
* Test case for Address::createPayPalAddress()
* Testing if address is save without checking if required fields are not empty.
* This is not needed as we assume that PayPal data is correct.
*/
public function testCreatePayPalAddressFail()
{
$payPalData = $this->getPayPalData();
$payPalData['PAYMENTREQUEST_0_SHIPTOSTREET'] = '';
$expressCheckoutResponse = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$expressCheckoutResponse->setData($payPalData);
$payPalAddress = oxNew(\OxidEsales\Eshop\Application\Model\Address::class);
// checking if required field exists
$reqFields = \OxidEsales\Eshop\Core\Registry::getConfig()->getConfigParam("aMustFillFields");
$this->assertTrue(in_array("oxaddress__oxstreet", $reqFields));
$payPalAddress->createPayPalAddress($expressCheckoutResponse, 'testUserId');
$address = oxNew(\OxidEsales\Eshop\Application\Model\Address::class);
$address->load($payPalAddress->getId());
$this->assertEquals('testName', $address->oxaddress__oxfname->value);
$this->assertEquals("", $address->oxaddress__oxstreet->value);
}
/**
* Test case for oePayPalAddress::createPayPalAddress()
* Not creating if exist
*/
public function testCreatePayPalAddressIfExist()
{
//creating existing address
$address = oxNew(\OxidEsales\Eshop\Application\Model\Address::class);
$address->oxaddress__oxuserid = new \OxidEsales\Eshop\Core\Field('testUserId');
$address->oxaddress__oxfname = new \OxidEsales\Eshop\Core\Field('testName');
$address->oxaddress__oxlname = new \OxidEsales\Eshop\Core\Field('testSurname');
$address->oxaddress__oxstreet = new \OxidEsales\Eshop\Core\Field('testStreetName str.');
$address->oxaddress__oxstreetnr = new \OxidEsales\Eshop\Core\Field('12');
$address->oxaddress__oxcity = new \OxidEsales\Eshop\Core\Field('testCity');
$address->oxaddress__oxstateid = new \OxidEsales\Eshop\Core\Field('333');
$address->oxaddress__oxzip = new \OxidEsales\Eshop\Core\Field('testZip');
$address->oxaddress__oxfon = new \OxidEsales\Eshop\Core\Field('testPhoneNum');
$address->oxaddress__oxcountryid = new \OxidEsales\Eshop\Core\Field('8f241f11096877ac0.98748826');
$address->save();
$addressId = $address->getId();
$this->getSession()->setVariable('deladrid', null);
$sQ = "SELECT COUNT(*) FROM `oxaddress`";
$addressCount = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getOne($sQ);
// preparing data fo new address - the same
$payPalData = $this->getPayPalData();
$expressCheckoutResponse = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$expressCheckoutResponse->setData($payPalData);
$payPalOxAddress = oxNew(\OxidEsales\Eshop\Application\Model\Address::class);
$payPalOxAddress->createPayPalAddress($expressCheckoutResponse, 'testUserId');
$addressCountAfter = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getOne($sQ);
// skips the same address
$this->assertEquals($addressCount, $addressCountAfter);
// sets existing address id
$this->assertEquals($this->getSession()->getVariable('deladrid'), $addressId);
}
/**
* Data provider for testCreatePayPalAddress_splittingAddress()
*
* @return array
*/
public function createPayPalAddress_splittingAddress_dataProvider()
{
$address["addr"][] = "4 Street Name ";
$address["addr"][] = " 4a Street Name";
$address["addr"][] = "4a-5 Street Name";
$address["addr"][] = "4a-5 11 Street Name";
$address["addr"][] = "Street Name 4";
$address["addr"][] = "Street Name 4a";
$address["addr"][] = "Street Name 4a-5 ";
$address["addr"][] = "Street Name 11 4a-5";
$address["addr"][] = " Street Name ";
$address["addr"][] = "bertoldstr.48";
$address["addr"][] = "Street Name 4 a";
$address["ress"][] = array("Street Name", "4");
$address["ress"][] = array("Street Name", "4a");
$address["ress"][] = array("Street Name", "4a-5");
$address["ress"][] = array("11 Street Name", "4a-5");
$address["ress"][] = array("Street Name", "4");
$address["ress"][] = array("Street Name", "4a");
$address["ress"][] = array("Street Name", "4a-5");
$address["ress"][] = array("Street Name 11", "4a-5");
$address["ress"][] = array("Street Name", "");
$address["ress"][] = array("bertoldstr.48", "");
$address["ress"][] = array("Street Name", "4 a");
foreach ($address["addr"] as $key => $value) {
$ret[] = array($value, $address["ress"][$key]);
}
return $ret;
}
/**
* Test case for oePayPalAddress::createPayPalAddress()
* Creating new address
*
* @dataProvider createPayPalAddress_splittingAddress_dataProvider
*/
public function testCreatePayPalAddress_splittingAddress($address, $result)
{
$payPalData = $this->getPayPalData();
$payPalData['PAYMENTREQUEST_0_SHIPTOSTREET'] = $address;
$expressCheckoutResponse = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$expressCheckoutResponse->setData($payPalData);
$payPalOxAddress = oxNew(\OxidEsales\Eshop\Application\Model\Address::class);
$payPalOxAddress->createPayPalAddress($expressCheckoutResponse, 'testUserId');
$addressId = $payPalOxAddress->getId();
$address = oxNew(\OxidEsales\Eshop\Application\Model\Address::class);
$address->load($addressId);
$this->assertEquals($result[0], $address->oxaddress__oxstreet->value);
$this->assertEquals($result[1], $address->oxaddress__oxstreetnr->value);
}
/**
* Data provider for testCreatePayPalAddress_splittingUserName()
*
* @return array
*/
public function createPayPalAddress_splittingUserName_dataProvider()
{
$address["name"][] = "Firstname Lastname";
$address["name"][] = "Firstname Lastname Lastname2";
$address["name"][] = "Firstname Lastname Lastname2 Lastname3";
$address["name"][] = "Firstname";
$address["res"][] = array("Firstname", "Lastname");
$address["res"][] = array("Firstname", "Lastname Lastname2");
$address["res"][] = array("Firstname", "Lastname Lastname2 Lastname3");
$address["res"][] = array("Firstname", "");
foreach ($address["name"] as $key => $value) {
$ret[] = array($value, $address["res"][$key]);
}
return $ret;
}
/**
* Test case for oePayPalAddress::createPayPalAddress()
* Creating new address
*
* @dataProvider createPayPalAddress_splittingUserName_dataProvider
*/
public function testCreatePayPalAddress_splittingUserName($name, $result)
{
$payPalData = $this->getPayPalData();
$payPalData['PAYMENTREQUEST_0_SHIPTONAME'] = $name;
$expressCheckoutResponse = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$expressCheckoutResponse->setData($payPalData);
$payPalOxAddress = oxNew(\OxidEsales\Eshop\Application\Model\Address::class);
$payPalOxAddress->createPayPalAddress($expressCheckoutResponse, 'testUserId');
$addressId = $payPalOxAddress->getId();
$address = oxNew(\OxidEsales\Eshop\Application\Model\Address::class);
$address->load($addressId);
$this->assertEquals($result[0], $address->oxaddress__oxfname->value);
$this->assertEquals($result[1], $address->oxaddress__oxlname->value);
}
}

View File

@@ -0,0 +1,64 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing oxAccessRightException class.
*/
class ArticleTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* @dataProvider provider
*/
public function dataProvider()
{
return array(
array(false, false, false),
array(true, false, false),
array(false, true, false),
array(true, true, true),
);
}
/**
* @dataProvider dataProvider
*/
public function testIsVirtualPayPalArticle($isMaterial, $isDownloadable, $result)
{
$article = oxNew(\OxidEsales\PayPalModule\Model\Article::class);
$article->oxarticles__oxnonmaterial = new \OxidEsales\Eshop\Core\Field($isMaterial);
$article->oxarticles__oxisdownloadable = new \OxidEsales\Eshop\Core\Field($isDownloadable);
$this->assertEquals($result, $article->isVirtualPayPalArticle());
}
/**
*/
public function testGetStockAmount()
{
$article = oxNew(\OxidEsales\PayPalModule\Model\Article::class);
$article->oxarticles__oxstock = new \OxidEsales\Eshop\Core\Field(321);
$this->assertEquals(321, $article->getStockAmount());
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
class ArticleToExpressCheckoutCurrentItemTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Tests setter and getter.
*/
public function testSetGetArticleId()
{
$articleId = 'this is product id';
$articleToExpressCheckoutValidator = new \OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutCurrentItem();
$articleToExpressCheckoutValidator->setArticleId($articleId);
$this->assertEquals($articleId, $articleToExpressCheckoutValidator->getArticleId());
}
/**
* Tests setter and getter.
*/
public function testSetGeSelectList()
{
$selectList = array('testable' => 'selection list');
$articleToExpressCheckoutValidator = new \OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutCurrentItem();
$articleToExpressCheckoutValidator->setSelectList($selectList);
$this->assertEquals($selectList, $articleToExpressCheckoutValidator->getSelectList());
}
/**
* Tests setter and getter.
*/
public function testSetGetPersistParam()
{
$persistentParam = array('testable' => 'persistent param');
$articleToExpressCheckoutValidator = new \OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutCurrentItem();
$articleToExpressCheckoutValidator->setPersistParam($persistentParam);
$this->assertEquals($persistentParam, $articleToExpressCheckoutValidator->getPersistParam());
}
/**
* Tests setter and getter.
*/
public function testSetGetArticleAmount()
{
$amount = 5;
$articleToExpressCheckoutValidator = new \OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutCurrentItem();
$articleToExpressCheckoutValidator->setArticleAmount($amount);
$this->assertEquals($amount, $articleToExpressCheckoutValidator->getArticleAmount());
}
}

View File

@@ -0,0 +1,191 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
use OxidEsales\Eshop\Application\Model\Basket;
class ArticleToExpressCheckoutValidatorTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function providerSetGetItemToValidate()
{
$item = new \OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutCurrentItem();
return array(
array($item),
array(null)
);
}
/**
* Tests setBasket and getBasket, sets basket object and checks if it get correct
*
* @param $item
*
* @dataProvider providerSetGetItemToValidate
*/
public function testSetGetItemToValidate($item)
{
$articleToExpressCheckoutValidator = new \OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutValidator();
$articleToExpressCheckoutValidator->setItemToValidate($item);
$this->assertEquals($item, $articleToExpressCheckoutValidator->getItemToValidate());
}
public function providerSetGetBasket()
{
$oxBasket = oxNew(Basket::class);
return array(
array($oxBasket),
array(null)
);
}
/**
* Tests setBasket and getBasket, sets basket object and checks if it get correct
*
* @param $basket
*
* @dataProvider providerSetGetBasket
*/
public function testSetGetBasket($basket)
{
$articleToExpressCheckoutValidator = new \OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutValidator();
$articleToExpressCheckoutValidator->setBasket($basket);
$this->assertEquals($basket, $articleToExpressCheckoutValidator->getBasket());
}
public function providerIsArticleValid_True()
{
return array(
array(null, null, null),
array('ProductId', array('testable' => 'list'), null),
array('ProductId', null, null),
array(null, null, 'persistent param')
);
}
/**
* Checks if item is same in given basket
*
* @param $basketProductId
* @param $basketSelectionList
* @param $basketPersistentParam
*
* @dataProvider providerIsArticleValid_True
*/
public function testIsArticleValid_True($basketProductId, $basketSelectionList, $basketPersistentParam)
{
$productId = 'ProductId';
$selectionList = array('testable' => 'list');
$persistentParam = array('testable' => 'persistent param');
$amount = 1;
$basket = $this->createBasket($basketProductId, $basketSelectionList, $basketPersistentParam);
$articleToExpressCheckoutCurrentItem = new \OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutCurrentItem();
$articleToExpressCheckoutValidator = new \OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutValidator();
$articleToExpressCheckoutCurrentItem->setPersistParam($persistentParam);
$articleToExpressCheckoutCurrentItem->setSelectList($selectionList);
$articleToExpressCheckoutCurrentItem->setArticleId($productId);
$articleToExpressCheckoutCurrentItem->setArticleAmount($amount);
$articleToExpressCheckoutValidator->setBasket($basket);
$articleToExpressCheckoutValidator->setItemToValidate($articleToExpressCheckoutCurrentItem);
$this->assertTrue($articleToExpressCheckoutValidator->isArticleValid());
}
public function providerIsArticleValid_False()
{
return array(
// Same article
array('ProductId', array('testable' => 'list'), array('testable' => 'persistent param'), 1),
// Article amount is 0
array('ProductId', null, null, 0),
array('ProductId', null, null, null)
);
}
/**
* Checks if item is same in given basket, if so, item is not valid
*
* @dataProvider providerIsArticleValid_False
*/
public function testIsArticleValid_False($productId, $selectionList, $persistentParam, $amount)
{
$basketProductId = 'ProductId';
$basketSelectionList = array('testable' => 'list');
$basketPersistentParam = array('testable' => 'persistent param');
$basket = $this->createBasket($basketProductId, $basketSelectionList, $basketPersistentParam);
$articleToExpressCheckoutCurrentItem = new \OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutCurrentItem();
$articleToExpressCheckoutValidator = new \OxidEsales\PayPalModule\Model\ArticleToExpressCheckoutValidator();
$articleToExpressCheckoutCurrentItem->setPersistParam($persistentParam);
$articleToExpressCheckoutCurrentItem->setSelectList($selectionList);
$articleToExpressCheckoutCurrentItem->setArticleId($productId);
$articleToExpressCheckoutCurrentItem->setArticleAmount($amount);
$articleToExpressCheckoutValidator->setBasket($basket);
$articleToExpressCheckoutValidator->setItemToValidate($articleToExpressCheckoutCurrentItem);
$this->assertFalse($articleToExpressCheckoutValidator->isArticleValid());
}
/**
* Function creates mocked basket
*
* @param $basketProductId
* @param $basketSelectionList
* @param $basketPersistentParam
*
* @return PHPUnit_Framework_MockObject_MockObject
*/
protected function createBasket($basketProductId, $basketSelectionList, $basketPersistentParam)
{
$basketItemsList = array();
//if $basketProductId is null we say that $basketItemsList is empty array
if (!is_null($basketProductId)) {
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\BasketItem::class);
$mockBuilder->setMethods(['getProductId', 'getPersParams', 'getSelList']);
$basketItem = $mockBuilder->getMock();
$basketItem->expects($this->any())->method('getProductId')->will($this->returnValue($basketProductId));
$basketItem->expects($this->any())->method('getSelList')->will($this->returnValue($basketSelectionList));
$basketItem->expects($this->any())->method('getPersParams')->will($this->returnValue($basketPersistentParam));
$basketItemsList = array(
$basketProductId => $basketItem
);
}
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Basket::class);
$mockBuilder->setMethods(['getContents']);
$basket = $mockBuilder->getMock();
$basket->expects($this->any())->method('getContents')->will($this->returnValue($basketItemsList));
return $basket;
}
}

View File

@@ -0,0 +1,518 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
use OxidEsales\Eshop\Application\Model\Basket;
/**
* Testing oxAccessRightException class.
*/
class BasketTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Test data provider
*
* @return array
*/
public function isVirtualPayPalBasketDataProvider()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Article::class);
$mockBuilder->setMethods(['isVirtualPayPalArticle']);
$product1 = $mockBuilder->getMock();
$product1->expects($this->any())->method('isVirtualPayPalArticle')->will($this->returnValue(true));
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Article::class);
$mockBuilder->setMethods(['isVirtualPayPalArticle']);
$product2 = $mockBuilder->getMock();
$product2->expects($this->any())->method('isVirtualPayPalArticle')->will($this->returnValue(false));
return array(
array($product1, $product2, false),
array($product1, $product1, true),
);
}
/**
* Test case for oePayPalUser::isVirtualPayPalArticle()
*
* @dataProvider isVirtualPayPalBasketDataProvider
*/
public function testIsVirtualPayPalBasket($product1, $product2, $result)
{
$products = array($product1, $product2);
$mockBuilder = $this->getMockBuilder(Basket::class);
$mockBuilder->setMethods(['getBasketArticles']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method('getBasketArticles')->will($this->returnValue($products));
$this->assertEquals($result, $basket->isVirtualPayPalBasket());
}
/**
* Test data provider
*
* @return array
*/
public function getPayPalAdditionalCostsDataProvider()
{
return array(
array(true, 17.6, 15.14, 15.14),
array(false, 17.6, 15.14, 17.6),
array(true, 0, 0, 0),
array(false, 0, 0, 0),
);
}
/**
* Test case for oePayPalUser::getPayPalWrappingCosts()
*
* @dataProvider getPayPalAdditionalCostsDataProvider
*/
public function testGetPayPalWrappingCosts($calculationModeNetto, $wrappingPriceBrutto, $wrappingPriceNetto, $wrappingPriceExpect)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Price::class);
$mockBuilder->setMethods(['getNettoPrice', 'getBruttoPrice']);
$price = $mockBuilder->getMock();
$price->expects($this->any())->method('getBruttoPrice')->will($this->returnValue($wrappingPriceBrutto));
$price->expects($this->any())->method('getNettoPrice')->will($this->returnValue($wrappingPriceNetto));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Basket::class);
$mockBuilder->setMethods(['getCosts', 'isCalculationModeNetto']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method('getCosts')->with($this->equalTo('oxwrapping'))->will($this->returnValue($price));
$basket->expects($this->once())->method('isCalculationModeNetto')->will($this->returnValue($calculationModeNetto));
$this->assertEquals($wrappingPriceExpect, $basket->getPayPalWrappingCosts());
}
/**
* Test case for oePayPalUser::getPayPalGiftCardCosts()
*
* @dataProvider getPayPalAdditionalCostsDataProvider
*/
public function testGetPayPalGiftCardCosts($calculationModeNetto, $giftCardPriceBrutto, $giftCardPriceNetto, $giftCardPrice)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Price::class);
$mockBuilder->setMethods(['getNettoPrice', 'getBruttoPrice']);
$price = $mockBuilder->getMock();
$price->expects($this->any())->method('getBruttoPrice')->will($this->returnValue($giftCardPriceBrutto));
$price->expects($this->any())->method('getNettoPrice')->will($this->returnValue($giftCardPriceNetto));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Basket::class);
$mockBuilder->setMethods(['getCosts', 'isCalculationModeNetto']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method('getCosts')->with($this->equalTo('oxgiftcard'))->will($this->returnValue($price));
$basket->expects($this->once())->method('isCalculationModeNetto')->will($this->returnValue($calculationModeNetto));
$this->assertEquals($giftCardPrice, $basket->getPayPalGiftCardCosts());
}
/**
* Test case for oePayPalUser::getPayPalPaymentCosts()
*
* @dataProvider getPayPalAdditionalCostsDataProvider
*/
public function testGetPayPalPaymentCosts($calculationModeNetto, $paymentCostsPriceBrutto, $paymentCostsPriceNetto, $paymentPrice)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Price::class);
$mockBuilder->setMethods(['getNettoPrice', 'getBruttoPrice']);
$price = $mockBuilder->getMock();
$price->expects($this->any())->method('getBruttoPrice')->will($this->returnValue($paymentCostsPriceBrutto));
$price->expects($this->any())->method('getNettoPrice')->will($this->returnValue($paymentCostsPriceNetto));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Basket::class);
$mockBuilder->setMethods(['getCosts', 'isCalculationModeNetto']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method('getCosts')->with($this->equalTo('oxpayment'))->will($this->returnValue($price));
$basket->expects($this->once())->method('isCalculationModeNetto')->will($this->returnValue($calculationModeNetto));
$this->assertEquals($paymentPrice, $basket->getPayPalPaymentCosts());
}
/**
* Test data provider
*
* @return array
*/
public function getDiscountSumPayPalBasketDataProvider()
{
$basketDiscount1 = oxNew(\OxidEsales\Eshop\Core\Price::class);
$basketDiscount1->setPrice(2);
$basketDiscount2 = oxNew(\OxidEsales\Eshop\Core\Price::class);
$basketDiscount2->setPrice(4);
// vouchers
$voucher = oxNew(\OxidEsales\Eshop\Application\Model\Voucher::class);
$VoucherDiscount1 = $voucher->getSimpleVoucher();
$VoucherDiscount1->dVoucherdiscount = 6;
$VoucherDiscount2 = $voucher->getSimpleVoucher();
$VoucherDiscount2->dVoucherdiscount = 8;
$paymentCost1 = 7;
$paymentCost2 = -7;
return array(
array(0, array(), 0, 0),
array(0, array(), $paymentCost1, 0),
array($basketDiscount1, array($VoucherDiscount1, $VoucherDiscount2), $paymentCost1, 16),
array($basketDiscount2, array($VoucherDiscount1, $VoucherDiscount2), $paymentCost2, 25),
);
}
/**
* Test case for oePayPalUser::getDiscountSumPayPalBasket()
*
* @dataProvider getDiscountSumPayPalBasketDataProvider
*/
public function testGetDiscountSumPayPalBasket($discount, $vouchers, $paymentCost, $result)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Basket::class);
$mockBuilder->setMethods(['getTotalDiscount', 'getPaymentCosts', 'getVouchers']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method('getTotalDiscount')->will($this->returnValue($discount));
$basket->expects($this->once())->method('getVouchers')->will($this->returnValue($vouchers));
$basket->expects($this->once())->method('getPaymentCosts')->will($this->returnValue($paymentCost));
$this->assertEquals($result, $basket->getDiscountSumPayPalBasket());
}
/**
* Test data provider
*
* @return array
*/
public function getSumOfCostOfAllItemsPayPalBasketDataProvider()
{
// discounts
$productsPrice = oxNew(\OxidEsales\Eshop\Core\PriceList::class);
$productsPrice->addToPriceList(oxNew(\OxidEsales\Eshop\Core\Price::class, 15));
$paymentCost = 3;
$wrappingCost = 5;
return array(
array($productsPrice, 0, 0, 15),
array($productsPrice, $paymentCost, $wrappingCost, 23),
array($productsPrice, -1 * $paymentCost, $wrappingCost, 20),
);
}
/**
* Test case for oePayPalUser::getSumOfCostOfAllItemsPayPalBasket()
*
* @dataProvider getSumOfCostOfAllItemsPayPalBasketDataProvider
*/
public function testGetSumOfCostOfAllItemsPayPalBasket($productsPrice, $paymentCost, $wrappingCost, $result)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Basket::class);
$mockBuilder->setMethods(['getProductsPrice', 'getPayPalPaymentCosts', 'getPayPalWrappingCosts']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method('getProductsPrice')->will($this->returnValue($productsPrice));
$basket->expects($this->once())->method('getPayPalPaymentCosts')->will($this->returnValue($paymentCost));
$basket->expects($this->once())->method('getPayPalWrappingCosts')->will($this->returnValue($wrappingCost));
$this->assertEquals($result, $basket->getSumOfCostOfAllItemsPayPalBasket());
}
/**
* Test data provider
*
* @return array
*/
public function getPayPalBasketVatValueDataProvider()
{
return array(
array(array(1 => 13.32, 12 => 1.69), 1, 2, 3, 21.01),
array(array(0 => 0), 0, 0, 0, 0),
array(array(5 => 3.45), 1, 2, 3, 9.45),
array(array(5 => 3.45), 1, 0, 0, 4.45),
array(array(5 => 3.45), 0, 2, 0, 5.45),
array(array(5 => 3.45), 0, 0, 3, 6.45),
array(array(), 0, 0, 0, 0),
);
}
/**
* Test case for \OxidEsales\PayPalModule\Model\Basket::getPayPalBasketVatValue()
*
* @dataProvider getPayPalBasketVatValueDataProvider
*/
public function testGetPayPalBasketVatValue($productsVat, $wrappingVat, $giftCardVat, $payCostVat, $basketVat)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Basket::class);
$mockBuilder->setMethods(['getProductVats', 'getPayPalWrappingVat', 'getPayPalGiftCardVat', 'getPayPalPayCostVat']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method('getProductVats')->will($this->returnValue($productsVat));
$basket->expects($this->once())->method('getPayPalWrappingVat')->will($this->returnValue($wrappingVat));
$basket->expects($this->once())->method('getPayPalGiftCardVat')->will($this->returnValue($giftCardVat));
$basket->expects($this->once())->method('getPayPalPayCostVat')->will($this->returnValue($payCostVat));
// Rounding because of PHPunit bug: Failed asserting that <double:21.01> matches expected <double:21.01>.
$this->assertEquals($basketVat, round($basket->getPayPalBasketVatValue(), 2), 'Basket VAT do not match SUM of products VAT.');
}
/**
* Test data provider
*
* @return array
*/
public function getPayPalProductVatDataProvider()
{
return array(
array(array(1 => 13.32, 12 => 1.69), 1426 => 15.01),
array(array(0, 0), 0),
array(array(5 => 3.45), 3.45),
array(array(), 0),
);
}
/**
* Test case for \OxidEsales\PayPalModule\Model\Basket::testGetPayPalProductVat()
*
* @dataProvider getPayPalProductVatDataProvider
*/
public function testGetPayPalProductVat($productsVat, $basketVat)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Basket::class);
$mockBuilder->setMethods(['getProductVats']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method('getProductVats')->will($this->returnValue($productsVat));
$this->assertEquals($basketVat, $basket->getPayPalBasketVatValue(), 'Products VAT SUM is different than expected.');
}
/**
* Test data provider
*
* @return array
*/
public function getPayPalAdditionalCostsVatDataProvider()
{
return array(
array(10, 10),
array(0, 0),
);
}
/**
* Test case for \OxidEsales\PayPalModule\Model\Basket::GetPayPalWrappingVat()
*
* @dataProvider getPayPalAdditionalCostsVatDataProvider
*/
public function testGetPayPalWrappingVat($costVat, $costVatExpected)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Price::class);
$mockBuilder->setMethods(['getVatValue']);
$price = $mockBuilder->getMock();
$price->expects($this->any())->method('getVatValue')->will($this->returnValue($costVat));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Basket::class);
$mockBuilder->setMethods(['getCosts']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method('getCosts')->with($this->equalTo('oxwrapping'))->will($this->returnValue($price));
$this->assertEquals($costVatExpected, $basket->getPayPalWrappingVat(), 'Wrapping VAT SUM is different than expected.');
}
/**
* Test case for \OxidEsales\PayPalModule\Model\Basket::GetPayPalGiftCardVat()
*
* @dataProvider getPayPalAdditionalCostsVatDataProvider
*/
public function testGetPayPalGiftCardVat($costVat, $costVatExpected)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Price::class);
$mockBuilder->setMethods(['getVatValue']);
$price = $mockBuilder->getMock();
$price->expects($this->any())->method('getVatValue')->will($this->returnValue($costVat));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Basket::class);
$mockBuilder->setMethods(['getCosts']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method('getCosts')->with($this->equalTo('oxgiftcard'))->will($this->returnValue($price));
$this->assertEquals($costVatExpected, $basket->getPayPalGiftCardVat(), 'GiftCard VAT SUM is different than expected.');
}
/**
* Test case for \OxidEsales\PayPalModule\Model\Basket::GetPayPalPayCostVat()
*
* @dataProvider getPayPalAdditionalCostsVatDataProvider
*/
public function testGetPayPalPayCostVat($costVat, $costVatExpected)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Price::class);
$mockBuilder->setMethods(['getVatValue']);
$price = $mockBuilder->getMock();
$price->expects($this->any())->method('getVatValue')->will($this->returnValue($costVat));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Basket::class);
$mockBuilder->setMethods(['getCosts']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method('getCosts')->with($this->equalTo('oxpayment'))->will($this->returnValue($price));
$this->assertEquals($costVatExpected, $basket->getPayPalPayCostVat(), 'PayCost VAT SUM is different than expected.');
}
/**
* Test case for ViewConfig::sendOrderInfoToPayPal()
*/
public function testIsFractionQuantityItemsPresentWhenFractionQuantityArticlePresent()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Article::class);
$mockBuilder->setMethods(['getAmount']);
$article = $mockBuilder->getMock();
$article->expects($this->any())->method('getAmount')->will($this->returnValue(5.6));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Basket::class);
$mockBuilder->setMethods(['getContents']);
/** @var \OxidEsales\PayPalModule\Model\Basket $basket */
$basket = $mockBuilder->getMock();
$basket->expects($this->any())->method('getContents')->will($this->returnValue(array($article)));
$this->assertTrue($basket->isFractionQuantityItemsPresent());
}
/**
* Test case for ViewConfig::sendOrderInfoToPayPal()
*/
public function testSendOrderInfoToPayPalWhenNoFractionQuantityArticlesArePresent()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Article::class);
$mockBuilder->setMethods(['getAmount']);
$article = $mockBuilder->getMock();
$article->expects($this->any())->method('getAmount')->will($this->returnValue(5));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Basket::class);
$mockBuilder->setMethods(['getContents']);
/** @var \OxidEsales\PayPalModule\Model\Basket $basket */
$basket = $mockBuilder->getMock();
$basket->expects($this->any())->method('getContents')->will($this->returnValue(array($article)));
$this->assertFalse($basket->isFractionQuantityItemsPresent());
}
/**
* Test case for ViewConfig::sendOrderInfoToPayPal()
*/
public function testSendOrderInfoToPayPalWhenBasketIsEmpty()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Basket::class);
$mockBuilder->setMethods(['getContents']);
/** @var \OxidEsales\PayPalModule\Model\Basket $basket */
$basket = $mockBuilder->getMock();
$basket->expects($this->any())->method('getContents')->will($this->returnValue(array()));
$this->assertFalse($basket->isFractionQuantityItemsPresent());
}
public function providerHasProductVariantInBasket()
{
return [
'parent' => [
[
'_variant',
'_alternate_variant'
],
'_parent',
'assertTrue'
],
'variant' => [
[
'_variant'
],
'_variant',
'assertFalse'
],
'other_variant' => [
[
'_variant'
],
'_alternate_variant',
'assertFalse'
],
'has_no_variant'=> [
[
'_variant'
],
'_has_no_variant',
'assertFalse'
]
];
}
/**
* @param array $toBasket
* @param string $productId
* @param string $assertMethod
*
* @dataProvider providerHasProductVariantInBasket()
*/
public function testHasProductVariantInBasket($toBasket, $productId, $assertMethod)
{
$this->prepareProducts();
$product = oxNew(\OxidEsales\Eshop\Application\Model\Article::class);
$product->load($productId);
$basket = oxNew(\OxidEsales\Eshop\Application\Model\Basket::class);
foreach ($toBasket as $productId) {
$basket->addToBasket($productId, 1);
}
$this->$assertMethod($basket->hasProductVariantInBasket($product));
}
private function prepareProducts()
{
$products = [
'_parent' => [
'oxid' => '_parent',
'oxstock' => 0
],
'_variant'=> [
'oxid' => '_variant',
'oxparentid' => '_parent',
'oxstock' => 10
],
'_alternate_variant'=> [
'oxid' => '_alternate_variant',
'oxparentid' => '_parent',
'oxstock' => 20
],
'_has_no_variant' => [
'oxid' => '_has_no_variant',
'oxstock' => 100
]
];
foreach ($products as $assign) {
$product = oxNew(\OxidEsales\Eshop\Application\Model\Article::class);
$product->assign($assign);
$product->save();
}
}
}

View File

@@ -0,0 +1,271 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing \OxidEsales\PayPalModule\Model\IPNPaymentBuilder class.
*/
class IPNPaymentBuilderTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
protected function setUp(): void
{
parent::setUp();
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpaymentcomments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpayments`');
}
public function testSetGetRequest()
{
$request = $this->prepareRequest();
$paymentBuilder = new \OxidEsales\PayPalModule\Model\IPNPaymentBuilder();
$paymentBuilder->setRequest($request);
$this->assertEquals($request, $paymentBuilder->getRequest(), 'Getter should return what is set in setter.');
}
public function testSetGetOrderPaymentSetter()
{
$payPalIPNPaymentSetter = new \OxidEsales\PayPalModule\Model\IPNRequestPaymentSetter();
$paymentBuilder = new \OxidEsales\PayPalModule\Model\IPNPaymentBuilder();
$paymentBuilder->setOrderPaymentSetter($payPalIPNPaymentSetter);
$this->assertEquals($payPalIPNPaymentSetter, $paymentBuilder->getOrderPaymentSetter(), 'Getter should return what is set in setter.');
}
public function testGetOrderPaymentSetter()
{
$paymentBuilder = new \OxidEsales\PayPalModule\Model\IPNPaymentBuilder();
$payPalIPNPaymentSetter = $paymentBuilder->getOrderPaymentSetter();
$this->assertTrue(
$payPalIPNPaymentSetter instanceof \OxidEsales\PayPalModule\Model\IPNRequestPaymentSetter,
'Getter should create IPNRequestPaymentSetter.'
);
}
public function testSetOrderPaymentValidator()
{
$payPalIPNPaymentValidator = new \OxidEsales\PayPalModule\Model\IPNPaymentValidator();
$paymentBuilder = new \OxidEsales\PayPalModule\Model\IPNPaymentBuilder();
$paymentBuilder->setOrderPaymentValidator($payPalIPNPaymentValidator);
$this->assertEquals($payPalIPNPaymentValidator, $paymentBuilder->getOrderPaymentValidator(), 'Getter should return what is set in Validator.');
}
public function testGetOrderPaymentValidator()
{
$paymentBuilder = new \OxidEsales\PayPalModule\Model\IPNPaymentBuilder();
$this->assertTrue(
$paymentBuilder->getOrderPaymentValidator() instanceof \OxidEsales\PayPalModule\Model\IPNPaymentValidator,
'Getter should create \OxidEsales\PayPalModule\Model\IPNRequestValidator.'
);
}
public function testSetGetPaymentCreator()
{
$payPalIPNPaymentCreator = new \OxidEsales\PayPalModule\Model\IPNPaymentCreator();
$paymentBuilder = new \OxidEsales\PayPalModule\Model\IPNPaymentBuilder();
$paymentBuilder->setOrderPaymentSetter($payPalIPNPaymentCreator);
$this->assertEquals($payPalIPNPaymentCreator, $paymentBuilder->getPaymentCreator(), 'Getter should return what is set in setter.');
}
public function testGetPaymentCreator()
{
$paymentBuilder = new \OxidEsales\PayPalModule\Model\IPNPaymentBuilder();
$payPalIPNPaymentCreator = $paymentBuilder->getPaymentCreator();
$this->assertTrue(
$payPalIPNPaymentCreator instanceof \OxidEsales\PayPalModule\Model\IPNPaymentCreator,
'Getter should create \OxidEsales\PayPalModule\Model\IPNPaymentCreator.'
);
}
public function testSetGetLang()
{
$lang = oxNew(\OxidEsales\Eshop\Core\Language::class);
$paymentBuilder = new \OxidEsales\PayPalModule\Model\IPNPaymentBuilder();
$paymentBuilder->setLang($lang);
$this->assertEquals($lang, $paymentBuilder->getLang(), 'Getter should return what is set in Validator.');
}
/**
* Data provider for function testGetPayment.
*/
public function provideGetPayment()
{
return array(
array(false, 'some validation message'),
// array( true, '' ),
);
}
/**
* Check if payment is formed from request.
* Check if payment is formed with validator results.
*
* @param bool $paymentValid if payment is valid.
* @param string $validationMessage validation message.
*
* @dataProvider provideGetPayment
*/
public function testGetPayment($paymentValid, $validationMessage)
{
$transactionIdRequestPayment = '_someId';
$transactionIdCreatedOrder = '_someOtherid';
$request = $this->prepareRequest();
$requestOrderPayment = $this->prepareOrderPayment($transactionIdRequestPayment);
$orderPayment = $this->prepareOrderPayment($transactionIdCreatedOrder);
$lang = $this->prepareLang();
// Request Payment should be called with request object.
$payPalIPNPaymentSetter = $this->prepareRequestPaymentSetter($request, $requestOrderPayment);
$payPalIPNPaymentValidator = $this->prepareIPNPaymentValidator($requestOrderPayment, $orderPayment, $lang, $paymentValid, $validationMessage);
// Mock order loading, so we do not touch database.
/** @var \OxidEsales\PayPalModule\Model\IPNPaymentBuilder $paymentBuilder */
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\IPNPaymentBuilder::class);
$mockBuilder->setMethods(['loadOrderPayment']);
$paymentBuilder = $mockBuilder->getMock();
$paymentBuilder->expects($this->atLeastOnce())->method('loadOrderPayment')->with($transactionIdRequestPayment)->will($this->returnValue($orderPayment));
$paymentBuilder->setRequest($request);
$paymentBuilder->setLang($lang);
$paymentBuilder->setOrderPaymentSetter($payPalIPNPaymentSetter);
$paymentBuilder->setOrderPaymentValidator($payPalIPNPaymentValidator);
$buildOrderPayment = $paymentBuilder->buildPayment();
// Get first comment as there should be only one.
$comments = $buildOrderPayment->getCommentList();
$comments = $comments->getArray();
$comment = $comments[0]->getComment();
// Payment should be built with validator results from setter request.
// Save on order payment as it is already loaded from database.
$this->assertEquals($paymentValid, $buildOrderPayment->getIsValid(), 'Payment should be valid or not as it is mocked in validator.');
$this->assertEquals(1, count($comments), 'There should be only one comment - failure message.');
$this->assertEquals($validationMessage, $comment, 'Validation message should be same as it is mocked in validator.');
$this->assertEquals($transactionIdCreatedOrder, $buildOrderPayment->getTransactionId(), 'Payment should have same id as get from payment setter.');
}
/**
* Wrapper to create request object.
*
* @return \OxidEsales\PayPalModule\Core\Request
*/
protected function prepareRequest()
{
$_POST['zzz'] = 'yyy';
$request = new \OxidEsales\PayPalModule\Core\Request();
return $request;
}
/**
* Wrapper to create oxLang.
*
* @return \OxidEsales\Eshop\Core\Language
*/
protected function prepareLang()
{
$lang = oxNew(\OxidEsales\Eshop\Core\Language::class);
return $lang;
}
/**
* @param \OxidEsales\PayPalModule\Core\Request $request request.
* @param \OxidEsales\PayPalModule\Model\OrderPayment $orderPayment order payment.
*
* @return \OxidEsales\PayPalModule\Model\IPNRequestPaymentSetter
*/
protected function prepareRequestPaymentSetter($request, $orderPayment)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\IPNRequestPaymentSetter::class);
$mockBuilder->setMethods(['setRequest', 'getRequestOrderPayment']);
$payPalIPNPaymentSetter = $mockBuilder->getMock();
$payPalIPNPaymentSetter->expects($this->atLeastOnce())->method('setRequest')->with($request);
$payPalIPNPaymentSetter->expects($this->atLeastOnce())->method('getRequestOrderPayment')->will($this->returnValue($orderPayment));
return $payPalIPNPaymentSetter;
}
/**
* Wrapper to create order payment.
*
* @param string $transactionId transaction id.
* @param bool $valid if payment should be marked as not valid.
* @param string $validationMessage validation message
*
* @return \OxidEsales\PayPalModule\Model\OrderPayment
*/
protected function prepareOrderPayment($transactionId, $valid = true, $validationMessage = '')
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setPaymentId('__a24das5das45');
$orderPayment->setOrderId('_sOrderId');
$orderPayment->setTransactionId($transactionId);
if (!$valid) {
$orderPayment->setIsValid(false);
}
if ($validationMessage) {
$utilsDate = \OxidEsales\Eshop\Core\Registry::getUtilsDate();
$date = date('Y-m-d H:i:s', $utilsDate->getTime());
$orderPayment->addComment($date . ' ' . $validationMessage);
}
return $orderPayment;
}
/**
* Wrapper to create payment validator.
* Check if called with correct parameters. Always return mocked validation information.
*
* @param \OxidEsales\PayPalModule\Model\OrderPayment $requestOrderPayment object validator will be called with.
* @param \OxidEsales\PayPalModule\Model\OrderPayment $orderPayment object validator will return.
* @param \OxidEsales\Eshop\Core\Language $lang set to validator to translate validation failure message.
* @param bool $valid set if order is valid.
* @param string $validationMessage validation message.
*
* @return \OxidEsales\PayPalModule\Model\IPNPaymentValidator
*/
protected function prepareIPNPaymentValidator($requestOrderPayment, $orderPayment, $lang, $valid, $validationMessage)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\IPNPaymentValidator::class);
$mockBuilder->setMethods(['setRequestOrderPayment', 'setOrderPayment', 'setLang', 'isValid', 'getValidationFailureMessage']);
$payPalIPNPaymentValidator = $mockBuilder->getMock();
$payPalIPNPaymentValidator->expects($this->atLeastOnce())->method('setRequestOrderPayment')->with($requestOrderPayment);
$payPalIPNPaymentValidator->expects($this->atLeastOnce())->method('setOrderPayment')->with($orderPayment);
$payPalIPNPaymentValidator->expects($this->atLeastOnce())->method('setLang')->with($lang);
$payPalIPNPaymentValidator->expects($this->atLeastOnce())->method('isValid')->will($this->returnValue($valid));
// Validation message will be checked only when validation fail.
$payPalIPNPaymentValidator->expects($this->any())->method('getValidationFailureMessage')->will($this->returnValue($validationMessage));
return $payPalIPNPaymentValidator;
}
}

View File

@@ -0,0 +1,360 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing \OxidEsales\PayPalModule\Model\IPNPaymentCreator class.
*/
class IPNPaymentCreatorTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/** @var string test order dummy oxid */
const TEST_ORDER_ID = '_sometestoxorderoxid';
/** @var string PayPal transaction id */
const PAYPAL_TRANSACTION_ID = '5H706430HM112602B';
/** @var string PayPal id of authorization transaction */
const PAYPAL_AUTHID = '5H706430HM1126666';
/** @var string PayPal parent transaction id*/
const PAYPAL_PARENT_TRANSACTION_ID = '8HF77866N86936335';
/** @var string Amount paid*/
const PAYMENT_AMOUNT = 30.66;
/** @var string currency specifier*/
const PAYMENT_CURRENCY = 'EUR';
/** @var string PayPal correlation id for transaction*/
const PAYMENT_CORRELATION_ID = '361b9ebf97777';
/** @var string PayPal correlation id for authorization transaction*/
const AUTH_CORRELATION_ID = '361b9ebf9bcee';
/**
* Fixture set up.
*/
protected function setUp(): void
{
parent::setUp();
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpaymentcomments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpayments`');
}
/**
* Test setter and getter.
*/
public function testSetGetRequest()
{
$data = $this->getIPNDataCapture();
$request = $this->prepareRequest($data);
$paymentBuilder = oxNew(\OxidEsales\PayPalModule\Model\IPNPaymentCreator::class);
$paymentBuilder->setRequest($request);
$this->assertEquals($request, $paymentBuilder->getRequest(), 'Getter should return what is set in setter.');
}
/**
* Test handling new paypal order payment from IPN.
* Case that we do not have a parent transaction and nothing needs to be done.
*/
public function testPayPalIPNPaymentCreationNoParentFound()
{
$ipnData = $this->getIPNDataCapture();
$request = $this->prepareRequest($ipnData);
$paymentCreator = oxNew(\OxidEsales\PayPalModule\Model\IPNPaymentCreator::class);
$paymentCreator->setRequest($request);
$requestOrderPayment = $this->createPayPalOrderPaymentFromRequest($ipnData, 'capture');
$requestOrderPayment = $paymentCreator->handleOrderPayment($requestOrderPayment);
$this->assertNull($requestOrderPayment);
}
/**
* Test handling new paypal order payment from IPN.
* Case that parent transaction exists and is of kind authorization
*/
public function testPayPalIPNPaymentCreationForNewCapture()
{
$this->createPayPalOrderPaymentAuthorization();
$ipnData = $this->getIPNDataCapture();
$request = $this->prepareRequest($ipnData);
$paymentCreator = oxNew(\OxidEsales\PayPalModule\Model\IPNPaymentCreator::class);
$paymentCreator->setRequest($request);
$requestOrderPayment = $this->createPayPalOrderPaymentFromRequest($ipnData,'capture');
$requestOrderPayment = $paymentCreator->handleOrderPayment($requestOrderPayment);
$this->assertTrue( 0 < $requestOrderPayment->getId());
}
/**
* Test handling new paypal order payment from IPN.
* Case that parent transaction exists and is of kind authorization.
* Test if payment memo is added correctly.
*/
public function testPayPalIPNPaymentCreationForNewCaptureWithMemo()
{
$this->createPayPalOrderPaymentAuthorization();
$ipnData = $this->getIPNDataCapture();
$request = $this->prepareRequest($ipnData);
$paymentCreator = oxNew(\OxidEsales\PayPalModule\Model\IPNPaymentCreator::class);
$paymentCreator->setRequest($request);
$requestOrderPayment = $this->createPayPalOrderPaymentFromRequest($ipnData,'capture');
$requestOrderPayment = $paymentCreator->handleOrderPayment($requestOrderPayment);
$memoList = $requestOrderPayment->getCommentList();
$this->assertEquals($memoList->getPaymentId(), $requestOrderPayment->getId());
$this->assertEquals('capture_new', $memoList->current()->getComment());
}
/**
* Test handling new paypal order payment from IPN.
* Case that parent transaction exists and is of kind authorization.
* Test if authorization status is changed from Pending to Completed.
*/
public function testPayPalIPNPaymentAuthorizationStatusUpdate()
{
$authorization = $this->createPayPalOrderPaymentAuthorization();
$this->assertEquals('Pending', $authorization->getStatus());
$ipnData = $this->getIPNDataCapture();
$request = $this->prepareRequest($ipnData);
$paymentCreator = oxNew(\OxidEsales\PayPalModule\Model\IPNPaymentCreator::class);
$paymentCreator->setRequest($request);
$requestOrderPayment = $this->createPayPalOrderPaymentFromRequest($ipnData,'capture');
$paymentCreator->handleOrderPayment($requestOrderPayment);
$authorization->load();
$this->assertEquals('Completed', $authorization->getStatus());
}
/**
* Test handling new paypal order refund payment from IPN.
* Case that parent transaction exists and is of kind capture.
*/
public function testPayPalIPNPaymentRefund()
{
$this->createPayPalOrderPaymentAuthorization();
$parentTransaction = $this->createPayPalOrderPaymentParent();
$ipnData = $this->getIPNDataRefund();
$request = $this->prepareRequest($ipnData);
$paymentCreator = oxNew(\OxidEsales\PayPalModule\Model\IPNPaymentCreator::class);
$paymentCreator->setRequest($request);
$requestOrderPayment = $this->createPayPalOrderPaymentFromRequest($ipnData,'refund');
$requestOrderPayment = $paymentCreator->handleOrderPayment($requestOrderPayment);
$this->assertTrue( 0 < $requestOrderPayment->getId());
$parentTransaction->load();
$this->assertEquals(self::PAYMENT_AMOUNT * 0.5, $parentTransaction->getRefundedAmount());
}
/**
* Wrapper to create request object.
*
* @param array $data
*
* @return \OxidEsales\PayPalModule\Core\Request
*/
private function prepareRequest($data)
{
$_POST = $data;
$request = new \OxidEsales\PayPalModule\Core\Request();
return $request;
}
/**
* Get IPN test data for capture transaction.
*
* @return array
*/
private function getIPNDataCapture()
{
$data = array(
'payment_type' => 'instant',
'payment_date' => '00:54:36 Jun 03, 2015 PDT',
'payment_status' => 'Completed',
'payer_status' => 'verified',
'first_name' => 'Max',
'last_name' => 'Muster',
'payer_email' => 'buyer@paypalsandbox_com',
'payer_id' => 'TESTBUYERID01',
'address_name' => 'Max_Muster',
'address_city' => 'Freiburg',
'address_street' => 'Blafööstraße_123',
'charset' => 'UTF-8',
'transaction_entity' => 'payment',
'address_country_code' => 'DE',
'notify_version' => '3_8',
'custom' => 'Bestellnummer_8',
'parent_txn_id' => self::PAYPAL_AUTHID,
'txn_id' => self::PAYPAL_TRANSACTION_ID,
'auth_id' => self::PAYPAL_AUTHID,
'receiver_email' => 'devbiz@oxid-esales_com',
'item_name' => 'Bestellnummer_8',
'mc_currency' => 'EUR',
'test_ipn' => '1',
'auth_amount' => self::PAYMENT_AMOUNT,
'mc_gross' => self::PAYMENT_AMOUNT,
'correlation_id' => self::PAYMENT_CORRELATION_ID,
'auth_status' => 'Completed',
'memo' => 'capture_new'
);
return $data;
}
/**
* Get IPN test data for refund transaction.
*
* @return array
*/
private function getIPNDataRefund()
{
$data = array(
'payment_type' => 'instant',
'payment_date' => '00:54:36 Jun 03, 2015 PDT',
'payment_status' => 'Refunded',
'payer_status' => 'verified',
'first_name' => 'Max',
'last_name' => 'Muster',
'payer_email' => 'buyer@paypalsandbox_com',
'payer_id' => 'TESTBUYERID01',
'address_name' => 'Max_Muster',
'address_city' => 'Freiburg',
'address_street' => 'Blafööstraße_123',
'charset' => 'UTF-8',
'transaction_entity' => 'payment',
'address_country_code' => 'DE',
'notify_version' => '3_8',
'custom' => 'Bestellnummer_8',
'parent_txn_id' => self::PAYPAL_PARENT_TRANSACTION_ID,
'txn_id' => self::PAYPAL_TRANSACTION_ID,
'auth_id' => self::PAYPAL_AUTHID,
'receiver_email' => 'devbiz@oxid-esales_com',
'item_name' => 'Bestellnummer_8',
'mc_currency' => 'EUR',
'test_ipn' => '1',
'auth_amount' => self::PAYMENT_AMOUNT,
'mc_gross' => -self::PAYMENT_AMOUNT * 0.5,
'correlation_id' => self::AUTH_CORRELATION_ID,
'memo' => 'refund_new'
);
return $data;
}
/**
* Create order payment authorization or capture.
* Object is NOT saved into db.
*
* @param string $mode Chose type of orderpayment (authorization or capture)
*
* @return \OxidEsales\PayPalModule\Model\OrderPayment
*/
private function createPayPalOrderPaymentFromRequest($fromIPN, $action = 'capture')
{
$paypalOrderPayment = oxNew(\OxidEsales\PayPalModule\Model\OrderPayment::class);
$paypalOrderPayment->setOrderid(self::TEST_ORDER_ID);
$paypalOrderPayment->setAction($action);
$paypalOrderPayment->setTransactionId($fromIPN['txn_id']);
$paypalOrderPayment->setAmount(abs($fromIPN['mc_gross']));
$paypalOrderPayment->setCurrency($fromIPN['mc_currency']);
$paypalOrderPayment->setStatus($fromIPN['payment_status']);
$paypalOrderPayment->setCorrelationId($fromIPN['correlation_id']);
$paypalOrderPayment->setDate('2015-04-01 13:13:13');
return $paypalOrderPayment;
}
/**
* Create order payment authorization or capture.
* Object is NOT saved into db.
*
* @param string $mode Chose type of orderpayment (authorization or capture)
*
* @return \OxidEsales\PayPalModule\Model\OrderPayment
*/
private function createPayPalOrderPayment($mode = 'authorization')
{
$data = array();
$data['authorization'] = array(
'setAction' => 'authorization',
'setTransactionId' => self::PAYPAL_AUTHID,
'setAmount' => self::PAYMENT_AMOUNT,
'setCurrency' => self::PAYMENT_CURRENCY,
'setStatus' => 'Pending',
'setCorrelationId' => self::AUTH_CORRELATION_ID,
'setDate' => '2015-04-01 12:12:12'
);
$data['capture'] = array(
'setAction' => 'capture',
'setTransactionId' => self::PAYPAL_PARENT_TRANSACTION_ID,
'setAmount' => self::PAYMENT_AMOUNT,
'setCurrency' => self::PAYMENT_CURRENCY,
'setStatus' => 'Completed',
'setCorrelationId' => self::PAYMENT_CORRELATION_ID,
'setDate' => '2015-04-01 13:13:13'
);
$paypalOrderPayment = oxNew(\OxidEsales\PayPalModule\Model\OrderPayment::class);
$paypalOrderPayment->setOrderid(self::TEST_ORDER_ID);
foreach ($data[$mode] as $function => $argument) {
$paypalOrderPayment->$function($argument);
}
$paypalOrderPayment->save();
return $paypalOrderPayment;
}
/**
* Test helper for creating order payment parent transaction with PayPal.
*
* @return \OxidEsales\PayPalModule\Model\OrderPayment
*/
private function createPayPalOrderPaymentAuthorization()
{
$orderPayment = $this->createPayPalOrderPayment('authorization');
return $orderPayment;
}
/**
* Test helper for creating order payment parent transaction with PayPal.
*
* @return \OxidEsales\PayPalModule\Model\OrderPayment
*/
private function createPayPalOrderPaymentParent()
{
$orderPaymentParent = $this->createPayPalOrderPayment('capture');
return $orderPaymentParent;
}
}

View File

@@ -0,0 +1,119 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing \OxidEsales\PayPalModule\Model\IPNPaymentValidator class.
*/
class IPNPaymentValidatorTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Data provider for testIsValid()
*
* @return array
*/
public function providerIsValid()
{
// We test with not installed module, so we check for translation constant - PAYPAL_INFORMATION.
// If module would be installed, translation would be returned instead of constant name.
return array(
array(true, '', null, null, null, null),
array(true, '', 'USD', 125.38, 'USD', 125.38),
array(true, '', 'EUR', 0.08, 'EUR', 0.08),
array(false, 'Bezahlinformation: 0.09 USD. PayPal-Information: 0.08 EUR.'
, 'EUR', 0.08, 'USD', 0.09),
array(false, 'Bezahlinformation: 0.08 USD. PayPal-Information: 0.08 EUR.'
, 'EUR', 0.08, 'USD', 0.08),
array(false, 'Bezahlinformation: 0.09 EUR. PayPal-Information: 0.08 EUR.'
, 'EUR', 0.08, 'EUR', 0.09),
);
}
/**
* @dataProvider providerIsValid
*
* @param $isValidExpected
* @param $validationMessageExpected
* @param $currencyPayPal
* @param $pricePayPal
* @param $currencyPayment
* @param $amountPayment
*/
public function testIsValid($isValidExpected, $validationMessageExpected, $currencyPayPal, $pricePayPal, $currencyPayment, $amountPayment)
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setCurrency($currencyPayment);
$orderPayment->setAmount($amountPayment);
$requestOrderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$requestOrderPayment->setCurrency($currencyPayPal);
$requestOrderPayment->setAmount($pricePayPal);
$validationMessage = '';
$payPalIPNRequestValidator = new \OxidEsales\PayPalModule\Model\IPNPaymentValidator();
$payPalIPNRequestValidator->setLang(\OxidEsales\Eshop\Core\Registry::getLang());
$payPalIPNRequestValidator->setOrderPayment($orderPayment);
$payPalIPNRequestValidator->setRequestOrderPayment($requestOrderPayment);
$isValid = $payPalIPNRequestValidator->isValid();
if (!$isValidExpected) {
$validationMessage = $payPalIPNRequestValidator->getValidationFailureMessage();
}
$this->assertEquals($isValidExpected, $isValid, 'IPN request validation state is not as expected. ');
$this->assertEquals($validationMessageExpected, $validationMessage, 'IPN request validation message is not as expected. ');
}
public function testSetGetOrderPayment()
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setCurrency('EUR');
$orderPayment->setAmount('12.23');
$payPalIPNRequestValidator = new \OxidEsales\PayPalModule\Model\IPNPaymentValidator();
$payPalIPNRequestValidator->setOrderPayment($orderPayment);
$this->assertEquals($orderPayment, $payPalIPNRequestValidator->getOrderPayment(), 'Getter should return same as set in setter.');
}
public function testSetGetRequestOrderPayment()
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setCurrency('EUR');
$orderPayment->setAmount('12.23');
$payPalIPNRequestValidator = new \OxidEsales\PayPalModule\Model\IPNPaymentValidator();
$payPalIPNRequestValidator->setRequestOrderPayment($orderPayment);
$this->assertEquals($orderPayment, $payPalIPNRequestValidator->getRequestOrderPayment(), 'Getter should return same as set in setter.');
}
public function testSetGetLang()
{
$lang = oxNew(\OxidEsales\Eshop\Core\Language::class);
$lang->setBaseLanguage(0);
$payPalIPNRequestValidator = new \OxidEsales\PayPalModule\Model\IPNPaymentValidator();
$payPalIPNRequestValidator->setLang($lang);
$this->assertEquals($lang, $payPalIPNRequestValidator->getLang(), 'Getter should return same as set in setter.');
}
}

View File

@@ -0,0 +1,123 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing oePayPalIPNRequestVerifier class.
*/
class IPNProcessorTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function testSetGetRequest()
{
$requestSet = new \OxidEsales\PayPalModule\Core\Request();
$processor = new \OxidEsales\PayPalModule\Model\IPNProcessor();
$processor->setRequest($requestSet);
$this->assertEquals($requestSet, $processor->getRequest(), 'Getter should return what is set in setter.');
}
public function testSetGetLang()
{
$lang = oxNew(\OxidEsales\Eshop\Core\Language::class);
$processor = new \OxidEsales\PayPalModule\Model\IPNProcessor();
$processor->setLang($lang);
$this->assertEquals($lang, $processor->getLang(), 'Getter should return what is set in setter.');
}
public function testSetGetPaymentBuilder()
{
$paymentBuilder = new \OxidEsales\PayPalModule\Model\IPNPaymentBuilder();
$processor = new \OxidEsales\PayPalModule\Model\IPNProcessor();
$processor->setPaymentBuilder($paymentBuilder);
$this->assertEquals($paymentBuilder, $processor->getPaymentBuilder(), 'Getter should return what is set in setter.');
}
public function testGetPaymentBuilder()
{
$processor = new \OxidEsales\PayPalModule\Model\IPNProcessor();
$this->assertTrue($processor->getPaymentBuilder() instanceof \OxidEsales\PayPalModule\Model\IPNPaymentBuilder, 'Getter should create payment builder if nothing is set.');
}
public function testSetGetOrderManager()
{
$orderManager = new \OxidEsales\PayPalModule\Model\OrderManager();
$processor = new \OxidEsales\PayPalModule\Model\IPNProcessor();
$processor->setOrderManager($orderManager);
$this->assertEquals($orderManager, $processor->getOrderManager(), 'Getter should return what is set in setter.');
}
public function testGetOrderManager()
{
$processor = new \OxidEsales\PayPalModule\Model\IPNProcessor();
$this->assertTrue($processor->getOrderManager() instanceof \OxidEsales\PayPalModule\Model\OrderManager, 'Getter should create order manager if nothing is set.');
}
public function testProcess()
{
$orderUpdated = true;
$lang = oxNew(\OxidEsales\Eshop\Core\Language::class);
$request = new \OxidEsales\PayPalModule\Core\Request();
$payment = new \OxidEsales\PayPalModule\Model\OrderPayment();
// Call Payment Builder with defined lang and defined request. Will return mocked payment.
$paymentBuilder = $this->preparePaymentBuilder($lang, $request, $payment);
// Call Order Manager with payment from payment builder. Will return if order updated == PayPal call processed.
$payPalOrderManager = $this->prepareOrderManager($payment, $orderUpdated);
$payPalIPNProcessor = new \OxidEsales\PayPalModule\Model\IPNProcessor();
$payPalIPNProcessor->setLang($lang);
$payPalIPNProcessor->setRequest($request);
$payPalIPNProcessor->setPaymentBuilder($paymentBuilder);
$payPalIPNProcessor->setOrderManager($payPalOrderManager);
$this->assertEquals($orderUpdated, $payPalIPNProcessor->process(), 'Order manager decide if order updated - processed successfully.');
}
protected function preparePaymentBuilder($lang, $request, $payment)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\IPNPaymentBuilder::class);
$mockBuilder->setMethods(['setLang', 'setRequest', 'buildPayment']);
$paymentBuilder = $mockBuilder->getMock();
$paymentBuilder->expects($this->atLeastOnce())->method('setLang')->with($lang);
$paymentBuilder->expects($this->atLeastOnce())->method('setRequest')->with($request);
$paymentBuilder->expects($this->atLeastOnce())->method('buildPayment')->will($this->returnValue($payment));
return $paymentBuilder;
}
protected function prepareOrderManager($payment, $orderUpdated)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\OrderManager::class);
$mockBuilder->setMethods(['setOrderPayment', 'updateOrderStatus']);
$orderManager = $mockBuilder->getMock();
$orderManager->expects($this->atLeastOnce())->method('setOrderPayment')->with($payment);
$orderManager->expects($this->atLeastOnce())->method('updateOrderStatus')->will($this->returnValue($orderUpdated));
return $orderManager;
}
}

View File

@@ -0,0 +1,108 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing oePayPalIPNRequest class.
*/
class IPNRequestPaymentSetterTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function providerGetRequestOrderPayment()
{
return array(
'capture' => array(
array(
'payment_status' => 'Completed',
'txn_id' => 'a2s12as1d2',
'receiver_email' => 'test@oxid-esales.com',
'mc_gross' => 15.66,
'mc_currency' => 'EUR',
'ipn_track_id' => 'corrxxx',
'payment_date' => '00:54:36 Jun 03, 2015 PDT',
),
'capture'
),
'nothing' => array(null, ''),
'refund' => array(
array(
'payment_status' => 'Refunded',
'txn_id' => 'a2s12as1dxxx',
'receiver_email' => 'test@oxid-esales.com',
'mc_gross' => -6.66,
'mc_currency' => 'EUR',
'correlation_id' => 'corryyy',
'payment_date' => '00:54:36 Jun 03, 2015 PDT',
),
'refund'
),
);
}
/**
* Test case for \OxidEsales\PayPalModule\Model\IPNRequestPaymentSetter::getRequestOrderPayment
* Test case for \OxidEsales\PayPalModule\Model\IPNRequestPaymentSetter::setRequestOrderPayment
* Test case for \OxidEsales\PayPalModule\Model\IPNRequestPaymentSetter::_prepareOrderPayment
* Test case for \OxidEsales\PayPalModule\Model\IPNRequestPaymentSetter::getRequest
* Test case for \OxidEsales\PayPalModule\Model\IPNRequestPaymentSetter::getAction
* Test case for \OxidEsales\PayPalModule\Model\IPNRequestPaymentSetter::getAmount
*
* @param array $params parameters for POST imitating PayPal.
* @param string $expectedAction Expected action for resulting payment.
*
* @dataProvider providerGetRequestOrderPayment
*/
public function testGetRequestOrderPayment($params, $expectedAction)
{
$payPalExpectedPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
if (!empty($params)) {
$payPalExpectedPayment->setStatus($params['payment_status']);
$payPalExpectedPayment->setTransactionId($params['txn_id']);
$payPalExpectedPayment->setCurrency($params['mc_currency']);
$payPalExpectedPayment->setAmount(abs($params['mc_gross']));
$payPalExpectedPayment->setAction($expectedAction);
$correlationId = empty($params['correlation_id']) ? $params['ipn_track_id'] :$params['correlation_id'];
$payPalExpectedPayment->setCorrelationId($correlationId);
$payPalExpectedPayment->setDate(date('Y-m-d H:i:s', strtotime($params['payment_date'])));
} else {
$payPalExpectedPayment->setStatus(null);
$payPalExpectedPayment->setTransactionId(null);
$payPalExpectedPayment->setCurrency(null);
$payPalExpectedPayment->setAmount(null);
$payPalExpectedPayment->setCorrelationId(null);
$payPalExpectedPayment->setDate(null);
$payPalExpectedPayment->setAction('capture');
}
$_POST = $params;
$request = new \OxidEsales\PayPalModule\Core\Request();
$payPalPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$payPalIPNRequestSetter = new \OxidEsales\PayPalModule\Model\IPNRequestPaymentSetter();
$payPalIPNRequestSetter->setRequest($request);
$payPalIPNRequestSetter->setRequestOrderPayment($payPalPayment);
$requestOrderPayment = $payPalIPNRequestSetter->getRequestOrderPayment();
$this->assertEquals($payPalExpectedPayment, $requestOrderPayment, 'Payment object do not have request parameters.');
}
}

View File

@@ -0,0 +1,133 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing \OxidEsales\PayPalModule\Model\IPNRequestValidator class.
*/
class IPNRequestValidatorTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Data provider for testIsValid()
*
* @return array
*/
public function providerIsValid()
{
return array(
array(true, null, null, array('VERIFIED' => 'true')),
array(true, 'none@oxid-esales.com', array('receiver_email' => 'none@oxid-esales.com'), array('VERIFIED' => '')),
array(true, 'none2@oxid-esales.com', array('receiver_email' => 'none2@oxid-esales.com'), array('VERIFIED' => '')),
array(false, 'none@oxid-esales.com', array('receiver_email' => 'none2@oxid-esales.com'), array('VERIFIED' => '')),
array(false, null, null, null),
array(false, 'none2@oxid-esales.com', array('receiver_email' => 'none2@oxid-esales.com'), array('NOT_VERIFIED' => '')),
array(false, 'none@oxid-esales.com', array('receiver_email' => 'none2@oxid-esales.com'), array('someString' => '')),
);
}
/**
* @param bool $isValidExpected
* @param string $shopOwnerUserName
* @param array $payPalRequest
* @param array $payPalResponseData
*
* @dataProvider providerIsValid
*/
public function testIsValid($isValidExpected, $shopOwnerUserName, $payPalRequest, $payPalResponseData)
{
$payPalIPNRequestValidator = $this->getIPNRequestValidator($payPalRequest, $payPalResponseData, $shopOwnerUserName);
$isValid = $payPalIPNRequestValidator->isValid();
$this->assertEquals($isValidExpected, $isValid, 'IPN request validation state is not as expected.');
}
/**
* Data provider for testIsValid()
*
* @return array
*/
public function providerGetValidationFailureMessage()
{
$cases = array();
$messages = array(
'Shop owner' => 'none@oxid-esales.com', 'PayPal ID' => 'none2@oxid-esales.com', 'PayPal ACK' => 'VERIFIED',
'PayPal Full Request' => 'Array( [receiver_email] => none2@oxid-esales.com)',
'PayPal Full Response' => 'Array( [VERIFIED] => )',
);
$cases[] = array($messages, 'none@oxid-esales.com', array('receiver_email' => 'none2@oxid-esales.com'), array('VERIFIED' => ''));
$messages = array(
'Shop owner' => '', 'PayPal ID' => '', 'PayPal ACK' => 'NOT VERIFIED',
'PayPal Full Request' => '',
'PayPal Full Response' => '',
);
$cases[] = array($messages, null, null, null);
$messages = array(
'Shop owner' => 'none2@oxid-esales.com', 'PayPal ID' => 'none2@oxid-esales.com', 'PayPal ACK' => 'NOT VERIFIED',
'PayPal Full Request' => 'Array( [receiver_email] => none2@oxid-esales.com)',
'PayPal Full Response' => 'Array( [NOT_VERIFIED] => )',
);
$cases[] = array($messages, 'none2@oxid-esales.com', array('receiver_email' => 'none2@oxid-esales.com'), array('NOT_VERIFIED' => ''));
$messages = array(
'Shop owner' => 'none@oxid-esales.com', 'PayPal ID' => 'none2@oxid-esales.com', 'PayPal ACK' => 'NOT VERIFIED',
'PayPal Full Request' => 'Array( [receiver_email] => none2@oxid-esales.com)',
'PayPal Full Response' => 'Array( [someString] => )',
);
$cases[] = array($messages, 'none@oxid-esales.com', array('receiver_email' => 'none2@oxid-esales.com'), array('someString' => ''));
return $cases;
}
/**
* @param bool $validationMessageExpected
* @param string $shopOwnerUserName
* @param array $payPalRequest
* @param array $payPalResponseData
*
* @dataProvider providerGetValidationFailureMessage
*/
public function testGetValidationFailureMessage($validationMessageExpected, $shopOwnerUserName, $payPalRequest, $payPalResponseData)
{
$payPalIPNRequestValidator = $this->getIPNRequestValidator($payPalRequest, $payPalResponseData, $shopOwnerUserName);
$validationMessage = $payPalIPNRequestValidator->getValidationFailureMessage();
foreach ($validationMessage as &$value) {
$value = str_replace("\n", '', $value);
}
$this->assertEquals($validationMessageExpected, $validationMessage, 'IPN request validation message is not as expected.');
}
protected function getIPNRequestValidator($payPalRequest, $payPalResponseData, $shopOwnerUserName)
{
$payPalResponse = new \OxidEsales\PayPalModule\Model\Response\ResponseDoVerifyWithPayPal();
$payPalResponse->setData($payPalResponseData);
$payPalIPNRequestValidator = new \OxidEsales\PayPalModule\Model\IPNRequestValidator();
$payPalIPNRequestValidator->setPayPalRequest($payPalRequest);
$payPalIPNRequestValidator->setPayPalResponse($payPalResponse);
$payPalIPNRequestValidator->setShopOwnerUserName($shopOwnerUserName);
return $payPalIPNRequestValidator;
}
}

View File

@@ -0,0 +1,195 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing \OxidEsales\PayPalModule\Model\IPNRequestVerifier class.
*/
class IPNRequestVerifierTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function testSetGetRequest()
{
$requestSet = new \OxidEsales\PayPalModule\Core\Request();
$handler = new \OxidEsales\PayPalModule\Model\IPNRequestVerifier();
$handler->setRequest($requestSet);
$requestGet = $handler->getRequest();
$this->assertEquals($requestSet, $requestGet, 'Getter should return what is set in setter.');
}
public function testSetGetShopOwner()
{
$shopOwner = 'some@oxid-esales.com';
$handler = new \OxidEsales\PayPalModule\Model\IPNRequestVerifier();
$handler->setShopOwner($shopOwner);
$this->assertEquals($shopOwner, $handler->getShopOwner(), 'Getter should return what is set in setter.');
}
public function testSetGetCommunicationService()
{
$ipnCommunicationService = new \OxidEsales\PayPalModule\Core\PayPalService();
$handler = new \OxidEsales\PayPalModule\Model\IPNRequestVerifier();
$handler->setCommunicationService($ipnCommunicationService);
$this->assertEquals($ipnCommunicationService, $handler->getCommunicationService(), 'Getter should return what is set in setter.');
}
public function testGetCommunicationService()
{
$handler = new \OxidEsales\PayPalModule\Model\IPNRequestVerifier();
$ipnCommunicationService = $handler->getCommunicationService();
$this->assertTrue(is_a($ipnCommunicationService, \OxidEsales\PayPalModule\Core\PayPalService::class));
}
public function testSetGetRequestValidator()
{
$paymentValidator = new \OxidEsales\PayPalModule\Model\IPNRequestValidator();
$handler = new \OxidEsales\PayPalModule\Model\IPNRequestVerifier();
$handler->setIPNRequestValidator($paymentValidator);
$this->assertEquals($paymentValidator, $handler->getIPNRequestValidator(), 'Getter should return what is set in setter.');
}
public function testGetRequestValidator()
{
$handler = new \OxidEsales\PayPalModule\Model\IPNRequestVerifier();
$ipnRequestValidator = $handler->getIPNRequestValidator();
$this->assertTrue(is_a($ipnRequestValidator, \OxidEsales\PayPalModule\Model\IPNRequestValidator::class));
}
public function testSetGetPayPalRequest()
{
$payPalRequest = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest();
$handler = new \OxidEsales\PayPalModule\Model\IPNRequestVerifier();
$handler->setPayPalRequest($payPalRequest);
$this->assertEquals($payPalRequest, $handler->getPayPalRequest(), 'Getter should return what is set in setter.');
}
public function testGetPayPalRequest()
{
$handler = new \OxidEsales\PayPalModule\Model\IPNRequestVerifier();
$this->assertTrue(is_a($handler->getPayPalRequest(), \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest::class));
}
public function testSetGetFailureMessage()
{
$failureMessage = 'some message';
$handler = new \OxidEsales\PayPalModule\Model\IPNRequestVerifier();
$handler->setFailureMessage($failureMessage);
$this->assertEquals($failureMessage, $handler->getFailureMessage(), 'Getter should return what is set in setter.');
}
public function providerRequestCorrect()
{
return array(
array(true),
array(false),
);
}
/**
* @dataProvider providerRequestCorrect
*/
public function testRequestCorrect($validatorSayIsValid)
{
$shopOwner = 'someone@oxid-esales.com';
$payPalRequest = array('zzz' => 'yyy');
$payPalResponse = array('aaa' => 'bbb');
$validatorFailureMessage = 'some message';
// Mock request to simulate PayPal request information.
$request = $this->prepareRequest($payPalRequest);
// Mock communication service as we do not want actually call PayPal to check if request is from there.
// Check iff communication is done with correct request.
$communicationService = $this->prepareCommunicationService($payPalResponse);
// Mock Validator to check if it gets request and response with shop owner.
// Will return if is valid from what is mocked.
$ipnRequestValidator = $this->preparePayPalValidator($payPalRequest, $payPalResponse, $shopOwner, $validatorSayIsValid, $validatorFailureMessage);
$handler = new \OxidEsales\PayPalModule\Model\IPNRequestVerifier();
$handler->setShopOwner($shopOwner);
$handler->setRequest($request);
$handler->setCommunicationService($communicationService);
$handler->setIPNRequestValidator($ipnRequestValidator);
$isValidPayPalCall = $handler->requestCorrect();
$failureMessage = $handler->getFailureMessage();
$this->assertEquals($validatorSayIsValid, $isValidPayPalCall, 'Validator decide if call is valid.');
if ($isValidPayPalCall) {
$this->assertTrue(is_null($failureMessage), 'Failure message is filled only if validation fail.');
} else {
$this->assertEquals($validatorFailureMessage, $failureMessage, 'Validator forms validation failure message.');
}
}
protected function prepareRequest($payPalRequest)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Request::class);
$mockBuilder->setMethods(['getPost']);
$request = $mockBuilder->getMock();
$request->expects($this->atLeastOnce())->method('getPost')->will($this->returnValue($payPalRequest));
return $request;
}
protected function prepareCommunicationService($payPalResponse)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
$mockBuilder->setMethods(['doVerifyWithPayPal']);
$communicationService = $mockBuilder->getMock();
$communicationService->expects($this->atLeastOnce())->method('doVerifyWithPayPal')->will($this->returnValue($payPalResponse));
return $communicationService;
}
protected function preparePayPalValidator($payPalRequest, $payPalResponse, $shopOwner, $validatorSayIsValid, $validatorFailureMessage)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\IPNRequestValidator::class);
$mockBuilder->setMethods(
['setPayPalRequest',
'setPayPalResponse',
'setShopOwnerUserName',
'isValid',
'getValidationFailureMessage']
);
$requestValidator = $mockBuilder->getMock();
$requestValidator->expects($this->atLeastOnce())->method('setPayPalRequest')->with($payPalRequest);
$requestValidator->expects($this->atLeastOnce())->method('setPayPalResponse')->with($payPalResponse);
$requestValidator->expects($this->atLeastOnce())->method('setShopOwnerUserName')->with($shopOwner);
$requestValidator->expects($this->atLeastOnce())->method('isValid')->will($this->returnValue($validatorSayIsValid));
$requestValidator->expects($this->any())->method('getValidationFailureMessage')->will($this->returnValue($validatorFailureMessage));
return $requestValidator;
}
}

View File

@@ -0,0 +1,80 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing oePayPalOxState class.
*/
class OrderActionManagerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Data provider for testIsActionAvailable()
*
* @return array
*/
public function isActionAvailableTest_dataProvider()
{
return array(
array('Sale', 'capture', 1000, 0, 0, 0, false),
array('Sale', 'reauthorize', 1000, 0, 0, 0, false),
array('Sale', 'void', 1000, 0, 0, 0, false),
array('Sale', 'refund', 1000, 0, 0, 0, false),
array('Authorization', 'capture', 1000, 999.99, 0, 0, true),
array('Authorization', 'capture', 1000, 900, 1200, 0, true),
array('Authorization', 'capture', 1000, 1000, 0, 0, false),
array('Authorization', 'capture', 1000, 1100, 0, 0, false),
array('Authorization', 'capture', 1000, 0, 0, 1000, false),
array('Authorization', 'reauthorize', 1000, 999.99, 0, 0, true),
array('Authorization', 'reauthorize', 1000, 900, 1200, 0, true),
array('Authorization', 'reauthorize', 1000, 1000, 0, 0, false),
array('Authorization', 'reauthorize', 1000, 1100, 0, 0, false),
array('Authorization', 'reauthorize', 1000, 0, 0, 1000, false),
array('Authorization', 'void', 1000, 999.99, 0, 0, true),
array('Authorization', 'void', 1000, 900, 1200, 0, true),
array('Authorization', 'void', 1000, 1000, 0, 0, false),
array('Authorization', 'void', 1000, 1100, 0, 0, false),
array('Authorization', 'void', 1000, 0, 0, 1000, false),
array('Authorization', 'refund', 1000, 0, 0, 0, false),
array('TestMode', 'testAction', -50, -5, 9999, 9999, false),
);
}
/**
* Tests isPayPalActionValid
*
* @dataProvider isActionAvailableTest_dataProvider
*/
public function testIsActionAvailable($transactionMode, $action, $total, $captured, $refunded, $voided, $isValid)
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setTotalOrderSum($total);
$order->setCapturedAmount($captured);
$order->setRefundedAmount($refunded);
$order->setVoidedAmount($voided);
$order->setTransactionMode($transactionMode);
$actionManager = new \OxidEsales\PayPalModule\Model\OrderActionManager();
$actionManager->setOrder($order);
$this->assertEquals($isValid, $actionManager->isActionAvailable($action));
}
}

View File

@@ -0,0 +1,190 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
use OxidEsales\PayPalModule\Controller\OrderController;
/**
* Testing oePayPalOxState class.
*/
class OrderManagerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function testGetOrder_noOrderSetWithPaymentSet_orderCreatedFomPayment()
{
$orderId = '_orderId';
$orderPayment = $this->prepareOrderPayment($orderId);
$payPalOrderManager = new \OxidEsales\PayPalModule\Model\OrderManager();
$payPalOrderManager->setOrderPayment($orderPayment);
$orderFromManager = $payPalOrderManager->getOrder();
$orderIdFromManager = $orderFromManager->getOrderid();
$this->assertEquals($orderId, $orderIdFromManager, 'Order id from manager is not same as in payment.');
}
public function testGetOrder_noOrderSetNoPaymentSet_noOrderCreated()
{
$payPalOrderManager = new \OxidEsales\PayPalModule\Model\OrderManager();
$orderFromManager = $payPalOrderManager->getOrder();
$this->assertEquals(null, $orderFromManager, 'No order should be created as no order set and no payment set.');
}
/**
* Check if correct Order Payment object passed to Calculator.
* Check if correct Order Status is stored afterword.
*/
public function testUpdateOrderStatus_withOrderPaymentWithOrder_orderStatusFromCalculator()
{
$orderId = '_orderId';
$order = $this->prepareOrder($orderId);
$orderPayment = $this->prepareOrderPayment($orderId);
$OrderCalculatedStatus = 'completed';
$payPalOrderPaymentStatusCalculator = $this->preparePayPalOrderPaymentStatusCalculator($orderPayment, $order, $OrderCalculatedStatus);
$payPalOrderManager = new \OxidEsales\PayPalModule\Model\OrderManager();
$payPalOrderManager->setOrderPayment($orderPayment);
$payPalOrderManager->setOrder($order);
$payPalOrderManager->setOrderPaymentStatusCalculator($payPalOrderPaymentStatusCalculator);
$orderUpdated = $payPalOrderManager->updateOrderStatus();
$payPalOrderManager->getOrder();
$orderNewStatus = $order->getPaymentStatus();
$this->assertEquals($OrderCalculatedStatus, $orderNewStatus, 'Order status did not change to calculator calculated.');
$this->assertTrue($orderUpdated, 'Order should be updated, and return indicates this with true.');
}
/**
* Check if correct Order Payment object passed to Calculator.
* Check if correct Order Status is stored afterword.
*/
public function testUpdateOrderStatus_noOrderPaymentWithOrder_orderStatusFromCalculator()
{
$orderId = '_orderId';
$order = $this->prepareOrder($orderId);
$orderPayment = null;
$OrderCalculatedStatus = 'completed';
$payPalOrderPaymentStatusCalculator = $this->preparePayPalOrderPaymentStatusCalculator($orderPayment, $order, $OrderCalculatedStatus);
$payPalOrderManager = new \OxidEsales\PayPalModule\Model\OrderManager();
$payPalOrderManager->setOrder($order);
$payPalOrderManager->setOrderPaymentStatusCalculator($payPalOrderPaymentStatusCalculator);
$orderUpdated = $payPalOrderManager->updateOrderStatus();
$payPalOrderManager->getOrder();
$orderNewStatus = $order->getPaymentStatus();
$this->assertEquals($OrderCalculatedStatus, $orderNewStatus, 'Order status did not change to calculator calculated.');
$this->assertTrue($orderUpdated, 'Order should be updated, and return indicates this with true.');
}
/**
* Check if correct Order Payment object passed to Calculator.
* Check if correct Order Status is stored afterword.
*/
public function testUpdateOrderStatus_withOrderPaymentNoOrder_orderStatusFromCalculator()
{
$orderId = '_orderId';
$order = $this->prepareOrder($orderId);
$orderPayment = $this->prepareOrderPayment($orderId);
$OrderCalculatedStatus = 'completed';
$payPalOrderPaymentStatusCalculator = $this->preparePayPalOrderPaymentStatusCalculator($orderPayment, $order, $OrderCalculatedStatus);
// Mock order manager to check if order is created from given payment. This prevents from database usage.
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\OrderManager::class);
$mockBuilder->setMethods(['getOrderFromPayment']);
$payPalOrderManager = $mockBuilder->getMock();
$payPalOrderManager->expects($this->once())->method('getOrderFromPayment')->with($orderPayment)->will($this->returnValue($order));
$payPalOrderManager->setOrderPayment($orderPayment);
$payPalOrderManager->setOrderPaymentStatusCalculator($payPalOrderPaymentStatusCalculator);
$orderUpdated = $payPalOrderManager->updateOrderStatus();
$payPalOrderManager->getOrder();
$orderNewStatus = $order->getPaymentStatus();
$this->assertEquals($OrderCalculatedStatus, $orderNewStatus, 'Order status did not change to calculator calculated.');
$this->assertTrue($orderUpdated, 'Order should be updated, and return indicates this with true.');
}
/**
* Check if correct Order Payment object passed to Calculator.
* Check if correct Order Status is stored afterword.
*/
public function testUpdateOrderStatus_noOrderPaymentNoOrder_orderStatusFromCalculator()
{
$payPalOrderManager = new \OxidEsales\PayPalModule\Model\OrderManager();
$orderUpdated = $payPalOrderManager->updateOrderStatus();
$this->assertFalse($orderUpdated, 'Order should be updated, and return indicates this with true.');
}
/**
* Create order with status different than order status calculator returns.
*
* @param string $orderId order id.
*
* @return \OxidEsales\PayPalModule\Model\PayPalOrder
*/
protected function prepareOrder($orderId)
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setPaymentStatus('pending');
$order->setOrderId($orderId);
return $order;
}
/**
* Create order payment with some transaction id and same order id as order in _prepareOrder().
*
* @param string $orderId order id.
*
* @return \OxidEsales\PayPalModule\Model\OrderPayment
*/
protected function prepareOrderPayment($orderId)
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setTransactionId('_asdadsd45a4sd5a4sd54a5');
$orderPayment->setOrderId($orderId);
return $orderPayment;
}
/**
* Mock order payment calculator.
* Check if called with correct parameters.
* Mock return calculated state. Order state should change according to this one.
*
* @param \OxidEsales\PayPalModule\Model\OrderPayment $orderPayment
* @param OrderController $order
* @param string $OrderCalculatedStatus
*
* @return \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator
*/
protected function preparePayPalOrderPaymentStatusCalculator($orderPayment, $order, $OrderCalculatedStatus)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator::class);
$mockBuilder->setMethods(['setOrderPayment', 'setOrder', 'getStatus']);
$payPalOrderPaymentStatusCalculator = $mockBuilder->getMock();
$payPalOrderPaymentStatusCalculator->expects($this->any())->method('setOrderPayment')->with($orderPayment);
$payPalOrderPaymentStatusCalculator->expects($this->once())->method('setOrder')->with($order);
$payPalOrderPaymentStatusCalculator->expects($this->any())->method('getStatus')->will($this->returnValue($OrderCalculatedStatus));
return $payPalOrderPaymentStatusCalculator;
}
}

View File

@@ -0,0 +1,75 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing oePayPalOxState class.
*/
class OrderPaymentActionManagerTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Data provider for testIsActionValidCapture()
*
* @return array
*/
public function isActionValid_dataProvider()
{
return array(
array('capture', 1000, 0, 'Completed', 'refund', true),
array('capture', 1000, 50, 'Completed', 'refund', true),
array('capture', 1000, 1000, 'Completed', 'refund', false),
array('capture', 0, 0, 'Completed', 'refund', false),
array('capture', 0, 20, 'Completed', 'refund', false),
array('capture', -30, 20, 'Completed', 'refund', false),
array('capture', 1000, 0, 'Pending', 'refund', false),
array('void', 1000, 0, 'Voided', 'refund', false),
array('authorization', 1000, 0, 'Pending', 'refund', false),
array('testAction', -99, -8, 'test', 'testAction', false),
);
}
/**
* Tests isPayPalActionValid
*
* @dataProvider isActionValid_dataProvider
*
* @param $paymentMethod
* @param $amount
* @param $refunded
* @param $state
* @param $action
* @param $isValid
*/
public function testIsActionAvailable($paymentMethod, $amount, $refunded, $state, $action, $isValid)
{
$payment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$payment->setAction($paymentMethod);
$payment->setAmount($amount);
$payment->setRefundedAmount($refunded);
$payment->setStatus($state);
$actionManager = new \OxidEsales\PayPalModule\Model\OrderPaymentActionManager();
$actionManager->setPayment($payment);
$this->assertEquals($isValid, $actionManager->isActionAvailable($action));
}
}

View File

@@ -0,0 +1,97 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing oxAccessRightException class.
*/
class OrderPaymentCommentListTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Setup: Prepare data - create need tables
*/
protected function setUp(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpaymentcomments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpayments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_order`');
}
/**
* Test case for oePayPalOrderPayment::oePayPalOrderPaymentList()
* Gets PayPal Order Payment history list
*/
public function testLoadOrderPayments()
{
$comment = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$comment->setDate('2013-02-03 12:12:12');
$comment->setComment('comment1');
$comment->setPaymentId(2);
$comment->save();
$comment = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$comment->setDate('2013-02-03 12:12:12');
$comment->setComment('comment2');
$comment->setPaymentId(2);
$comment->save();
$comments = new \OxidEsales\PayPalModule\Model\OrderPaymentCommentList();
$comments->load(2);
$this->assertEquals(2, count($comments));
$i = 1;
foreach ($comments as $comment) {
$this->assertEquals('comment' . $i++, $comment->getComment());
}
}
/**
* Test case for oePayPalOrderPayment::hasPendingPayment()
* Checks if list has pending payments
*/
public function testAddComment()
{
$list = new \OxidEsales\PayPalModule\Model\OrderPaymentCommentList();
$list->load('payment');
$this->assertEquals(0, count($list));
$comment = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$comment->setPaymentId('payment');
$comment->save();
$list = new \OxidEsales\PayPalModule\Model\OrderPaymentCommentList();
$list->load('payment');
$this->assertEquals(1, count($list));
$comment = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$comment->setComment('Comment');
$list->addComment($comment);
$list = new \OxidEsales\PayPalModule\Model\OrderPaymentCommentList();
$list->load('payment');
$this->assertEquals(2, count($list));
}
}

View File

@@ -0,0 +1,127 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing oxAccessRightException class.
*/
class OrderPaymentCommentTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Setup: Prepare data - create need tables
*/
protected function setUp(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpaymentcomments`');
}
/**
* Test case for \OxidEsales\PayPalModule\Model\PayPalOrder::save()
* Tests adding / getting PayPal Order Payment history item
*/
public function testSavePayPalPayPalOrder_insertIdSet()
{
$comment = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$comment->setCommentId(1);
$comment->setDate('2013-02-03 12:12:12');
$comment->setComment('comment');
$comment->setPaymentId(2);
$id = $comment->save();
$this->assertEquals(1, $id);
$commentLoaded = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$commentLoaded->load($comment->getCommentId());
$this->assertEquals(1, $commentLoaded->getCommentId());
$this->assertEquals('comment', $commentLoaded->getComment());
$this->assertEquals(2, $commentLoaded->getPaymentId());
$this->assertEquals('2013-02-03 12:12:12', $commentLoaded->getDate());
}
/**
* Test case for \OxidEsales\PayPalModule\Model\PayPalOrder::save()
* Tests adding / getting PayPal Order Payment history item
*/
public function testSavePayPalPayPalOrder_withoutDate_dateSetNow()
{
$comment = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$comment->setComment('comment');
$comment->setPaymentId(2);
$comment->save();
$commentLoaded = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$commentLoaded->load($comment->getCommentId());
$this->assertEquals('comment', $commentLoaded->getComment());
$this->assertEquals(date('Y-m-d'), substr($commentLoaded->getDate(), 0, 10));
}
/**
* Test case for \OxidEsales\PayPalModule\Model\PayPalOrder::save()
* Tests adding / getting PayPal Order Payment history item
*/
public function testSavePayPalPayPalOrder_insertIdNotSet()
{
$comment = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$comment->setDate('2013-02-03 12:12:12');
$comment->setComment('comment');
$comment->setPaymentId(2);
$commentId = $comment->save();
$commentLoaded = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$commentLoaded->load($commentId);
$this->assertEquals($commentId, $commentLoaded->getCommentId());
$this->assertEquals('comment', $commentLoaded->getComment());
$this->assertEquals(2, $commentLoaded->getPaymentId());
$this->assertEquals('2013-02-03 12:12:12', $commentLoaded->getDate());
}
/**
* Test case for \OxidEsales\PayPalModule\Model\PayPalOrder::save()
* Tests adding / getting PayPal Order Payment history item
*/
public function testSavePayPalPayPalOrder_update()
{
$comment = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$comment->setCommentId(10);
$comment->setDate('2013-02-03 12:12:12');
$comment->setComment('comment');
$comment->setPaymentId(2);
$comment->save();
$commentLoaded = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$commentLoaded->load(10);
$commentLoaded->setComment('comment comment');
$id = $commentLoaded->save();
$this->assertEquals(10, $id);
$commentLoaded = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$commentLoaded->load(10);
$this->assertEquals(10, $commentLoaded->getCommentId());
$this->assertEquals('comment comment', $commentLoaded->getComment());
$this->assertEquals(2, $commentLoaded->getPaymentId());
$this->assertEquals('2013-02-03 12:12:12', $commentLoaded->getDate());
}
}

View File

@@ -0,0 +1,251 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing ePayPalOrderPaymentListCalculator class.
*/
class OrderPaymentListCalculatorTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Setup: Prepare data - create need tables
*/
protected function setUp(): void
{
parent::setUp();
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpayments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_order`');
}
/**
* Test case that no payment list is set.
*/
public function testCalculateNoPaymentList()
{
$listCalculator = oxNew(\OxidEsales\PayPalModule\Model\OrderPaymentListCalculator::class);
$listCalculator->calculate();
$this->assertEquals('0.0', $listCalculator->getCapturedAmount());
$this->assertEquals('0.0', $listCalculator->getVoidedAmount());
$this->assertEquals('0.0', $listCalculator->getRefundedAmount());
}
/**
* Test case that a payment list is set.
*/
public function testCapturedAmountCalculateWithPaymentList()
{
$orderPaymentList = $this->createOrderPaymentList();
/** @var \OxidEsales\PayPalModule\Model\OrderPaymentListCalculator $listCalculator */
$listCalculator = oxNew(\OxidEsales\PayPalModule\Model\OrderPaymentListCalculator::class);
$listCalculator->setPaymentList($orderPaymentList);
$listCalculator->calculate();
$this->assertEquals('11.22', $listCalculator->getCapturedAmount());
}
/**
* Test case that a payment list is set.
* Void data is taken from voided Authorization.
*/
public function testVoidedAmountCalculateWithPaymentList()
{
$orderPaymentList = $this->createOrderPaymentList();
$listCalculator = oxNew(\OxidEsales\PayPalModule\Model\OrderPaymentListCalculator::class);
$listCalculator->setPaymentList($orderPaymentList);
$listCalculator->calculate();
$this->assertEquals('44.33', $listCalculator->getVoidedAmount());
}
/**
* Test case that a payment list is set.
*/
public function testRefundedAmountCalculateWithPaymentList()
{
$orderPaymentList = $this->createOrderPaymentList();
$listCalculator = oxNew(\OxidEsales\PayPalModule\Model\OrderPaymentListCalculator::class);
$listCalculator->setPaymentList($orderPaymentList);
$listCalculator->calculate();
$this->assertEquals('6.78', $listCalculator->getRefundedAmount());
}
/**
* Test case that a payment list is set.
* Voided amount comes from void action.
*/
public function testCapturedAmountCalculateWithPaymentListAndVoidAction()
{
$orderPaymentList = $this->createOrderPaymentListContainingVoidAction();
$listCalculator = oxNew(\OxidEsales\PayPalModule\Model\OrderPaymentListCalculator::class);
$listCalculator->setPaymentList($orderPaymentList);
$listCalculator->calculate();
$this->assertEquals('30.00', $listCalculator->getCapturedAmount());
}
/**
* Test case that a payment list is set.
* Voided amount comes from void action.
*/
public function testVoidedAmountCalculateWithPaymentListAndVoidAction()
{
$orderPaymentList = $this->createOrderPaymentListContainingVoidAction();
$listCalculator = oxNew(\OxidEsales\PayPalModule\Model\OrderPaymentListCalculator::class);
$listCalculator->setPaymentList($orderPaymentList);
$listCalculator->calculate();
$this->assertEquals('11.00', $listCalculator->getVoidedAmount());
}
/**
* Test case that a payment list is set.
* Voided amount comes from void action.
*/
public function testRefundedAmountCalculateWithPaymentListAndVoidAction()
{
$orderPaymentList = $this->createOrderPaymentListContainingVoidAction();
$listCalculator = oxNew(\OxidEsales\PayPalModule\Model\OrderPaymentListCalculator::class);
$listCalculator->setPaymentList($orderPaymentList);
$listCalculator->calculate();
$this->assertEquals('10.00', $listCalculator->getRefundedAmount());
}
/**
* Test helper, prepares some paypal order payments.
*
* @return \OxidEsales\PayPalModule\Model\OrderPaymentList
*/
private function createOrderPaymentList()
{
$orderId = '123';
$orderPayment = oxNew(\OxidEsales\PayPalModule\Model\OrderPayment::class);
$orderPayment->setPaymentId(1);
$orderPayment->setOrderId($orderId);
$orderPayment->setAmount(55.55);
$orderPayment->setAction('authorization');
$orderPayment->setStatus('Voided');
$orderPayment->setDate("2012-04-13 12:13:15");
$orderPayment->save();
$orderPayment->setPaymentId(2);
$orderPayment->setAction('capture');
$orderPayment->setAmount(11.11);
$orderPayment->setRefundedAmount(1.23);
$orderPayment->setStatus('Completed');
$orderPayment->save();
$orderPayment->setPaymentId(3);
$orderPayment->setAction('capture');
$orderPayment->setAmount(0.11);
$orderPayment->setStatus('Completed');
$orderPayment->save();
$orderPayment->setPaymentId(4);
$orderPayment->setAction('capture');
$orderPayment->setAmount(22.22);
$orderPayment->setStatus('Pending');
$orderPayment->save();
$orderPayment->setPaymentId(5);
$orderPayment->setAction('refund');
$orderPayment->setAmount(5.55);
$orderPayment->setStatus('Refunded');
$orderPayment->save();
$orderPayment->setPaymentId(6);
$orderPayment->setAction('refund');
$orderPayment->setAmount(15.55);
$orderPayment->setStatus('Instant');
$orderPayment->save();
$orderPayment->setPaymentId(7);
$orderPayment->setAction('void');
$orderPayment->setAmount(15.55);
$orderPayment->setStatus('Instant');
$orderPayment->save();
$orderPayment->setPaymentId(8);
$orderPayment->setAction('refund');
$orderPayment->setAmount(1.23);
$orderPayment->setStatus('Refunded');
$orderPayment->save();
$orderPaymentList = oxNew(\OxidEsales\PayPalModule\Model\OrderPaymentList::class);
$orderPaymentList->load($orderId);
return $orderPaymentList;
}
/**
* Test helper, prepares some paypal order payments.
* Voided amount comes from void action.
*
* @return \OxidEsales\PayPalModule\Model\OrderPaymentList
*/
private function createOrderPaymentListContainingVoidAction()
{
$orderId = '123';
$orderPayment = oxNew(\OxidEsales\PayPalModule\Model\OrderPayment::class);
$orderPayment->setPaymentId(1);
$orderPayment->setOrderId($orderId);
$orderPayment->setAmount(50.00);
$orderPayment->setAction('authorization');
$orderPayment->setStatus('Voided');
$orderPayment->setDate("2012-04-13 12:13:15");
$orderPayment->save();
$orderPayment->setPaymentId(2);
$orderPayment->setAction('capture');
$orderPayment->setAmount(30.00);
$orderPayment->setRefundedAmount(20.00);
$orderPayment->setStatus('Completed');
$orderPayment->save();
$orderPayment->setPaymentId(3);
$orderPayment->setAction('refund');
$orderPayment->setAmount(10.00);
$orderPayment->setStatus('Refunded');
$orderPayment->save();
$orderPayment->setPaymentId(4);
$orderPayment->setAction('void');
$orderPayment->setAmount(11.00);
$orderPayment->setStatus('Voided');
$orderPayment->save();
$orderPaymentList = oxNew(\OxidEsales\PayPalModule\Model\OrderPaymentList::class);
$orderPaymentList->load($orderId);
return $orderPaymentList;
}
}

View File

@@ -0,0 +1,157 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing oxAccessRightException class.
*/
class OrderPaymentListTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Setup: Prepare data - create need tables
*/
protected function setUp(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpayments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_order`');
}
/**
* Test case for \OxidEsales\PayPalModule\Model\OrderPayment::oePayPalOrderPaymentList()
* Gets PayPal Order Payment history list
*/
public function testLoadOrderPayments()
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setPaymentId(1);
$orderPayment->setOrderId("123");
$orderPayment->setAmount(50);
$orderPayment->setAction("OEPAYPAL_STATUS_COMPLETED");
$orderPayment->setDate("2012-04-13 12:13:15");
$orderPayment->save();
$orderPayment->setPaymentId(2);
$orderPayment->setDate("2012-02-01");
$orderPayment->save();
$orderPayment->setPaymentId(3);
$orderPayment->setDate("2012-01-15");
$orderPayment->save();
$orderPaymentList = new \OxidEsales\PayPalModule\Model\OrderPaymentList();
$orderPaymentList->load("123");
$this->assertEquals(3, count($orderPaymentList));
$i = 1;
foreach ($orderPaymentList as $orderPayment) {
$this->assertEquals($i++, $orderPayment->getPaymentId());
}
}
/**
* Test case for \OxidEsales\PayPalModule\Model\OrderPayment::hasFailedPayment()
* Checks if list has failed payments
*/
public function testHasFailedPayment()
{
$orderPaymentList = new \OxidEsales\PayPalModule\Model\OrderPaymentList();
$orderPaymentList->load("order");
$this->assertFalse($orderPaymentList->hasFailedPayment());
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId("order");
$orderPayment->setStatus("Completed");
$orderPayment->save();
$orderPaymentList->load("order");
$this->assertFalse($orderPaymentList->hasFailedPayment());
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId("order");
$orderPayment->setStatus("Failed");
$orderPayment->save();
$orderPaymentList->load("order");
$this->assertTrue($orderPaymentList->hasFailedPayment());
}
/**
* Test case for \OxidEsales\PayPalModule\Model\OrderPayment::hasPendingPayment()
* Checks if list has pending payments
*/
public function testHasPendingPayment()
{
$orderPaymentList = new \OxidEsales\PayPalModule\Model\OrderPaymentList();
$orderPaymentList->load("order");
$this->assertFalse($orderPaymentList->hasPendingPayment());
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId("order");
$orderPayment->setStatus("Completed");
$orderPayment->save();
$orderPaymentList->load("order");
$this->assertFalse($orderPaymentList->hasPendingPayment());
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId("order");
$orderPayment->setStatus("Pending");
$orderPayment->save();
$orderPaymentList->load("order");
$this->assertTrue($orderPaymentList->hasPendingPayment());
}
/**
* Test case for \OxidEsales\PayPalModule\Model\OrderPayment::hasPendingPayment()
* Checks if list has pending payments
*/
public function testAddPayment()
{
$orderPaymentList = new \OxidEsales\PayPalModule\Model\OrderPaymentList();
$orderPaymentList->load("order");
$this->assertEquals(0, count($orderPaymentList));
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId("order");
$orderPayment->save();
$orderPaymentList = new \OxidEsales\PayPalModule\Model\OrderPaymentList();
$orderPaymentList->load("order");
$this->assertEquals(1, count($orderPaymentList));
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setDate('2013-01-12');
$orderPayment->setAction('Pending');
$orderPaymentList->addPayment($orderPayment);
$orderPaymentList = new \OxidEsales\PayPalModule\Model\OrderPaymentList();
$orderPaymentList->load("order");
$this->assertEquals(2, count($orderPaymentList));
}
}

View File

@@ -0,0 +1,447 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing oePayPalOxState class.
*/
class OrderPaymentStatusCalculatorTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Setup: Prepare data - create need tables
*/
protected function setUp(): void
{
\OxidEsales\PayPalModule\Core\Events::addOrderPaymentsTable();
\OxidEsales\PayPalModule\Core\Events::addOrderTable();
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE TABLE `oepaypal_order`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE TABLE `oepaypal_orderpayments`');
}
/**
* Provides with valid and not valid order payments to be set.
*/
public function providerPayment()
{
$orderPaymentValid = $this->getValidOrderPayment();
$orderPaymentNotValid = $this->getNotValidOrderPayment();
return array(
array(null),
array($orderPaymentValid),
array($orderPaymentNotValid),
);
}
/**
* Provides with valid and not valid order payments to be set.
*/
public function providerPayment_paymentPending()
{
$orderPaymentValid = $this->getValidOrderPayment();
$orderPaymentNotValid = $this->getNotValidOrderPayment();
return array(
// Order state calculation do not change if there is no virtual payment.
array(null, 'pending'),
// Valid virtual payment do not affect order state.
array($orderPaymentValid, 'pending'),
// Order failed if virtual payment failed.
array($orderPaymentNotValid, 'failed'),
);
}
/**
* Provides with valid and not valid order payments to be set.
*/
public function providerPayment_paymentCompleted()
{
$orderPaymentValid = $this->getValidOrderPayment();
$orderPaymentNotValid = $this->getNotValidOrderPayment();
return array(
// Order state calculation do not change if there is no virtual payment.
array(null, 'completed'),
// Valid virtual payment do not affect order state.
array($orderPaymentValid, 'completed'),
// Order failed if virtual payment failed.
array($orderPaymentNotValid, 'failed'),
);
}
/**
* Data provider for testGetSuggestStatus_onVoidNoCapture()
* Provides with valid and not valid order payments to be set.
*/
public function providerPayment_paymentCanceled()
{
$orderPaymentValid = $this->getValidOrderPayment();
$orderPaymentNotValid = $this->getNotValidOrderPayment();
return array(
// Order state calculation do not change if there is no virtual payment.
array(null, 'canceled'),
// Valid virtual payment do not affect order state.
array($orderPaymentValid, 'canceled'),
// Order failed if virtual payment failed.
array($orderPaymentNotValid, 'failed'),
);
}
/**
* Provides with valid and not valid order payments to be set.
*/
public function providerPayment_paymentRefund()
{
$orderPaymentValid = $this->getValidOrderPayment();
$orderPaymentNotValid = $this->getNotValidOrderPayment();
return array(
// Order state calculation do not change if there is no virtual payment.
array(null, 'refund_partial'),
// Valid virtual payment do not affect order state.
array($orderPaymentValid, 'refund_partial'),
// Order failed if virtual payment failed.
array($orderPaymentNotValid, 'failed'),
);
}
/**
* Testing setting order
*/
public function testSetGetOrder()
{
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrder('order');
$this->assertEquals('order', $manager->getOrder());
}
/**
* Testing setting order payment
*
*/
public function testSetGetOrderPayment()
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setTransactionId('asdadsd45a4sd5a4sd54a5');
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrderPayment($orderPayment);
$this->assertEquals($orderPayment, $manager->getOrderPayment(), 'Order Payment is not same as set.');
}
/**
* Testing setting payment list
*
* @dataProvider providerPayment_paymentRefund
*/
public function testGetSuggestStatus_orderNotSet($orderPaymentVirtual, $orderStatus)
{
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrderPayment($orderPaymentVirtual);
$this->assertNull($manager->getSuggestStatus($orderStatus));
}
/**
* Testing setting payment list
*
* @dataProvider providerPayment
*/
public function testGetStatus_orderNotSet_orderStatusNull($orderPayment)
{
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrderPayment($orderPayment);
$this->assertNull($manager->getStatus());
}
/**
* Testing status if can not be changes automatically from failed
*
* @dataProvider providerPayment
*/
public function testGetStatus_OrderStateFailed($orderPaymentVirtual)
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId('order');
$orderPayment->setStatus('Pending');
$orderPayment->save();
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('order');
$order->setPaymentStatus('failed');
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrder($order);
$manager->setOrderPayment($orderPaymentVirtual);
$this->assertEquals('failed', $manager->getStatus());
}
/**
* Testing status if can not be changes automatically from canceled.
*
* @dataProvider providerPayment
*/
public function testGetStatus_OrderStateCanceled($orderPaymentVirtual)
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId('order');
$orderPayment->setStatus('Failed');
$orderPayment->save();
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('order');
$order->setPaymentStatus('canceled');
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrder($order);
$manager->setOrderPayment($orderPaymentVirtual);
$this->assertEquals('canceled', $manager->getStatus());
}
/**
* Testing status IPN and order creation - status failed
*
* @dataProvider providerPayment
*/
public function testGetStatus_paymentFailed_orderFailed($orderPaymentVirtual)
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId('order');
$orderPayment->setStatus('Failed');
$orderPayment->save();
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('order');
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrder($order);
$manager->setOrderPayment($orderPaymentVirtual);
$this->assertEquals('failed', $manager->getStatus());
}
/**
* Testing status IPN and order creation - status pending
*
* @dataProvider providerPayment_paymentPending
*/
public function testGetStatus_paymentPending($orderPaymentVirtual, $orderStatus)
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId('order');
$orderPayment->setStatus('Pending');
$orderPayment->save();
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('order');
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrder($order);
$manager->setOrderPayment($orderPaymentVirtual);
$this->assertEquals($orderStatus, $manager->getStatus());
}
/**
* Testing status IPN and order creation - status completed
*
* @dataProvider providerPayment_paymentCompleted
*/
public function testGetStatus_paymentCompleted($orderPaymentVirtual, $orderStatus)
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId('order');
$orderPayment->setStatus('Completed');
$orderPayment->save();
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId('order');
$orderPayment->setStatus('Refunded');
$orderPayment->save();
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId('order');
$orderPayment->setStatus('Voided');
$orderPayment->save();
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('order');
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrder($order);
$manager->setOrderPayment($orderPaymentVirtual);
$this->assertEquals($orderStatus, $manager->getStatus());
}
/**
* Testing suggest status on void with no captured money
*
* @dataProvider providerPayment_paymentCanceled
*/
public function testGetSuggestStatus_onVoidNoCapture($orderPaymentVirtual, $orderStatus)
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('order');
$order->setCapturedAmount(0);
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrder($order);
$manager->setOrderPayment($orderPaymentVirtual);
$this->assertEquals($orderStatus, $manager->getSuggestStatus('void'));
}
/**
* Testing suggest status on void with some captured money
*
* @dataProvider providerPayment_paymentCompleted
*/
public function testGetSuggestStatus_onVoidSomeCapture($orderPaymentVirtual, $orderStatus)
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('order');
$order->setCapturedAmount(10);
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrder($order);
$manager->setOrderPayment($orderPaymentVirtual);
$this->assertEquals($orderStatus, $manager->getSuggestStatus('void'));
}
/**
* Testing suggest status on partial refund
*
* @dataProvider providerPayment_paymentPending
*/
public function testGetSuggestStatus_onRefundPartial($orderPaymentVirtual, $orderStatus)
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('order');
$order->setPaymentStatus('pending');
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrder($order);
$manager->setOrderPayment($orderPaymentVirtual);
$this->assertEquals($orderStatus, $manager->getSuggestStatus('refund_partial'));
}
/**
* Testing suggest status on refund
*
* @dataProvider providerPayment_paymentCompleted
*/
public function testGetSuggestStatus_onRefund($orderPaymentVirtual, $orderStatus)
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('order');
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrder($order);
$manager->setOrderPayment($orderPaymentVirtual);
$this->assertEquals($orderStatus, $manager->getSuggestStatus('refund'));
}
/**
* Testing suggest status on capture
*
* @dataProvider providerPayment_paymentCompleted
*/
public function testGetSuggestStatus_onCapture($orderPaymentVirtual, $orderStatus)
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('order');
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrder($order);
$manager->setOrderPayment($orderPaymentVirtual);
$this->assertEquals($orderStatus, $manager->getSuggestStatus('capture'));
}
/**
* Testing suggest status on partial capture
*
* @dataProvider providerPayment_paymentCompleted
*/
public function testGetSuggestStatus_onCapturePartial($orderPaymentVirtual, $orderStatus)
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('order');
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrder($order);
$manager->setOrderPayment($orderPaymentVirtual);
$this->assertEquals($orderStatus, $manager->getSuggestStatus('capture_partial'));
}
/**
* Testing suggest status on partial capture
*/
public function testGetSuggestStatus_onReauthorize()
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('order');
$order->setPaymentStatus('pending');
$manager = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusCalculator();
$manager->setOrder($order);
$this->assertEquals('pending', $manager->getSuggestStatus('reauthorize'));
}
/**
* Prepare OrderPayment object.
*
* @return \OxidEsales\PayPalModule\Model\OrderPayment
*/
protected function getOrderPayment()
{
\OxidEsales\PayPalModule\Core\Events::addOrderPaymentsTable();
\OxidEsales\PayPalModule\Core\Events::addOrderTable();
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setTransactionId('asdadsd45a4sd5a4sd54a5');
$orderPayment->setOrderId('order');
return $orderPayment;
}
/**
* Prepare valid OrderPayment object.
*
* @return \OxidEsales\PayPalModule\Model\OrderPayment
*/
protected function getValidOrderPayment()
{
$orderPayment = $this->getOrderPayment();
return $orderPayment;
}
/**
* Prepare not valid OrderPayment object.
*
* @return \OxidEsales\PayPalModule\Model\OrderPayment
*/
protected function getNotValidOrderPayment()
{
$orderPayment = $this->getOrderPayment();
$orderPayment->setIsValid(false);
return $orderPayment;
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing oxAccessRightException class.
*/
class OrderPaymentStatusListTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Data provider for testIsActionValidCapture()
*
* @return array
*/
public function availableStatusesTest_dataProvider()
{
return array(
array('capture', array('completed')),
array('capture_partial', array('completed', 'pending')),
array('refund', array('completed', 'pending', 'canceled')),
array('refund_partial', array('completed', 'pending', 'canceled')),
array('void', array('completed', 'pending', 'canceled')),
array('test', array()),
);
}
/**
* Testing adding amount to PayPal refunded amount
*
* @dataProvider availableStatusesTest_dataProvider
*/
public function testGetAvailableStatuses($action, $statusList)
{
$statusListProvider = new \OxidEsales\PayPalModule\Model\OrderPaymentStatusList();
$this->assertEquals($statusList, $statusListProvider->getAvailableStatuses($action));
}
}

View File

@@ -0,0 +1,194 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing oxAccessRightException class.
*/
class OrderPaymentTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Setup: Prepare data - create need tables
*/
protected function setUp(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpaymentcomments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpayments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_order`');
}
/**
* Test case for adding / getting PayPal Order Payment history item
*/
public function testCreatePayPalOrderPayment()
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId('123');
$orderPayment->setTransactionId('transactionId');
$orderPayment->setCorrelationId('correlationId');
$orderPayment->setAmount(50);
$orderPayment->setRefundedAmount(12.13);
$orderPayment->setAction('capture');
$orderPayment->setDate('2012-04-13 15:16:32');
$orderPayment->setStatus('status');
$orderPayment->setCurrency('LTL');
$orderPayment->save();
$orderPaymentLoaded = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPaymentLoaded->load($orderPayment->getPaymentId());
$this->assertEquals('123', $orderPaymentLoaded->getOrderId());
$this->assertEquals('transactionId', $orderPaymentLoaded->getTransactionId());
$this->assertEquals('correlationId', $orderPaymentLoaded->getCorrelationId());
$this->assertEquals(50, $orderPaymentLoaded->getAmount());
$this->assertEquals(12.13, $orderPaymentLoaded->getRefundedAmount());
$this->assertEquals('capture', $orderPaymentLoaded->getAction());
$this->assertEquals('2012-04-13 15:16:32', $orderPaymentLoaded->getDate());
$this->assertEquals('status', $orderPaymentLoaded->getStatus());
$this->assertEquals('LTL', $orderPaymentLoaded->getCurrency());
}
/**
* Testing adding amount to PayPal refunded amount
*/
public function testAddRefundedAmount_WhenEmpty()
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->addRefundedAmount(100);
$this->assertEquals(100, $orderPayment->getRefundedAmount());
}
/**
* Testing adding amount to PayPal refunded amount
*/
public function testAddRefundedAmount_NotEmpty()
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setRefundedAmount(100);
$orderPayment->addRefundedAmount(100);
$this->assertEquals(200, $orderPayment->getRefundedAmount());
}
/**
* Testing loading payment by transaction id
*/
public function testLoadByTransactionId()
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId('orderId');
$orderPayment->setTransactionId('transactionId');
$orderPayment->save();
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->loadByTransactionId('transactionId');
$this->assertEquals('orderId', $orderPayment->getOrderId());
}
/**
* Data provider for test testSetGetIsValid.
*/
public function providerSetGetIsValid()
{
return array(
array(true),
array(false),
);
}
/**
* Test case for \OxidEsales\PayPalModule\Model\OrderPayment::setIsValid
* Test case for \OxidEsales\PayPalModule\Model\OrderPayment::getIsValid
*
* @param bool $isValid
*
* @dataProvider providerSetGetIsValid
*/
public function testSetGetIsValid($isValid)
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setIsValid($isValid);
$this->assertEquals($isValid, $orderPayment->getIsValid(), 'Should be same value from getter as set in setter.');
}
/**
* Data provider for test testSetGetValidationMessage.
*/
public function providerSetGetValidationMessage()
{
return array(
array(''),
array('zzzzz'),
array('yyyyy'),
);
}
/**
* Test case add comment to payment
*/
public function testAddComment_setParams_CheckInDb()
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId('123');
$orderPayment->save();
$this->assertEquals(0, count($orderPayment->getCommentList()), 'No comments - default value empty array.');
$comment = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$comment->setComment('comment');
$orderPayment->addComment($comment);
$this->assertEquals(1, count($orderPayment->getCommentList()));
}
/**
* Test case add comment to payment
*/
public function testAddComment_NoDateGiven()
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$orderPayment->setOrderId('123');
$orderPayment->save();
$this->assertEquals(0, count($orderPayment->getCommentList()), 'No comments - default value empty array.');
$comment = new \OxidEsales\PayPalModule\Model\OrderPaymentComment();
$comment->setComment('comment');
$orderPayment->addComment($comment);
$this->assertEquals(1, count($orderPayment->getCommentList()));
}
/**
* Test case add comment to payment
*/
public function testGetCommentList_noComments_instanceOfCommentList()
{
$orderPayment = new \OxidEsales\PayPalModule\Model\OrderPayment();
$this->assertTrue(
$orderPayment->getCommentList() instanceof \OxidEsales\PayPalModule\Model\OrderPaymentCommentList,
'No comments - default value empty array.');
}
}

View File

@@ -0,0 +1,270 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
use OxidEsales\Eshop\Application\Model\Order;
/**
* Testing oxAccessRightException class.
*/
class OrderTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Tear down the fixture.
*/
protected function tearDown(): void
{
$delete = 'TRUNCATE TABLE `oxorder`';
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($delete);
$this->getSession()->setVariable('sess_challenge', null);
}
/**
* Test case for \OxidEsales\PayPalModule\Model\Order::loadPayPalOrder()
*/
public function testLoadPayPalOrder()
{
// creating order
$order = oxNew(Order::class);
$order->setId('_testOrderId');
$order->save();
// checking load from session
$this->getSession()->setVariable('sess_challenge', '_testOrderId');
$order = new \OxidEsales\PayPalModule\Model\Order();
$order->loadPayPalOrder();
$this->assertEquals('_testOrderId', $order->oxorder__oxid->value);
// checking order creation if not exist in session order id
$this->getSession()->setVariable('sess_challenge', null);
$order = new \OxidEsales\PayPalModule\Model\Order();
$order->loadPayPalOrder();
$this->assertTrue((bool) $order->oxorder__oxid->value);
}
public function dataProviderFinalizePayPalOrder()
{
return [
'sale' => [
'Sale',
'OK',
date('Y-m-d'),
[
'PAYMENTINFO_0_TRANSACTIONID' => '_testTransactionId',
'PAYMENTINFO_0_PAYMENTSTATUS' => 'Completed',
]
],
'authorize' => [
'Authorization',
'NOT_FINISHED',
'0000-00-00',
[
'PAYMENTINFO_0_TRANSACTIONID' => '_testTransactionId',
'PAYMENTINFO_0_PAYMENTSTATUS' => 'Pending',
]
]
];
}
/**
* Test case for \OxidEsales\PayPalModule\Model\Order::finalizePayPalOrder()
*
* @dataProvider dataProviderFinalizePayPalOrder()
*
* @param string $transactionMode
* @param string $expectedStatus
* @param string $expectedPaid
*/
public function testFinalizePayPalOrder($transactionMode, $expectedStatus, $expectedPaid, $result)
{
// creating order
$order = new \OxidEsales\Eshop\Application\Model\Order();
$order->setId('_testOrderId');
$order->oxorder__oxtransstatus = new \OxidEsales\Eshop\Core\Field('NOT_FINISHED');
$order->save();
/** @var \OxidEsales\Eshop\Application\Model\Basket $basket */
$basket = oxNew(\OxidEsales\Eshop\Application\Model\Basket::class);
$this->getSession()->setVariable('sess_challenge', '_testOrderId');
$order = new \OxidEsales\PayPalModule\Model\Order();
$order->loadPayPalOrder();
$details = new \OxidEsales\PayPalModule\Model\Response\ResponseDoExpressCheckoutPayment();
$details->setData($result);
$order->finalizePayPalOrder($details, $basket, $transactionMode);
$this->assertEquals($expectedStatus, $order->oxorder__oxtransstatus->value);
$this->assertEquals('_testTransactionId', $order->oxorder__oxtransid->value);
$this->assertEquals($expectedPaid, substr($order->oxorder__oxpaid->value, 0, 10));
}
/**
* Test case for \OxidEsales\PayPalModule\Model\Order::finalizePayPalOrder() - when processing order with other payment method
* (not PayPal), order status should not be changed.
*/
public function testFinalizeOrder_notPayPalPayment()
{
$testOrder = oxNew(\OxidEsales\Eshop\Application\Model\Order::class);
$testOrder->setId('_testOrderId');
$testOrder->oxorder__oxtransstatus = new \OxidEsales\Eshop\Core\Field("OK");
$testOrder->save();
$this->getSession()->setVariable('sess_challenge', '_testOrderId');
/** @var \OxidEsales\Eshop\Application\Model\Basket $basket */
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Basket::class);
$mockBuilder->setMethods(['getPaymentId']);
$basket = $mockBuilder->getMock();
$basket->expects($this->any())->method('getPaymentId')->will($this->returnValue("anotherPayment"));
/** @var \OxidEsales\Eshop\Application\Model\User $user */
$user = oxNew(\OxidEsales\Eshop\Application\Model\User::class);
/** @var \OxidEsales\Eshop\Application\Model\Order $order */
$order = oxNew(\OxidEsales\Eshop\Application\Model\Order::class);
$order->setId('_testOrderId');
$order->finalizeOrder($basket, $user);
$updatedOrder = new \OxidEsales\Eshop\Application\Model\Order();
$updatedOrder->load('_testOrderId');
$this->assertEquals("OK", $updatedOrder->oxorder__oxtransstatus->value);
}
/**
* Test case for \OxidEsales\PayPalModule\Model\Order::deletePayPalOrder()
*/
public function testDeletePayPalOrder()
{
$testOrder = new \OxidEsales\Eshop\Application\Model\Order();
$testOrder->setId('_testOrderId');
$testOrder->save();
$this->getSession()->setVariable('sess_challenge', '_testOrderId');
$order = new \OxidEsales\PayPalModule\Model\Order();
$order->deletePayPalOrder();
$updatedOrder = new \OxidEsales\Eshop\Application\Model\Order();
$this->assertFalse($updatedOrder->load('_testOrderId'));
}
/**
* Tests getAuthorizationId
*/
public function testGetAuthorizationId()
{
$testOrder = new \OxidEsales\PayPalModule\Model\Order();
$testOrder->oxorder__oxtransid = new \OxidEsales\Eshop\Core\Field('testAuthorizationId');
$this->assertEquals('testAuthorizationId', $testOrder->getAuthorizationId());
}
/**
*
*/
public function testValidateDelivery_EmptyPaymentValid_PaymentValid()
{
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Application\Model\PaymentList::class, null);
$basket = $this->createPartialMock(\OxidEsales\PayPalModule\Model\Basket::class, ['getPaymentId', 'getShippingId']);
$basket->method('getPaymentId')->willReturn('oxidpaypal');
$basket->method('getShippingId')->willReturn('oxidstandard');
$emptyPayment = oxNew(\OxidEsales\Eshop\Application\Model\Payment::class);
$emptyPayment->load('oxempty');
$emptyPayment->oxpayments__oxactive = new \OxidEsales\Eshop\Core\Field(1);
$emptyPayment->save();
$deliverySetList = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\DeliverySetList::class)
->setMethods(['getDeliverySetList'])
->getMock();
$deliverySetList->expects($this->once())->method('getDeliverySetList')->willReturn([]);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Application\Model\DeliverySetList::class, $deliverySetList);
/** @var \OxidEsales\PayPalModule\Model\User $user */
$user = oxNew(\OxidEsales\PayPalModule\Model\User::class);
$order = oxNew(\OxidEsales\PayPalModule\Model\Order::class);
$order->setUser($user);
$this->assertNull($order->validateDelivery($basket));
}
/**
* Asserts that order is updated
*
*/
public function testUpdateOrderNumber()
{
$order = oxNew(\OxidEsales\PayPalModule\Model\Order::class);
$order->oxorder__oxid = new \OxidEsales\Eshop\Core\Field('_test_order');
$order->save();
$this->assertTrue($order->oePayPalUpdateOrderNumber());
}
/**
* Asserts that number is set next than existing one
*/
public function testUpdateOrderNumber_OrderNumberNotSet()
{
$counterIdent = 'orderTestCounter';
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Order::class);
$mockBuilder->setMethods(['_getCounterIdent']);
$order = $mockBuilder->getMock();
$order->expects($this->any())->method('_getCounterIdent')->will($this->returnValue($counterIdent));
$order->oxorder__oxid = new \OxidEsales\Eshop\Core\Field('_test_order');
$order->save();
$counter = oxNew(\OxidEsales\Eshop\Core\Counter::class);
$orderNumber = $counter->getNext($counterIdent);
$order->oePayPalUpdateOrderNumber();
$this->assertEquals($orderNumber + 1, $order->oxorder__oxordernr->value);
}
/**
*
*/
public function testUpdateOrderNumber_OrderNumberSet()
{
$counterIdent = 'orderTestCounter';
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Order::class);
$mockBuilder->setMethods(['_getCounterIdent']);
$order = $mockBuilder->getMock();
$order->expects($this->any())->method('_getCounterIdent')->will($this->returnValue($counterIdent));
$counter = oxNew(\OxidEsales\Eshop\Core\Counter::class);
$counter->getNext($counterIdent);
$order->oxorder__oxordernr = new \OxidEsales\Eshop\Core\Field(5);
$order->oePayPalUpdateOrderNumber();
$this->assertEquals(5, $order->oxorder__oxordernr->value);
}
}

View File

@@ -0,0 +1,130 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
use OxidEsales\Eshop\Application\Model\Basket;
/**
* Testing oePayPalBasketValidator class.
*/
class OutOfStockValidatorTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function providerSetGetBasket()
{
$oxBasket = oxNew(Basket::class);
return array(
array($oxBasket),
array(null)
);
}
/**
* @param $basket
*
* @dataProvider providerSetGetBasket
*/
public function testSetGetBasket($basket)
{
$basketValidator = new \OxidEsales\PayPalModule\Model\OutOfStockValidator();
$basketValidator->setBasket($basket);
$this->assertEquals($basket, $basketValidator->getBasket());
}
/**
*/
public function testSetGetEmptyStockLevel()
{
$basketValidator = new \OxidEsales\PayPalModule\Model\OutOfStockValidator();
$basketValidator->setEmptyStockLevel(10);
$this->assertEquals(10, $basketValidator->getEmptyStockLevel());
}
/**
* Data provider for testHasOutOfStockItems
*/
public function providerHasOutOfStockItems()
{
return array(
// Basket Article ID, Basket item amount, Stock Amount, Stock empty level, expected result
array('ProductId5', 5, 5, 0, false),
array('ProductId5', 5, 5, 1, true),
array('ProductId5', 6, 5, 0, true),
array('ProductId3', 2, 3, 2, true),
array('ProductId2', 2, 2, 1, true),
array('ProductId1', 2, 2, 0, false),
);
}
/**
* @dataProvider providerHasOutOfStockItems
*/
public function testHasOutOfStockArticles($productId, $basketItemAmount, $stockAmount, $stockEmptyLevel, $expectedResult)
{
$basket = $this->createBasket($productId, $basketItemAmount, $stockAmount);
$basketValidator = new \OxidEsales\PayPalModule\Model\OutOfStockValidator();
$basketValidator->setBasket($basket);
$basketValidator->setEmptyStockLevel($stockEmptyLevel);
$this->assertEquals($expectedResult, $basketValidator->hasOutOfStockArticles());
}
/**
* Function creates mocked basket
*
* @param $productId
* @param $basketAmount
* @param $stockAmount
*
* @return PHPUnit_Framework_MockObject_MockObject
*/
protected function createBasket($productId, $basketAmount, $stockAmount)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Article::class);
$mockBuilder->setMethods(['getStockAmount']);
$article = $mockBuilder->getMock();
$article->expects($this->any())->method('getStockAmount')->will($this->returnValue($stockAmount));
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\BasketItem::class);
$mockBuilder->setMethods(['getProductId', 'getAmount', 'getArticle']);
$basketItem = $mockBuilder->getMock();
$basketItem->expects($this->any())->method('getProductId')->will($this->returnValue($productId));
$basketItem->expects($this->any())->method('getAmount')->will($this->returnValue($basketAmount));
$basketItem->expects($this->any())->method('getArticle')->will($this->returnValue($article));
$basketItemsList = array(
$productId => $basketItem
);
$mockBuilder = $this->getMockBuilder(Basket::class);
$mockBuilder->setMethods(['getContents']);
$basket = $mockBuilder->getMock();
$basket->expects($this->any())->method('getContents')->will($this->returnValue($basketItemsList));
return $basket;
}
}

View File

@@ -0,0 +1,151 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
/**
* Testing oxAccessRightException class.
*/
class PayPalOrderTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Setup: Prepare data - create need tables
*/
protected function setUp(): void
{
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_orderpayments`');
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute('TRUNCATE `oepaypal_order`');
parent::setUp();
}
/**
* Test case for \OxidEsales\PayPalModule\Model\PayPalOrder::getOrderId()
* Tests adding / getting PayPal Order Payment history item
*/
public function testSetGet()
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('123');
$this->assertEquals('123', $order->getOrderId());
}
/**
* Test case for \OxidEsales\PayPalModule\Model\PayPalOrder::save()
* Tests adding / getting PayPal Order Payment history item
*/
public function testSavePayPalPayPalOrder_insert()
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('123');
$order->setPaymentStatus('pending');
$order->setCapturedAmount(24.13);
$order->setRefundedAmount(12.13);
$order->setVoidedAmount(15.13);
$order->setTotalOrderSum(299.99);
$order->setCurrency('LTU');
$order->setTransactionMode('Sale');
$order->save();
$orderLoaded = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$orderLoaded->load($order->getOrderId());
$this->assertEquals('123', $orderLoaded->getOrderId());
$this->assertEquals('pending', $orderLoaded->getPaymentStatus());
$this->assertEquals(24.13, $orderLoaded->getCapturedAmount());
$this->assertEquals(12.13, $orderLoaded->getRefundedAmount());
$this->assertEquals(15.13, $orderLoaded->getVoidedAmount());
$this->assertEquals(299.99, $orderLoaded->getTotalOrderSum());
$this->assertEquals('LTU', $orderLoaded->getCurrency());
$this->assertEquals('Sale', $orderLoaded->getTransactionMode());
}
/**
* Test case for \OxidEsales\PayPalModule\Model\PayPalOrder::save()
* Tests adding / getting PayPal Order Payment history item
*/
public function testSavePayPalPayPalOrder_update()
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->setOrderId('123');
$order->setPaymentStatus('pending');
$order->setCapturedAmount(24.13);
$order->setRefundedAmount(12.13);
$order->setVoidedAmount(15.13);
$order->setTotalOrderSum(299.99);
$order->setCurrency('LTU');
$order->setTransactionMode('Sale');
$order->save();
$orderLoaded = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$orderLoaded->load('123');
$orderLoaded->setPaymentStatus('completed');
$orderLoaded->save();
$orderLoaded = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$orderLoaded->load('123');
$this->assertEquals('completed', $orderLoaded->getPaymentStatus());
$this->assertEquals(24.13, $orderLoaded->getCapturedAmount());
$this->assertEquals(12.13, $orderLoaded->getRefundedAmount());
$this->assertEquals(15.13, $orderLoaded->getVoidedAmount());
$this->assertEquals(299.99, $orderLoaded->getTotalOrderSum());
$this->assertEquals('LTU', $orderLoaded->getCurrency());
$this->assertEquals('Sale', $orderLoaded->getTransactionMode());
}
/**
* Test case for \OxidEsales\PayPalModule\Model\PayPalOrder::addRefundedAmount()
* Tests adding amount to PayPal refunded amount
*/
public function testAddRefundedAmountWhenEmpty()
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->addRefundedAmount(100.29);
$order->addRefundedAmount(899.70);
$this->assertEquals(999.99, $order->getRefundedAmount());
}
/**
* Test case for \OxidEsales\PayPalModule\Model\PayPalOrder::addCapturedAmount()
* Tests adding amount to PayPal refunded amount
*/
public function testAddCapturedAmountWhenEmpty()
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$order->addCapturedAmount(100.29);
$order->addCapturedAmount(899.70);
$this->assertEquals(999.99, $order->getCapturedAmount());
}
/**
* Test case for \OxidEsales\PayPalModule\Model\PayPalOrder::getPaymentStatus()
* Tests PayPal payment status getter
*/
public function testGetPayPalPaymentStatusWhenStatusEmpty()
{
$order = new \OxidEsales\PayPalModule\Model\PayPalOrder();
$this->assertEquals("completed", $order->getPaymentStatus());
}
}

View File

@@ -0,0 +1,189 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\PayPalRequest;
use OxidEsales\Eshop\Application\Model\Basket;
use OxidEsales\Eshop\Application\Model\User;
use OxidEsales\Eshop\Core\Registry as EshopRegistry;
/**
* Testing \OxidEsales\PayPalModule\Model\PayPalRequest\DoExpressCheckoutPaymentRequestBuilder class.
*/
class DoExpressCheckoutPaymentRequestBuilderTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function providerDoExpressCheckoutPayment()
{
$facts = new \OxidEsales\Facts\Facts();
$buttonSource = 'O3SHOP_Cart_CommunityECS';
$data = [
'standard_checkout' => [\OxidEsales\PayPalModule\Core\Config::OEPAYPAL_ECS, $buttonSource],
'shortcut' => [\OxidEsales\PayPalModule\Core\Config::OEPAYPAL_SHORTCUT, 'O3SHOP_Cart_ECS_Shortcut']
];
return $data;
}
/**
* Test case for \OxidEsales\PayPalModule\Model\PayPalRequest\DoExpressCheckoutPaymentRequestBuilder::buildRequest.
*
* @dataProvider providerDoExpressCheckoutPayment
*
* @param int $trigger Mark if payment triggered by shortcut or by standard checkout.
* @param string $buttonSource Expected partnercode/BUTTONSOURCE
*/
public function testDoExpressCheckoutPayment($trigger, $buttonSource)
{
EshopRegistry::getConfig()->setConfigParam('OEPayPalDisableIPN', false);
// preparing session, inputs etc.
$result["PAYMENTINFO_0_TRANSACTIONID"] = "321";
// preparing price
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Price::class);
$mockBuilder->setMethods(['getBruttoPrice']);
$price = $mockBuilder->getMock();
$price->expects($this->once())->method("getBruttoPrice")->will($this->returnValue(123));
// preparing basket
$mockBuilder = $this->getMockBuilder(Basket::class);
$mockBuilder->setMethods(['getPrice']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method("getPrice")->will($this->returnValue($price));
// preparing session
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Session::class);
$mockBuilder->setMethods(['getBasket']);
$session = $mockBuilder->getMock();
$session->expects($this->any())->method("getBasket")->will($this->returnValue($basket));
$session->setVariable("oepaypal-token", "111");
$session->setVariable("oepaypal-payerId", "222");
$session->setVariable(\OxidEsales\PayPalModule\Core\Config::OEPAYPAL_TRIGGER_NAME, $trigger);
// preparing config
$payPalConfig = new \OxidEsales\PayPalModule\Core\Config();
// preparing order
$payPalOrder = oxNew(\OxidEsales\Eshop\Application\Model\Order::class);
$payPalOrder->oxorder__oxordernr = new \OxidEsales\Eshop\Core\Field("123");
$user = oxNew(User::class);
$user->oxuser__oxfname = new \OxidEsales\Eshop\Core\Field('firstname');
$user->oxuser__oxlname = new \OxidEsales\Eshop\Core\Field('lastname');
$user->oxuser__oxstreet = new \OxidEsales\Eshop\Core\Field('some street');
$user->oxuser__oxstreetnr = new \OxidEsales\Eshop\Core\Field('47');
$user->oxuser__oxcity = new \OxidEsales\Eshop\Core\Field('some city');
$user->oxuser__oxzip = new \OxidEsales\Eshop\Core\Field('zip');
$subj = sprintf(\OxidEsales\Eshop\Core\Registry::getLang()->translateString("OEPAYPAL_ORDER_CONF_SUBJECT"), $payPalOrder->oxorder__oxordernr->value);
$config = $this->getConfig();
$expectedResult = array(
'TOKEN' => '111',
'PAYERID' => '222',
'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
'PAYMENTREQUEST_0_AMT' => '123.00',
'PAYMENTREQUEST_0_CURRENCYCODE' => "EUR",
'PAYMENTREQUEST_0_NOTIFYURL' => $this->getConfig()->getCurrentShopUrl() . "index.php?cl=oepaypalipnhandler&fnc=handleRequest&shp=" . $config->getShopId(),
'PAYMENTREQUEST_0_DESC' => $subj,
'PAYMENTREQUEST_0_CUSTOM' => $subj,
'PAYMENTREQUEST_0_SHIPTONAME' => 'firstname lastname',
'PAYMENTREQUEST_0_SHIPTOSTREET' => 'some street 47',
'PAYMENTREQUEST_0_SHIPTOCITY' => 'some city',
'PAYMENTREQUEST_0_SHIPTOZIP' => 'zip',
'PAYMENTREQUEST_0_SHIPTOPHONENUM' => null,
'PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE' => null,
);
$expectedResult['BUTTONSOURCE'] = $buttonSource;
// testing
$builder = new \OxidEsales\PayPalModule\Model\PayPalRequest\DoExpressCheckoutPaymentRequestBuilder();
$builder->setPayPalConfig($payPalConfig);
$builder->setSession($session);
$builder->setBasket($basket);
$builder->setOrder($payPalOrder);
$builder->setTransactionMode('Sale');
$builder->setUser($user);
$request = $builder->buildRequest();
$this->assertEquals($expectedResult, $request->getData());
}
public function testAddAddressParams_SelectedAddressIdNotSet_TakeInfoFromUser()
{
$expectedParams = array(
'PAYMENTREQUEST_0_SHIPTONAME' => 'FirstName LastName',
'PAYMENTREQUEST_0_SHIPTOSTREET' => 'Street StreetNr',
'PAYMENTREQUEST_0_SHIPTOCITY' => 'City',
'PAYMENTREQUEST_0_SHIPTOZIP' => 'Zip',
'PAYMENTREQUEST_0_SHIPTOPHONENUM' => 'PhoneNum',
'PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE' => null,
);
$userMethodValues = array(
'getSelectedAddressId' => null,
);
$user = $this->_createStub(\OxidEsales\Eshop\Application\Model\User::class, $userMethodValues);
$user->oxuser__oxusername = new \OxidEsales\Eshop\Core\Field('test@test.com');
$user->oxuser__oxfname = new \OxidEsales\Eshop\Core\Field('FirstName');
$user->oxuser__oxlname = new \OxidEsales\Eshop\Core\Field('LastName');
$user->oxuser__oxstreet = new \OxidEsales\Eshop\Core\Field('Street');
$user->oxuser__oxstreetnr = new \OxidEsales\Eshop\Core\Field('StreetNr');
$user->oxuser__oxcity = new \OxidEsales\Eshop\Core\Field('City');
$user->oxuser__oxzip = new \OxidEsales\Eshop\Core\Field('Zip');
$user->oxuser__oxfon = new \OxidEsales\Eshop\Core\Field('PhoneNum');
$user->oxuser__oxcity = new \OxidEsales\Eshop\Core\Field('City');
$builder = new \OxidEsales\PayPalModule\Model\PayPalRequest\DoExpressCheckoutPaymentRequestBuilder();
$builder->setUser($user);
$builder->addAddressParams();
$this->assertArraysEqual($expectedParams, $builder->getRequest()->getData());
}
/**
* Checks whether array length are equal and array keys and values are equal independent on keys position
*
* @param $expected
* @param $result
*/
protected function assertArraysEqual($expected, $result)
{
$this->assertArraysContains($expected, $result);
$this->assertEquals(count($expected), count($result));
}
/**
* Checks whether array array keys and values are equal independent on keys position
*
* @param $expected
* @param $result
*/
protected function assertArraysContains($expected, $result)
{
foreach ($expected as $key => $value) {
$this->assertArrayHasKey($key, $result, "Key not found: $key");
$this->assertEquals($value, $result[$key], "Key '$key' value is not equal to '$value'");
}
}
}

View File

@@ -0,0 +1,83 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\PayPalRequest;
/**
* Testing \OxidEsales\PayPalModule\Model\PayPalRequest\GetExpressCheckoutDetailsRequestBuilder class.
*/
class GetExpressCheckoutDetailsRequestBuilderTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Test building PayPal request object
*/
public function testBuildRequest()
{
$expectedParams = array(
'TOKEN' => '111',
);
$session = oxNew(\OxidEsales\Eshop\Core\Session::class);
$session->setVariable("oepaypal-token", "111");
$builder = $this->getPayPalRequestBuilder();
$builder->setSession($session);
$builder->buildRequest();
$this->assertArraysEqual($expectedParams, $builder->getPayPalRequest()->getData());
}
/**
*
*
* @return \OxidEsales\PayPalModule\Model\PayPalRequest\GetExpressCheckoutDetailsRequestBuilder
*/
protected function getPayPalRequestBuilder()
{
$builder = new \OxidEsales\PayPalModule\Model\PayPalRequest\GetExpressCheckoutDetailsRequestBuilder();
return $builder;
}
/**
* Checks whether array length are equal and array keys and values are equal independent on keys position
*
* @param $expected
* @param $result
*/
protected function assertArraysEqual($expected, $result)
{
$this->assertArraysContains($expected, $result);
$this->assertEquals(count($expected), count($result));
}
/**
* Checks whether array array keys and values are equal independent on keys position
*
* @param $expected
* @param $result
*/
protected function assertArraysContains($expected, $result)
{
foreach ($expected as $key => $value) {
$this->assertArrayHasKey($key, $result, "Key not found: $key");
$this->assertEquals($value, $result[$key], "Key '$key' value is not equal to '$value'");
}
}
}

View File

@@ -0,0 +1,107 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\PayPalRequest;
/**
* Testing \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequestBuilder class.
*/
class PayPalRequestBuilderTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function testSetGetRequest()
{
$data = array('DATA' => 'data');
$request = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest();
$request->setData($data);
$builder = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequestBuilder();
$builder->setRequest($request);
$this->assertEquals($request, $builder->getRequest());
}
public function testSetAuthorizationId()
{
$authorizationId = 'AuthorizationId';
$expected = array('AUTHORIZATIONID' => $authorizationId);
$builder = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequestBuilder();
$builder->setAuthorizationId($authorizationId);
$request = $builder->getRequest();
$this->assertEquals($expected, $request->getData());
}
public function testSetAmount()
{
$amount = 99.99;
$currency = 'EUR';
$expected = array(
'AMT' => $amount,
'CURRENCYCODE' => $currency
);
$builder = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequestBuilder();
$builder->setAmount($amount);
$request = $builder->getRequest();
$this->assertEquals($expected, $request->getData());
}
public function testSetCompleteType()
{
$completeType = 'Full';
$expected = array('COMPLETETYPE' => $completeType);
$builder = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequestBuilder();
$builder->setCompleteType($completeType);
$request = $builder->getRequest();
$this->assertEquals($expected, $request->getData());
}
public function testSetRefundType()
{
$refundType = 'Complete';
$expected = array('REFUNDTYPE' => $refundType);
$builder = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequestBuilder();
$builder->setRefundType($refundType);
$request = $builder->getRequest();
$this->assertEquals($expected, $request->getData());
}
public function testSetComment()
{
$comment = 'Comment';
$expected = array('NOTE' => $comment);
$builder = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequestBuilder();
$builder->setComment($comment);
$request = $builder->getRequest();
$this->assertEquals($expected, $request->getData());
}
}

View File

@@ -0,0 +1,68 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\PayPalRequest;
/**
* Testing \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest class.
*/
class PayPalRequestTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function testSetGetData()
{
$data = array(
'AUTHORIZATIONID' => 'AuthorizationId'
);
$request = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest();
$request->setData($data);
$this->assertEquals($data, $request->getData());
}
public function testGetData_NoDataSet()
{
$request = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest();
$this->assertEquals(array(), $request->getData());
}
public function testSetGetParameter()
{
$request = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest();
$request->setParameter('AUTHORIZATIONID', 'AuthorizationId');
$this->assertEquals('AuthorizationId', $request->getParameter('AUTHORIZATIONID'));
}
public function testSetGetParameter_OverwritingOfSetData()
{
$data = array(
'AUTHORIZATIONID' => 'AuthorizationId',
'TRANSACTIONID' => 'TransactionId',
);
$newId = 'NewAuthorizationId';
$request = new \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest();
$request->setData($data);
$request->setParameter('AUTHORIZATIONID', $newId);
$data['AUTHORIZATIONID'] = $newId;
$this->assertEquals($data, $request->getData());
}
}

View File

@@ -0,0 +1,494 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\PayPalRequest;
use OxidEsales\PayPalModule\Core\Exception\PayPalMissingParameterException;
/**
* Testing \OxidEsales\PayPalModule\Model\PayPalRequest\SetExpressCheckoutRequestBuilder class.
*/
class SetExpressCheckoutRequestBuilderTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
*/
public function testAddBaseParams()
{
$expectedParams = array(
'CALLBACKVERSION' => '84.0',
'LOCALECODE' => 'OEPAYPAL_LOCALE',
'SOLUTIONTYPE' => 'Sole',
'BRANDNAME' => 'ShopName',
'CARTBORDERCOLOR' => 'BorderColor',
'LOGOIMG' => 'LogoImg',
'PAYMENTREQUEST_0_PAYMENTACTION' => 'TransactionMode',
'RETURNURL' => null,
'CANCELURL' => null,
);
$configMethodValues = array(
'getBrandName' => 'ShopName',
'getBorderColor' => 'BorderColor',
'getLogoUrl' => 'LogoImg',
'isGuestBuyEnabled' => true,
);
$config = $this->_createStub(\OxidEsales\PayPalModule\Core\Config::class, $configMethodValues);
$builder = $this->getPayPalRequestBuilder();
$builder->setPayPalConfig($config);
$builder->setTransactionMode('TransactionMode');
$builder->addBaseParams();
$this->assertArraysEqual($expectedParams, $builder->getPayPalRequest()->getData());
}
public function testAddBaseParams_NoLogoImg_NoLogoParamSet()
{
$configMethodValues = array(
'getBrandName' => 'ShopName',
'getBorderColor' => 'BorderColor',
'isGuestBuyEnabled' => true,
'getLogoUrl' => null,
);
$config = $this->_createStub(\OxidEsales\PayPalModule\Core\Config::class, $configMethodValues);
$builder = $this->getPayPalRequestBuilder();
$builder->setPayPalConfig($config);
$builder->addBaseParams();
$this->assertNotContains('LOGOIMG', $builder->getPayPalRequest()->getData());
}
public function testAddBaseParams_NoConfigSet_ExceptionThrown()
{
$this->expectException(PayPalMissingParameterException::class);
$builder = $this->getPayPalRequestBuilder();
$builder->addBaseParams();
}
public function testAddBaseParams_CancelUrlSet_ParameterNotNull()
{
$expectedParams = array(
'CANCELURL' => 'cancelUrl',
);
$config = new \OxidEsales\PayPalModule\Core\Config();
$builder = $this->getPayPalRequestBuilder();
$builder->setPayPalConfig($config);
$builder->setCancelUrl('cancelUrl');
$builder->addBaseParams();
$this->assertArraysContains($expectedParams, $builder->getPayPalRequest()->getData());
}
public function testAddBaseParams_ReturnUrlSet_ParameterNotNull()
{
$expectedParams = array(
'RETURNURL' => 'returnUrl',
);
$config = new \OxidEsales\PayPalModule\Core\Config();
$builder = $this->getPayPalRequestBuilder();
$builder->setPayPalConfig($config);
$builder->setReturnUrl('returnUrl');
$builder->addBaseParams();
$this->assertArraysContains($expectedParams, $builder->getPayPalRequest()->getData());
}
protected function getBasketStub($params = array())
{
$basketMethodValues = array(
'isVirtualPayPalBasket' => true,
'getPrice' => oxNew(\OxidEsales\Eshop\Core\Price::class),
'getPayPalBasketVatValue' => '88.88',
'isCalculationModeNetto' => true,
'getTransactionMode' => '88.88',
'getSumOfCostOfAllItemsPayPalBasket' => '77.77',
'getDeliveryCosts' => '66.66',
'getDiscountSumPayPalBasket' => '55.55',
'getShippingId' => null,
);
foreach ($params as $key => $value) {
$basketMethodValues[$key] = $value;
}
return $this->_createStub(\OxidEsales\Eshop\Application\Model\Basket::class, $basketMethodValues);
}
public function testSetBasket_AllParamsSet()
{
$expectedParams = array(
'NOSHIPPING' => '1',
'REQCONFIRMSHIPPING' => '0',
'PAYMENTREQUEST_0_AMT' => '99.99',
'PAYMENTREQUEST_0_CURRENCYCODE' => 'EUR',
'PAYMENTREQUEST_0_TAXAMT' => '88.88',
'PAYMENTREQUEST_0_ITEMAMT' => '77.77',
'PAYMENTREQUEST_0_SHIPPINGAMT' => '66.66',
'PAYMENTREQUEST_0_SHIPDISCAMT' => '-55.55',
'L_SHIPPINGOPTIONISDEFAULT0' => 'true',
'L_SHIPPINGOPTIONNAME0' => '#1',
'L_SHIPPINGOPTIONAMOUNT0' => '66.66',
);
$price = $this->_createStub(\OxidEsales\Eshop\Core\Price::class, array('getBruttoPrice' => '99.99'));
$basketMethodValues = array('getPrice' => $price);
$basket = $this->getBasketStub($basketMethodValues);
$builder = $this->getPayPalRequestBuilder();
$builder->setBasket($basket);
$builder->addBasketParams();
$this->assertArraysEqual($expectedParams, $builder->getPayPalRequest()->getData());
}
/**
*/
public function testSetBasket_OnUpdateCalledOnBasket()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Basket::class);
$mockBuilder->setMethods(
['onUpdate',
'calculateBasket',
'isVirtualPayPalBasket',
'getSumOfCostOfAllItemsPayPalBasket',
'getDiscountSumPayPalBasket']
);
$basket= $mockBuilder->getMock();
$basket->expects($this->at(0))->method('onUpdate');
$basket->expects($this->at(1))->method('calculateBasket');
$basket->expects($this->atLeastOnce())->method('isVirtualPayPalBasket');
$basket->expects($this->atLeastOnce())->method('getSumOfCostOfAllItemsPayPalBasket');
$basket->expects($this->atLeastOnce())->method('getDiscountSumPayPalBasket');
$builder = $this->getPayPalRequestBuilder();
$builder->setBasket($basket);
$builder->addBasketParams();
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
$mockBuilder->setMethods(['setParameter']);
$payPalService = $mockBuilder->getMock();
$payPalService->expects($this->any())->method("setParameter");
}
public function testSetBasket_NotVirtualBasket_ShippingReconfirmNotSet()
{
$basketMethodValues = array(
'isVirtualPayPalBasket' => false,
);
$basket = $this->getBasketStub($basketMethodValues);
$builder = $this->getPayPalRequestBuilder();
$builder->setBasket($basket);
$builder->addBasketParams();
$this->assertNotContains('REQCONFIRMSHIPPING', $builder->getPayPalRequest()->getData());
}
public function testSetBasket_NotNettoMode_TaxAmountNotSet()
{
$basketMethodValues = array(
'isCalculationModeNetto' => false,
);
$basket = $this->getBasketStub($basketMethodValues);
$builder = $this->getPayPalRequestBuilder();
$builder->setBasket($basket);
$builder->addBasketParams();
$this->assertNotContains('PAYMENTREQUEST_0_TAXAMT', $builder->getPayPalRequest()->getData());
}
public function testSetBasket_NoConfigSet_ExceptionThrown()
{
$this->expectException(PayPalMissingParameterException::class);
$builder = $this->getPayPalRequestBuilder();
$builder->addBasketParams();
}
public function testSetDescription()
{
$expectedParams = array(
'PAYMENTREQUEST_0_DESC' => 'ShopName 99.99 EUR',
'PAYMENTREQUEST_0_CUSTOM' => 'ShopName 99.99 EUR',
);
$basketMethodValues = array(
'getFPrice' => '99.99',
);
$basket = $this->_createStub(\OxidEsales\Eshop\Application\Model\Basket::class, $basketMethodValues);
$configMethodValues = array('getBrandName' => 'ShopName');
$config = $this->_createStub(\OxidEsales\PayPalModule\Core\Config::class, $configMethodValues);
$lang = $this->_createStub(\OxidEsales\Eshop\Core\Language::class, array('translateString' => '%s %s %s'));
$builder = $this->getPayPalRequestBuilder();
$builder->setLang($lang);
$builder->setBasket($basket);
$builder->setPayPalConfig($config);
$builder->addDescriptionParams();
$this->assertArraysEqual($expectedParams, $builder->getPayPalRequest()->getData());
}
public function testSetDescription_NoConfigSet_ExceptionThrown()
{
$this->expectException(PayPalMissingParameterException::class);
$builder = $this->getPayPalRequestBuilder();
$builder->addDescriptionParams();
}
public function testAddBasketItemParams_WithItems()
{
$expectedParams = array(
'L_PAYMENTREQUEST_0_NAME0' => 'BasketItemTitle',
'L_PAYMENTREQUEST_0_AMT0' => '99.99',
'L_PAYMENTREQUEST_0_QTY0' => '88',
'L_PAYMENTREQUEST_0_ITEMURL0' => 'BasketItemUrl',
'L_PAYMENTREQUEST_0_NUMBER0' => 'BasketItemArtNum',
'L_PAYMENTREQUEST_0_NAME1' => 'BasketItemTitle',
'L_PAYMENTREQUEST_0_AMT1' => '99.99',
'L_PAYMENTREQUEST_0_QTY1' => '88',
'L_PAYMENTREQUEST_0_ITEMURL1' => 'BasketItemUrl',
'L_PAYMENTREQUEST_0_NUMBER1' => 'BasketItemArtNum',
);
$article = oxNew(\OxidEsales\Eshop\Application\Model\Article::class);
$article->oxarticles__oxartnum = new \OxidEsales\Eshop\Core\Field('BasketItemArtNum');
$priceMethodValues = array(
'getPrice' => '99.99',
);
$price = $this->_createStub(\OxidEsales\Eshop\Core\Price::class, $priceMethodValues);
$basketItemMethodValues = array(
'getTitle' => 'BasketItemTitle',
'getUnitPrice' => $price,
'getAmount' => '88',
'getLink' => 'BasketItemUrl',
'getArticle' => $article,
);
$basketItem = $this->_createStub(\OxidEsales\Eshop\Application\Model\BasketItem::class, $basketItemMethodValues);
$basketItems = array($basketItem, $basketItem);
$basketMethodValues = array(
'getContents' => $basketItems,
'getPayPalPaymentCosts' => 0,
'getPayPalWrappingCosts' => 0,
'getPayPalGiftCardCosts' => 0
);
$basket = $this->_createStub(\OxidEsales\Eshop\Application\Model\Basket::class, $basketMethodValues);
$builder = $this->getPayPalRequestBuilder();
$builder->setBasket($basket);
$builder->addBasketItemParams();
$this->assertArraysEqual($expectedParams, $builder->getPayPalRequest()->getData());
}
public function testAddBasketItemParams_WithPayment()
{
$expectedParams = array(
'L_PAYMENTREQUEST_0_NAME0' => 'OEPAYPAL_SURCHARGE OEPAYPAL_TYPE_OF_PAYMENT',
'L_PAYMENTREQUEST_0_AMT0' => '66.74',
'L_PAYMENTREQUEST_0_QTY0' => 1,
);
$basketMethodValues = array(
'getContents' => array(),
'getPayPalPaymentCosts' => 66.74,
'getPayPalWrappingCosts' => 0,
'getPayPalGiftCardCosts' => 0
);
$basket = $this->_createStub(\OxidEsales\Eshop\Application\Model\Basket::class, $basketMethodValues);
$builder = $this->getPayPalRequestBuilder();
$builder->setBasket($basket);
$builder->addBasketItemParams();
$this->assertArraysEqual($expectedParams, $builder->getPayPalRequest()->getData());
}
public function testAddBasketItemParams_WithWrapping()
{
$expectedParams = array(
'L_PAYMENTREQUEST_0_NAME0' => 'OEPAYPAL_GIFTWRAPPER',
'L_PAYMENTREQUEST_0_AMT0' => '100.00',
'L_PAYMENTREQUEST_0_QTY0' => 1,
);
$basketMethodValues = array(
'getContents' => array(),
'getPayPalPaymentCosts' => 0,
'getPayPalWrappingCosts' => 100,
'getPayPalGiftCardCosts' => 0
);
$basket = $this->_createStub(\OxidEsales\Eshop\Application\Model\Basket::class, $basketMethodValues);
$builder = $this->getPayPalRequestBuilder();
$builder->setBasket($basket);
$builder->addBasketItemParams();
$this->assertArraysEqual($expectedParams, $builder->getPayPalRequest()->getData());
}
public function testAddBasketItemParams_WithGiftCard()
{
$expectedParams = array(
'L_PAYMENTREQUEST_0_NAME0' => 'OEPAYPAL_GREETING_CARD',
'L_PAYMENTREQUEST_0_AMT0' => '100.99',
'L_PAYMENTREQUEST_0_QTY0' => 1,
);
$basketMethodValues = array(
'getContents' => array(),
'getPayPalPaymentCosts' => 0,
'getPayPalWrappingCosts' => 0,
'getPayPalGiftCardCosts' => 100.99
);
$basket = $this->_createStub(\OxidEsales\Eshop\Application\Model\Basket::class, $basketMethodValues);
$builder = $this->getPayPalRequestBuilder();
$builder->setBasket($basket);
$builder->addBasketItemParams();
$this->assertArraysEqual($expectedParams, $builder->getPayPalRequest()->getData());
}
public function testAddBasketGrandTotalParams()
{
$expectedParams = array(
'L_PAYMENTREQUEST_0_NAME0' => 'OEPAYPAL_GRAND_TOTAL',
'L_PAYMENTREQUEST_0_AMT0' => '99.99',
'L_PAYMENTREQUEST_0_QTY0' => 1,
);
$basketMethodValues = array(
'getSumOfCostOfAllItemsPayPalBasket' => '99.99'
);
$basket = $this->_createStub(\OxidEsales\Eshop\Application\Model\Basket::class, $basketMethodValues);
$builder = $this->getPayPalRequestBuilder();
$builder->setBasket($basket);
$builder->addBasketGrandTotalParams();
$this->assertArraysEqual($expectedParams, $builder->getPayPalRequest()->getData());
}
public function testAddAddressParams_SelectedAddressIdNotSet_TakeInfoFromUser()
{
$expectedParams = array(
'EMAIL' => 'test@test.com',
'PAYMENTREQUEST_0_SHIPTONAME' => 'FirstName LastName',
'PAYMENTREQUEST_0_SHIPTOSTREET' => 'Street StreetNr',
'PAYMENTREQUEST_0_SHIPTOCITY' => 'City',
'PAYMENTREQUEST_0_SHIPTOZIP' => 'Zip',
'PAYMENTREQUEST_0_SHIPTOPHONENUM' => 'PhoneNum',
'PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE' => null,
);
$userMethodValues = array(
'getSelectedAddressId' => null,
);
$user = $this->_createStub(\OxidEsales\Eshop\Application\Model\User::class, $userMethodValues);
$user->oxuser__oxusername = new \OxidEsales\Eshop\Core\Field('test@test.com');
$user->oxuser__oxfname = new \OxidEsales\Eshop\Core\Field('FirstName');
$user->oxuser__oxlname = new \OxidEsales\Eshop\Core\Field('LastName');
$user->oxuser__oxstreet = new \OxidEsales\Eshop\Core\Field('Street');
$user->oxuser__oxstreetnr = new \OxidEsales\Eshop\Core\Field('StreetNr');
$user->oxuser__oxcity = new \OxidEsales\Eshop\Core\Field('City');
$user->oxuser__oxzip = new \OxidEsales\Eshop\Core\Field('Zip');
$user->oxuser__oxfon = new \OxidEsales\Eshop\Core\Field('PhoneNum');
$user->oxuser__oxcity = new \OxidEsales\Eshop\Core\Field('City');
$builder = $this->getPayPalRequestBuilder();
$builder->setUser($user);
$builder->addAddressParams();
$this->assertArraysEqual($expectedParams, $builder->getPayPalRequest()->getData());
}
/**
* @return \OxidEsales\PayPalModule\Model\PayPalRequest\SetExpressCheckoutRequestBuilder
*/
protected function getPayPalRequestBuilder()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Language::class);
$mockBuilder->setMethods(['translateString']);
$lang = $mockBuilder->getMock();
$lang->expects($this->any())
->method('translateString')
->will($this->returnArgument(0));
$builder = new \OxidEsales\PayPalModule\Model\PayPalRequest\SetExpressCheckoutRequestBuilder();
$builder->setLang($lang);
return $builder;
}
/**
* Checks whether array length are equal and array keys and values are equal independent on keys position
*
* @param $expected
* @param $result
*/
protected function assertArraysEqual($expected, $result)
{
$this->assertArraysContains($expected, $result);
$this->assertEquals(count($expected), count($result));
}
/**
* Checks whether array array keys and values are equal independent on keys position
*
* @param $expected
* @param $result
*/
protected function assertArraysContains($expected, $result)
{
foreach ($expected as $key => $value) {
$this->assertArrayHasKey($key, $result, "Key not found: $key");
$this->assertEquals($value, $result[$key], "Key '$key' value is not equal to '$value'");
}
}
public function testGetMaxDeliveryAmount_notSet_0()
{
$builder = new \OxidEsales\PayPalModule\Model\PayPalRequest\SetExpressCheckoutRequestBuilder();
$this->assertEquals(0, $builder->getMaxDeliveryAmount());
}
public function testGetMaxDeliveryAmount_setValue_setValue()
{
$builder = new \OxidEsales\PayPalModule\Model\PayPalRequest\SetExpressCheckoutRequestBuilder();
$builder->setMaxDeliveryAmount(13);
$this->assertEquals(13, $builder->getMaxDeliveryAmount());
}
}

View File

@@ -0,0 +1,160 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\Eshop\Application\Model\Basket;
use OxidEsales\Eshop\Application\Model\PaymentGateway;
/**
* Testing oxAccessRightException class.
*/
class PaymentGatewayTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
public function testGetPayPalConfig_notSet_config()
{
$paymentGateway = oxNew(PaymentGateway::class);
$config = $paymentGateway->getPayPalConfig();
$this->assertTrue($config instanceof \OxidEsales\PayPalModule\Core\Config);
}
public function testGetPayPalService_notSet_service()
{
$paymentGateway = new \OxidEsales\PayPalModule\Model\PaymentGateway();
$service = $paymentGateway->getPayPalCheckoutService();
$this->assertTrue($service instanceof \OxidEsales\PayPalModule\Core\PayPalService);
}
public function testDoExpressCheckoutPayment_onSuccess_true()
{
// preparing price
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Price::class);
$mockBuilder->setMethods(['getBruttoPrice']);
$price = $mockBuilder->getMock();
$price->expects($this->once())->method("getBruttoPrice")->will($this->returnValue(123));
// preparing basket
$mockBuilder = $this->getMockBuilder(Basket::class);
$mockBuilder->setMethods(['getPrice']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method("getPrice")->will($this->returnValue($price));
// preparing session
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Session::class);
$mockBuilder->setMethods(['getBasket']);
$session = $mockBuilder->getMock();
$session->expects($this->any())->method("getBasket")->will($this->returnValue($basket));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Session::class, $session);
// preparing config
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Config::class);
$mockBuilder->setMethods(['getTransactionMode']);
$payPalConfig = $mockBuilder->getMock();
$payPalConfig->expects($this->any())->method("getTransactionMode")->will($this->returnValue("Sale"));
// preparing order
$mockBuilder = $this->getMockBuilder(Order::class);
$mockBuilder->setMethods(['finalizePayPalOrder']);
$payPalOrder = $mockBuilder->getMock();
$payPalOrder->expects($this->once())->method("finalizePayPalOrder")->with($this->equalTo('Result'));
// preparing service
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
$mockBuilder->setMethods(['doExpressCheckoutPayment']);
$payPalService = $mockBuilder->getMock();
$payPalService->expects($this->any())->method("doExpressCheckoutPayment")->will($this->returnValue('Result'));
// preparing
$mockBuilder = $this->getMockBuilder(PaymentGateway::class);
$mockBuilder->setMethods(['getPayPalCheckoutService', 'getPayPalConfig', 'getPayPalOrder', 'getPayPalUser']);
$paymentGateway = $mockBuilder->getMock();
$paymentGateway->expects($this->any())->method("getPayPalCheckoutService")->will($this->returnValue($payPalService));
$paymentGateway->expects($this->any())->method("getPayPalOrder")->will($this->returnValue($payPalOrder));
$paymentGateway->expects($this->any())->method("getPayPalConfig")->will($this->returnValue($payPalConfig));
$paymentGateway->expects($this->any())->method("getPayPalUser")->will($this->returnValue(oxNew(\OxidEsales\Eshop\Application\Model\User::class)));
// testing
$this->assertTrue($paymentGateway->doExpressCheckoutPayment());
}
public function testDoExpressCheckoutPayment_onResponseError_FalseAndException()
{
$exception = new \OxidEsales\Eshop\Core\Exception\StandardException();
// preparing price
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Price::class);
$mockBuilder->setMethods(['getBruttoPrice']);
$price = $mockBuilder->getMock();
$price->expects($this->once())->method("getBruttoPrice")->will($this->returnValue(123));
// preparing basket
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Basket::class);
$mockBuilder->setMethods(['getPrice']);
$basket = $mockBuilder->getMock();
$basket->expects($this->once())->method("getPrice")->will($this->returnValue($price));
// preparing session
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Session::class);
$mockBuilder->setMethods(['getBasket']);
$session = $mockBuilder->getMock();
$session->expects($this->any())->method("getBasket")->will($this->returnValue($basket));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Session::class, $session);
// preparing config
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\Config::class);
$mockBuilder->setMethods(['getTransactionMode']);
$payPalConfig = $mockBuilder->getMock();
$payPalConfig->expects($this->any())->method("getTransactionMode")->will($this->returnValue("Sale"));
// preparing order
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\Order::class);
$mockBuilder->setMethods(['deletePayPalOrder']);
$payPalOrder = $mockBuilder->getMock();
$payPalOrder->expects($this->once())->method("deletePayPalOrder")->will($this->returnValue(true));
// preparing service
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Core\PayPalService::class);
$mockBuilder->setMethods(['doExpressCheckoutPayment']);
$payPalService = $mockBuilder->getMock();
$payPalService->expects($this->any())->method("doExpressCheckoutPayment")->will($this->throwException($exception));
// preparing
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\PaymentGateway::class);
$mockBuilder->setMethods(['getPayPalCheckoutService', 'getPayPalConfig', 'getPayPalOrder', 'getPayPalUser']);
$paymentGateway = $mockBuilder->getMock();
$paymentGateway->expects($this->any())->method("getPayPalCheckoutService")->will($this->returnValue($payPalService));
$paymentGateway->expects($this->any())->method("getPayPalOrder")->will($this->returnValue($payPalOrder));
$paymentGateway->expects($this->any())->method("getPayPalConfig")->will($this->returnValue($payPalConfig));
$paymentGateway->expects($this->any())->method("getPayPalUser")->will($this->returnValue(oxNew(\OxidEsales\Eshop\Application\Model\User::class)));
// testing
$this->assertFalse($paymentGateway->doExpressCheckoutPayment());
}
public function testGetPayPalOxOrder_NotSet()
{
$paymentGateway = new \OxidEsales\PayPalModule\Model\PaymentGateway();
$this->assertInstanceOf(\OxidEsales\Eshop\Application\Model\Order::class, $paymentGateway->getPayPalOxOrder());
}
}

View File

@@ -0,0 +1,310 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
/**
* Testing \OxidEsales\PayPalModule\Model\PaymentValidator class.
*/
class PaymentValidatorTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* getCheckCountry test with default value.
*/
public function testSetGetCheckCountry_default()
{
$validator = new \OxidEsales\PayPalModule\Model\PaymentValidator();
$this->assertTrue($validator->getCheckCountry());
}
/**
* getCheckCountry test with custom set value.
*/
public function testSetGetCheckCountry_custom()
{
$checkCountry = false;
$validator = new \OxidEsales\PayPalModule\Model\PaymentValidator();
$validator->setCheckCountry($checkCountry);
$this->assertFalse($validator->getCheckCountry());
}
/**
* Testing validator when price and user objects are not set and payment is active
*/
public function testIsPaymentValid_paymentActive_true()
{
$payment = new \OxidEsales\Eshop\Application\Model\Payment();
$payment->oxpayments__oxactive = new \OxidEsales\Eshop\Core\Field(1);
$validator = new \OxidEsales\PayPalModule\Model\PaymentValidator();
$validator->setPayment($payment);
$this->assertTrue($validator->isPaymentValid());
}
/**
* Checks validator when getCheckoutCountry returns default- true.
*/
public function testIsPaymentValid_checkCountryDefault_false()
{
$paymentValidator = $this->getPaymentValidator();
$this->assertFalse($paymentValidator->isPaymentValid());
}
/**
* Checks validator when getCheckoutCountry returns custom- false.
*/
public function testIsPaymentValid_checkCountryCustom_true()
{
$paymentValidator = $this->getPaymentValidator();
$paymentValidator->setCheckCountry(false);
$this->assertTrue($paymentValidator->isPaymentValid());
}
/**
* Testing validator when price and user objects are not set and payment is not active
*/
public function testIsPaymentValid_paymentInActive_true()
{
$payment = new \OxidEsales\Eshop\Application\Model\Payment();
$payment->oxpayments__oxactive = new \OxidEsales\Eshop\Core\Field(0);
$validator = new \OxidEsales\PayPalModule\Model\PaymentValidator();
$validator->setPayment($payment);
$this->assertFalse($validator->isPaymentValid());
}
public function providerIsPaymentValid_allCases()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Groups::class);
$mockBuilder->setMethods(['getId']);
$group1 = $mockBuilder->getMock();
$group1->expects($this->any())->method("getId")->will($this->returnValue("someGroup1"));
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Groups::class);
$mockBuilder->setMethods(['getId']);
$group2 = $mockBuilder->getMock();
$group2->expects($this->any())->method("getId")->will($this->returnValue("someGroup2"));
$listEmpty = oxNew(\OxidEsales\Eshop\Core\Model\ListModel::class);
$list1 = oxNew(\OxidEsales\Eshop\Core\Model\ListModel::class);
$list1[] = $group1;
$list2 = oxNew(\OxidEsales\Eshop\Core\Model\ListModel::class);
$list2[] = $group1;
$list2[] = $group2;
return array(
// price outside range, user has account, payment has no set countries, and no user groups set - expects false
array(1, 10, 100, 5, array(), null, "someCountry", true, $listEmpty, array(), false),
// price outside range, user has account, payment has no set countries, but has user group set, user belongs to the same group - expects false
array(1, 10, 100, 110, array(), null, "someCountry", true, $list1, array('someGroup1' => "data"), false),
// price inside range, user has account, payment has no set countries, but has user group set, user belongs to the same group - expects true
array(1, 10, 100, 10, array(), null, "someCountry", true, $list1, array('someGroup1' => "data"), true),
// paypal payment is not active - expects false
array(0, 10, 100, 10, array(), null, "someCountry", true, $listEmpty, array(), false),
// Shipping country not equal to given countries
// price inside range, user has account, payment has countries and groups set, but user is from other country, but belongs to the same group - expects false
array(1, 10, 100, 10, array("someOtherCountry", "andAnotherCountry"), "someCountry", null, true, $list1, array('someGroup1' => "data"), false),
// price inside range, user has account, payment has countries and groups set, but user is from the same country and belongs to the same group - expects true
array(1, 10, 100, 100, array("someOtherCountry", "someCountry", "andAnotherCountry"), null, "someCountry", true, $list1, array('someGroup1' => "data"), true),
// price inside range, user has account, payment does not have countries set, but has user groups set, user does not belong to any user group - expects false
array(1, 10, 100, 10, array(), null, "someCountry", true, $list2, array(), false),
// price inside range, user has account, payment does not have countries set, but has user groups set, user belongs to one user group - expects true
array(1, 10, 100, 10, array(), null, "someCountry", true, $list2, array('someGroup1' => "data"), true),
// price inside range, user has account, payment does not have countries set, but has user groups set, user belongs to different user group - expects false
array(1, 10, 100, 10, array(), null, "someCountry", true, $list2, array('someGroup3' => "data"), false),
// price inside range, user does not have account (anonymous), payment has groups set - expects true
array(1, 10, 100, 10, array(), null, "someCountry", false, $list2, array(), true),
// Shipping country not given, but user address is given
array(1, 10, 100, 10, array(), "someCountry", null, false, $list2, array(), true),
array(1, 10, 100, 10, array("someOtherCountry", "someCountry", "andAnotherCountry"), "someCountry", null, false, $list2, array(), true),
// Shipping country not given and user address is not same as given countries
array(1, 10, 100, 10, array("someOtherCountry", "andAnotherCountry"), "someCountry", null, true, $list2, array(), false),
);
}
/**
* Testing PayPal payment validator all cases
*
* @dataProvider providerIsPaymentValid_allCases
*/
public function testIsPaymentValid_allCases($isActivePayment, $rangeFrom, $rangeTo, $price, $paymentCountries, $userCountryId, $userShippingCountryId, $userHasAccount, $paymentUserGroups, $userGroups, $expectedResult)
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Payment::class);
$mockBuilder->setMethods(['getCountries', 'getGroups']);
$payment = $mockBuilder->getMock();
$payment->expects($this->any())->method("getCountries")->will($this->returnValue($paymentCountries));
$payment->expects($this->any())->method("getGroups")->will($this->returnValue($paymentUserGroups));
$payment->load('oxidpaypal');
$payment->oxpayments__oxfromamount = new \OxidEsales\Eshop\Core\Field($rangeFrom);
$payment->oxpayments__oxtoamount = new \OxidEsales\Eshop\Core\Field($rangeTo);
$payment->oxpayments__oxactive = new \OxidEsales\Eshop\Core\Field($isActivePayment);
$address = oxNew(\OxidEsales\Eshop\Application\Model\Address::class);
$address->oxaddress__oxcountryid = new \OxidEsales\Eshop\Core\Field($userShippingCountryId);
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\User::class);
$mockBuilder->setMethods(['getUserGroups', 'hasAccount', 'getSelectedAddress', 'getSelectedAddressId']);
$user = $mockBuilder->getMock();
$user->expects($this->any())->method("getUserGroups")->will($this->returnValue($userGroups));
$user->expects($this->any())->method("hasAccount")->will($this->returnValue($userHasAccount));
$user->expects($this->any())->method("getSelectedAddress")->will($this->returnValue($address));
$user->expects($this->any())->method("getSelectedAddressId")->will($this->returnValue($userShippingCountryId));
$user->oxuser__oxcountryid = new \OxidEsales\Eshop\Core\Field($userCountryId);
$validator = new \OxidEsales\PayPalModule\Model\PaymentValidator();
$validator->setConfig($this->getConfig());
$validator->setPayment($payment);
$validator->setUser($user);
$validator->setPrice($price);
$this->assertEquals($expectedResult, $validator->isPaymentValid());
}
/**
* Testing PayPal payment validator all cases
*
*/
public function testIsPaymentValid_NoGroupsAssignedToPayment_True()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\Payment::class);
$mockBuilder->setMethods(['getCountries', 'getGroups']);
$payment = $mockBuilder->getMock();
$payment->oxpayments__oxactive = new \OxidEsales\Eshop\Core\Field(1);
$payment->expects($this->any())->method("getGroups")->will($this->returnValue(array()));
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\User::class);
$mockBuilder->setMethods(['hasAccount']);
$user = $mockBuilder->getMock();
$user->expects($this->any())->method("hasAccount")->will($this->returnValue(1));
$validator = new \OxidEsales\PayPalModule\Model\PaymentValidator();
$validator->setConfig($this->getConfig());
$validator->setPayment($payment);
$validator->setUser($user);
$this->assertEquals(true, $validator->isPaymentValid());
}
/**
* Testing isPaymentValid when iMinOrderPrice is not set and payment price is passed
*/
public function testIsPaymentActive_MinOrderPriceNotSet_True()
{
$payment = new \OxidEsales\Eshop\Application\Model\Payment();
$payment->oxpayments__oxfromamount = new \OxidEsales\Eshop\Core\Field(0);
$payment->oxpayments__oxtoamount = new \OxidEsales\Eshop\Core\Field(0);
$payment->oxpayments__oxactive = new \OxidEsales\Eshop\Core\Field(1);
$this->getConfig()->setConfigParam('iMinOrderPrice', '');
$validator = new \OxidEsales\PayPalModule\Model\PaymentValidator();
$validator->setConfig($this->getConfig());
$validator->setPayment($payment);
$validator->setPrice(50);
$this->assertEquals(true, $validator->isPaymentValid());
}
/**
* Testing isPaymentValid when iMinOrderPrice is set and payment price is higher
*/
public function testIsPaymentActive_MinOrderPriceSet_True()
{
$payment = new \OxidEsales\Eshop\Application\Model\Payment();
$payment->oxpayments__oxfromamount = new \OxidEsales\Eshop\Core\Field(0);
$payment->oxpayments__oxtoamount = new \OxidEsales\Eshop\Core\Field(0);
$payment->oxpayments__oxactive = new \OxidEsales\Eshop\Core\Field(1);
$this->getConfig()->setConfigParam('iMinOrderPrice', 10);
$validator = new \OxidEsales\PayPalModule\Model\PaymentValidator();
$validator->setConfig($this->getConfig());
$validator->setPayment($payment);
$validator->setPrice(50);
$this->assertEquals(true, $validator->isPaymentValid());
}
/**
* Testing isPaymentValid when iMinOrderPrice is not set and payment price is lower
*/
public function testIsPaymentActive_MinOrderPriceSet_False()
{
$payment = new \OxidEsales\Eshop\Application\Model\Payment();
$payment->oxpayments__oxfromamount = new \OxidEsales\Eshop\Core\Field(0);
$payment->oxpayments__oxtoamount = new \OxidEsales\Eshop\Core\Field(0);
$payment->oxpayments__oxactive = new \OxidEsales\Eshop\Core\Field(1);
$this->getConfig()->setConfigParam('iMinOrderPrice', 50);
$validator = new \OxidEsales\PayPalModule\Model\PaymentValidator();
$validator->setConfig($this->getConfig());
$validator->setPayment($payment);
$validator->setPrice(10);
$this->assertEquals(false, $validator->isPaymentValid());
}
/**
* @return \OxidEsales\PayPalModule\Model\PaymentValidator
*/
protected function getPaymentValidator()
{
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\User::class);
$mockBuilder->setMethods(['hasAccount']);
$user = $mockBuilder->getMock();
$user->expects($this->any())->method('hasAccount')->will($this->returnValue(true));
$mockBuilder = $this->getMockBuilder(\OxidEsales\PayPalModule\Model\PaymentValidator::class);
$mockBuilder->setMethods(
['isPaymentActive',
'getPrice',
'checkPriceRange',
'checkMinOrderPrice',
'getUser',
'checkUserGroup',
'checkUserCountry']
);
$paymentValidator = $mockBuilder->getMock();
$paymentValidator->expects($this->any())->method('isPaymentActive')->will($this->returnValue(true));
$paymentValidator->expects($this->any())->method('getPrice')->will($this->returnValue(true));
$paymentValidator->expects($this->any())->method('checkPriceRange')->will($this->returnValue(true));
$paymentValidator->expects($this->any())->method('checkMinOrderPrice')->will($this->returnValue(true));
$paymentValidator->expects($this->any())->method('getUser')->will($this->returnValue($user));
$paymentValidator->expects($this->any())->method('checkUserGroup')->will($this->returnValue(true));
$paymentValidator->expects($this->any())->method('checkUserCountry')->will($this->returnValue(false));
return $paymentValidator;
}
}

View File

@@ -0,0 +1,95 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Response;
/**
* Testing oxAccessRightException class.
*/
class ResponseDoCaptureTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Returns response data
*
* @return array
*/
protected function getResponseData()
{
$data = array(
'TRANSACTIONID' => 'transactionId',
'CORRELATIONID' => 'correlationId',
'PAYMENTSTATUS' => 'completed',
'AMT' => 12.45,
'CURRENCYCODE' => 'LTL'
);
return $data;
}
/**
* Test get authorization id
*/
public function testGetTransactionId()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoCapture();
$response->setData($this->getResponseData());
$this->assertEquals('transactionId', $response->getTransactionId());
}
/**
* Test get correlation id
*/
public function testGetCorrelationId()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoCapture();
$response->setData($this->getResponseData());
$this->assertEquals('correlationId', $response->getCorrelationId());
}
/**
* Test get payment status
*/
public function testGetPaymentStatus()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoCapture();
$response->setData($this->getResponseData());
$this->assertEquals('completed', $response->getPaymentStatus());
}
/**
* Test get payment status
*/
public function testGetCaptureAmount()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoCapture();
$response->setData($this->getResponseData());
$this->assertEquals(12.45, $response->getCapturedAmount());
}
/**
* Test get payment status
*/
public function testGetCurrency()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoCapture();
$response->setData($this->getResponseData());
$this->assertEquals('LTL', $response->getCurrency());
}
}

View File

@@ -0,0 +1,95 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Response;
/**
* Testing \OxidEsales\PayPalModule\Model\Response\ResponseDoExpressCheckoutPayment class.
*/
class ResponseDoExpressCheckoutPaymentTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Returns response data
*
* @return array
*/
protected function getResponseData()
{
$data = array(
'PAYMENTINFO_0_TRANSACTIONID' => 'transactionID',
'CORRELATIONID' => 'correlationID',
'PAYMENTINFO_0_PAYMENTSTATUS' => 'confirmed',
'PAYMENTINFO_0_AMT' => 1200,
'PAYMENTINFO_0_CURRENCYCODE' => 'LTL'
);
return $data;
}
/**
* Test get transaction id
*/
public function testGetTransactionId()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoExpressCheckoutPayment();
$response->setData($this->getResponseData());
$this->assertEquals('transactionID', $response->getTransactionId());
}
/**
* Test get transaction id
*/
public function testGetCorrelationId()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoExpressCheckoutPayment();
$response->setData($this->getResponseData());
$this->assertEquals('correlationID', $response->getCorrelationId());
}
/**
* Test get payment status
*/
public function testGetPaymentStatus()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoExpressCheckoutPayment();
$response->setData($this->getResponseData());
$this->assertEquals('confirmed', $response->getPaymentStatus());
}
/**
* Test get price amount
*/
public function testGetAmount()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoExpressCheckoutPayment();
$response->setData($this->getResponseData());
$this->assertEquals(1200, $response->getAmount());
}
/**
* Test get currency code
*/
public function testGetCurrencyCode()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoExpressCheckoutPayment();
$response->setData($this->getResponseData());
$this->assertEquals('LTL', $response->getCurrencyCode());
}
}

View File

@@ -0,0 +1,73 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Response;
/**
* Testing \OxidEsales\PayPalModule\Model\Response\ResponseDoReAuthorize class.
*/
class ResponseDoReAuthorizeTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Returns response data
*
* @return array
*/
protected function getResponseData()
{
$data = array(
'AUTHORIZATIONID' => 'authorizationId',
'CORRELATIONID' => 'correlationId',
'PAYMENTSTATUS' => 'completed'
);
return $data;
}
/**
* Test get authorization id
*/
public function testGetAuthorizationId()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoReAuthorize();
$response->setData($this->getResponseData());
$this->assertEquals('authorizationId', $response->getAuthorizationId());
}
/**
* Test get correlation id
*/
public function testGetCorrelationId()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoCapture();
$response->setData($this->getResponseData());
$this->assertEquals('correlationId', $response->getCorrelationId());
}
/**
* Test get payment status
*/
public function testGetPaymentStatus()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoReAuthorize();
$response->setData($this->getResponseData());
$this->assertEquals('completed', $response->getPaymentStatus());
}
}

View File

@@ -0,0 +1,95 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Response;
/**
* Testing oxAccessRightException class.
*/
class ResponseDoRefundTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Returns response data
*
* @return array
*/
protected function getResponseData()
{
$data = array(
'REFUNDTRANSACTIONID' => 'transactionId',
'CORRELATIONID' => 'correlationId',
'REFUNDSTATUS' => 'completed',
'GROSSREFUNDAMT' => 12.45,
'CURRENCYCODE' => 'LTL'
);
return $data;
}
/**
* Test get authorization id
*/
public function testGeTransactionId()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoRefund();
$response->setData($this->getResponseData());
$this->assertEquals('transactionId', $response->getTransactionId());
}
/**
* Test get correlation id
*/
public function testGetCorrelationId()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoCapture();
$response->setData($this->getResponseData());
$this->assertEquals('correlationId', $response->getCorrelationId());
}
/**
* Test get payment status
*/
public function testGetPaymentStatus()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoRefund();
$response->setData($this->getResponseData());
$this->assertEquals('completed', $response->getPaymentStatus());
}
/**
* Test get payment status
*/
public function testGetRefundAmount()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoRefund();
$response->setData($this->getResponseData());
$this->assertEquals(12.45, $response->getRefundAmount());
}
/**
* Test get payment status
*/
public function testGetCurrency()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoRefund();
$response->setData($this->getResponseData());
$this->assertEquals('LTL', $response->getCurrency());
}
}

View File

@@ -0,0 +1,138 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Response;
/**
* Testing \OxidEsales\PayPalModule\Model\Response\ResponseDoVerifyWithPayPal class.
*/
class ResponseDoVerifyWithPayPalTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Returns response data
*
* @return array
*/
public function providerResponseData()
{
return array(
array(
array(
'VERIFIED' => true,
'receiver_email' => 'some@oxid-esales.com',
'test_ipn' => true,
'payment_status' => 'refund',
'txn_id' => '153d4fd1s',
'mc_gross' => 20.55,
'mc_currency' => 'EUR',
),
array(
'ack' => true,
'receiver_email' => 'some@oxid-esales.com',
'test_ipn' => true,
'payment_status' => 'refund',
'transaction_id' => '153d4fd1s',
'amount' => 20.55,
'currency' => 'EUR',
)
),
array(
array(
'Not-VERIFIED' => true,
'receiver_email' => 'someone@oxid-esales.com',
'test_ipn' => false,
'payment_status' => 'completed',
'txn_id' => '454asd4as46d4',
'mc_gross' => 124.55,
'mc_currency' => 'USD',
),
array(
'ack' => false,
'receiver_email' => 'someone@oxid-esales.com',
'test_ipn' => false,
'payment_status' => 'completed',
'transaction_id' => '454asd4as46d4',
'amount' => 124.55,
'currency' => 'USD',
)
),
);
}
/**
* @dataProvider providerResponseData
*/
public function testIsPayPalAck($dataResponse, $dataExpect)
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoVerifyWithPayPal();
$response->setData($dataResponse);
$this->assertEquals($dataExpect['ack'], $response->isPayPalAck());
}
/**
* @dataProvider providerResponseData
*/
public function testGetReceiverEmail($dataResponse, $dataExpect)
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoVerifyWithPayPal();
$response->setData($dataResponse);
$this->assertEquals($dataExpect['receiver_email'], $response->getReceiverEmail());
}
/**
* @dataProvider providerResponseData
*/
public function testGetPaymentStatus($dataResponse, $dataExpect)
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoVerifyWithPayPal();
$response->setData($dataResponse);
$this->assertEquals($dataExpect['payment_status'], $response->getPaymentStatus());
}
/**
* @dataProvider providerResponseData
*/
public function testGetTransactionId($dataResponse, $dataExpect)
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoVerifyWithPayPal();
$response->setData($dataResponse);
$this->assertEquals($dataExpect['transaction_id'], $response->getTransactionId());
}
/**
* @dataProvider providerResponseData
*/
public function testGetCurrency($dataResponse, $dataExpect)
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoVerifyWithPayPal();
$response->setData($dataResponse);
$this->assertEquals($dataExpect['currency'], $response->getCurrency());
}
/**
* @dataProvider providerResponseData
*/
public function testGetAmount($dataResponse, $dataExpect)
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoVerifyWithPayPal();
$response->setData($dataResponse);
$this->assertEquals($dataExpect['amount'], $response->getAmount());
}
}

View File

@@ -0,0 +1,63 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Response;
/**
* Testing \OxidEsales\PayPalModule\Model\Response\ResponseDoVoid class.
*/
class ResponseDoVoidTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Returns response data
*
* @return array
*/
protected function getResponseData()
{
$data = array(
'AUTHORIZATIONID' => 'authorizationId',
'CORRELATIONID' => 'correlationId',
'PAYMENTSTATUS' => 'completed'
);
return $data;
}
/**
* Test get authorization id
*/
public function testGetAuthorizationId()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoVoid();
$response->setData($this->getResponseData());
$this->assertEquals('authorizationId', $response->getAuthorizationId());
}
/**
* Test get correlation id
*/
public function testGetCorrelationId()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseDoCapture();
$response->setData($this->getResponseData());
$this->assertEquals('correlationId', $response->getCorrelationId());
}
}

View File

@@ -0,0 +1,230 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Response;
/**
* Testing \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails class.
*/
class ResponseGetExpressCheckoutDetailsTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Returns response data
*
* @return array
*/
protected function getResponseData()
{
$data = array(
'SHIPPINGOPTIONNAME' => 'Air',
'PAYMENTREQUEST_0_AMT' => 1200,
'PAYERID' => 'payer',
'EMAIL' => 'oxid@oxid.com',
'FIRSTNAME' => 'Name',
'LASTNAME' => 'Surname',
'PAYMENTREQUEST_0_SHIPTOSTREET' => 'Street',
'PAYMENTREQUEST_0_SHIPTOCITY' => 'City',
'PAYMENTREQUEST_0_SHIPTONAME' => 'First Last',
'PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE' => 'CountryCode',
'PAYMENTREQUEST_0_SHIPTOSTATE' => 'State',
'PAYMENTREQUEST_0_SHIPTOZIP' => '1121',
'PAYMENTREQUEST_0_SHIPTOPHONENUM' => '+37000000000',
'PAYMENTREQUEST_0_SHIPTOSTREET2' => 'Street2',
'SALUTATION' => 'this is salutation',
'BUSINESS' => 'company',
'PHONENUM' => '123-345-789'
);
return $data;
}
/**
* Test getting shipping option name
*/
public function testGetShippingOptionName()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('Air', $response->getShippingOptionName());
}
/**
* Test getting token
*/
public function testGetAmount()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals(1200, $response->getAmount());
}
/**
* Test getting payer id
*/
public function testGetPayerId()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('payer', $response->getPayerId());
}
/**
* Test getting email
*/
public function testGetEmail()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('oxid@oxid.com', $response->getEmail());
}
/**
* Test getting first name
*/
public function testGetFirstName()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('Name', $response->getFirstName());
}
/**
* Test getting last name
*/
public function testGetLastName()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('Surname', $response->getLastName());
}
/**
* Test getting street
*/
public function testGetShipToStreet()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('Street', $response->getShipToStreet());
}
/**
* Test getting city
*/
public function testGetShipToCity()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('City', $response->getShipToCity());
}
/**
* Test getting name
*/
public function testGetShipToName()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('First Last', $response->getShipToName());
}
/**
* Test getting country code
*/
public function testGetShipToCountryCode()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('CountryCode', $response->getShipToCountryCode());
}
/**
* Test getting state
*/
public function testGetShipToState()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('State', $response->getShipToState());
}
/**
* Test getting state
*/
public function testGetShipToZip()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('1121', $response->getShipToZip());
}
/**
* Test getting phone number
*/
public function testGetShipToPhoneNumber()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('+37000000000', $response->getShipToPhoneNumber());
}
/**
* Test getting phone number
*/
public function testGetShipToPhoneNumberMandatory()
{
$defaultFields = \OxidEsales\Eshop\Core\Registry::getConfig()->getConfigParam('aMustFillFields');
\OxidEsales\Eshop\Core\Registry::getConfig()->setConfigParam('aMustFillFields', array_merge($defaultFields, ['oxuser__oxfon']));
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('123-345-789', $response->getShipToPhoneNumber());
}
/**
* Test getting phone number
*/
public function testGetShipToStreet2()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('Street2', $response->getShipToStreet2());
}
/**
* Test getting salutation
*/
public function testGetSalutation()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('this is salutation', $response->getSalutation());
}
/**
* Test getting company name
*/
public function testGetBusiness()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$response->setData($this->getResponseData());
$this->assertEquals('company', $response->getBusiness());
}
}

View File

@@ -0,0 +1,51 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model\Response;
/**
* Testing \OxidEsales\PayPalModule\Model\Response\ResponseSetExpressCheckout class.
*/
class ResponseSetExpressCheckoutTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/**
* Returns response data
*
* @return array
*/
protected function getResponseData()
{
$data = array(
'TOKEN' => 'thisIsToken',
);
return $data;
}
/**
* Test getting callback url
*/
public function testGetToken()
{
$response = new \OxidEsales\PayPalModule\Model\Response\ResponseSetExpressCheckout();
$response->setData($this->getResponseData());
$this->assertEquals('thisIsToken', $response->getToken());
}
}

View File

@@ -0,0 +1,476 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit\Model;
use OxidEsales\Eshop\Application\Model\User;
use OxidEsales\Eshop\Application\Model\User as EshopUserModel;
use OxidEsales\Eshop\Core\Exception\StandardException as EshopStandardException;
/**
* Testing oxAccessRightException class.
*/
class UserTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
private const TEST_USER_ID = 'e7af1c3b786fd02906ccd75698f4e6b9 ';
/**
* Tear down the fixture.
*/
protected function tearDown(): void
{
$delete = 'TRUNCATE TABLE `oxuser`';
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($delete);
parent::tearDown();
}
/**
* Set up
*/
protected function setUp(): void
{
parent::setUp();
// fix for state ID compatability between editions
$sqlState = "REPLACE INTO `oxstates` (`OXID`, `OXCOUNTRYID`, `OXTITLE`, `OXISOALPHA2`, `OXTITLE_1`, `OXTITLE_2`, `OXTITLE_3`, `OXTIMESTAMP`) " .
"VALUES ('333', '8f241f11096877ac0.98748826', 'USA last state', 'SS', 'USA last state', '', '', CURRENT_TIMESTAMP);";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($sqlState);
}
/**
* Prepare PayPal response data array
*
* @return array
*/
protected function getPayPalData()
{
$payPalData = array();
$payPalData['EMAIL'] = 'test@test.mail';
$payPalData['FIRSTNAME'] = 'testFirstName';
$payPalData['LASTNAME'] = 'testLastName';
$payPalData['PAYMENTREQUEST_0_SHIPTONAME'] = 'testFirstName testLastName';
$payPalData['PHONENUM'] = 'testPhone';
$payPalData['SALUTATION'] = 'testSalutation';
$payPalData['BUSINESS'] = 'testBusiness';
$payPalData['PAYMENTREQUEST_0_SHIPTOSTREET'] = 'testStreetName str. 12';
$payPalData['PAYMENTREQUEST_0_SHIPTOSTREET2'] = 'testCompany';
$payPalData['PAYMENTREQUEST_0_SHIPTOCITY'] = 'testCity';
$payPalData['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE'] = 'US';
$payPalData['PAYMENTREQUEST_0_SHIPTOSTATE'] = 'SS';
$payPalData['PAYMENTREQUEST_0_SHIPTOZIP'] = 'testZip';
$payPalData['PAYMENTREQUEST_0_SHIPTOPHONENUM'] = 'testPhoneNum';
return $payPalData;
}
/**
* Test case for \OxidEsales\PayPalModule\Model\User::createPayPalUser()
* Creating user
*/
public function testCreatePayPalUser()
{
$payPalData = $this->getPayPalData();
$details = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$details->setData($payPalData);
$this->addModuleObject(\OxidEsales\Eshop\Application\Model\Address::class, new \OxidEsales\PayPalModule\Model\Address());
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\User::class);
$mockBuilder->setMethods(['_setAutoGroups']);
$payPalUser = $mockBuilder->getMock();
$payPalUser->expects($this->once())->method('_setAutoGroups')->with($this->equalTo("8f241f11096877ac0.98748826"));
$payPalUser->createPayPalUser($details);
$userId = $payPalUser->getId();
$user = new \OxidEsales\Eshop\Application\Model\User();
$user->load($userId);
$this->assertEquals(1, $user->oxuser__oxactive->value);
$this->assertEquals('test@test.mail', $user->oxuser__oxusername->value);
$this->assertEquals('testFirstName', $user->oxuser__oxfname->value);
$this->assertEquals('testLastName', $user->oxuser__oxlname->value);
$this->assertEquals('testPhoneNum', $user->oxuser__oxfon->value);
$this->assertEquals('testSalutation', $user->oxuser__oxsal->value);
$this->assertEquals('testBusiness', $user->oxuser__oxcompany->value);
$this->assertEquals('testStreetName str.', $user->oxuser__oxstreet->value);
$this->assertEquals('12', $user->oxuser__oxstreetnr->value);
$this->assertEquals('testCity', $user->oxuser__oxcity->value);
$this->assertEquals('testZip', $user->oxuser__oxzip->value);
$this->assertEquals('8f241f11096877ac0.98748826', $user->oxuser__oxcountryid->value);
$this->assertEquals('333', $user->oxuser__oxstateid->value);
$this->assertEquals('testCompany', $user->oxuser__oxaddinfo->value);
}
/**
* Test case for \OxidEsales\PayPalModule\Model\User::createPayPalUser()
* Creating user
*/
public function testCreatePayPalUser_streetName()
{
// streetnr in first position
$payPalData = $this->getPayPalData();
$payPalData['PAYMENTREQUEST_0_SHIPTOSTREET'] = '12 testStreetName str.';
$details = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$details->setData($payPalData);
$this->addModuleObject(\OxidEsales\Eshop\Application\Model\Address::class, new \OxidEsales\PayPalModule\Model\Address());
$payPalUser = new \OxidEsales\PayPalModule\Model\User();
$payPalUser->createPayPalUser($details);
$user = new \OxidEsales\Eshop\Application\Model\User();
$user->load($payPalUser->getId());
$this->assertEquals('testStreetName str.', $user->oxuser__oxstreet->value);
$this->assertEquals('12', $user->oxuser__oxstreetnr->value);
}
/**
* Test case for \OxidEsales\PayPalModule\Model\User::createPayPalUser()
* Returning id if exist, not creating
*/
public function testCreatePayPalAddressIfExist()
{
//creating existing user
$payPalData = $this->getPayPalData();
$details = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$details->setData($payPalData);
$this->addModuleObject(\OxidEsales\Eshop\Application\Model\Address::class, new \OxidEsales\PayPalModule\Model\Address());
$payPalOxUser = new \OxidEsales\PayPalModule\Model\User();
$payPalOxUser->createPayPalUser($details);
$sQ = "SELECT COUNT(*) FROM `oxuser`";
$addressCount = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getOne($sQ);
// prepareing data fo new address - the same
$payPalOxUser = new \OxidEsales\PayPalModule\Model\User();
$payPalOxUser->createPayPalUser($details);
$addressCountAfter = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getOne($sQ);
// skips the same address
$this->assertEquals($addressCount, $addressCountAfter);
}
/**
* Test case for \OxidEsales\PayPalModule\Model\User::isSamePayPalUser()
*/
public function testIsSamePayPalUser()
{
$payPalData = $this->getPayPalData();
$details = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$details->setData($payPalData);
$this->addModuleObject(\OxidEsales\Eshop\Application\Model\Address::class, new \OxidEsales\PayPalModule\Model\Address());
$user = new \OxidEsales\PayPalModule\Model\User();
$user->createPayPalUser($details);
$this->assertTrue($user->isSamePayPalUser($details));
$payPalData = $this->getPayPalData();
$payPalData['FIRSTNAME'] = 'testFirstNameBla';
$details->setData($payPalData);
$this->assertFalse($user->isSamePayPalUser($details));
$payPalData = $this->getPayPalData();
$payPalData['LASTNAME'] = 'testFirstNameBla';
$details->setData($payPalData);
$this->assertFalse($user->isSamePayPalUser($details));
$payPalData = $this->getPayPalData();
$payPalData['PAYMENTREQUEST_0_SHIPTOSTREET'] = 'testStreetNameBla str. 12';
$details->setData($payPalData);
$this->assertFalse($user->isSamePayPalUser($details));
$payPalData = $this->getPayPalData();
$payPalData['PAYMENTREQUEST_0_SHIPTOCITY'] = 'testCitybla';
$details->setData($payPalData);
$this->assertFalse($user->isSamePayPalUser($details));
}
/**
* Test case for \OxidEsales\PayPalModule\Model\User::isSamePayPalUser()
*/
public function testIsSamePayPalUser_decoding_html()
{
$payPalData = $this->getPayPalData();
$details = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$details->setData($payPalData);
$this->addModuleObject(\OxidEsales\Eshop\Application\Model\Address::class, new \OxidEsales\PayPalModule\Model\Address());
$user = new \OxidEsales\PayPalModule\Model\User();
$user->createPayPalUser($details);
// by default single quote ' will be convrted to &#039;
$user->oxuser__oxfname = new \OxidEsales\Eshop\Core\Field("test'FName");
$user->oxuser__oxlname = new \OxidEsales\Eshop\Core\Field("test'LName");
$payPalData["FIRSTNAME"] = "test'FName";
$payPalData["LASTNAME"] = "test'LName";
$details->setData($payPalData);
$this->assertTrue($user->isSamePayPalUser($details));
}
/**
* Test case for \OxidEsales\PayPalModule\Model\User::isSamePayPalUser()
*/
public function testIsSameAddressPayPalUser()
{
$payPalData = $this->getPayPalData();
$details = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$details->setData($payPalData);
$this->addModuleObject(\OxidEsales\Eshop\Application\Model\Address::class, new \OxidEsales\PayPalModule\Model\Address());
$user = new \OxidEsales\PayPalModule\Model\User();
$user->createPayPalUser($details);
$this->assertTrue($user->isSamePayPalUser($details));
$payPalData['PAYMENTREQUEST_0_SHIPTOSTREET'] = 'testStreetNameBla str. 12';
$details->setData($payPalData);
$this->assertFalse($user->isSamePayPalUser($details));
$payPalData['PAYMENTREQUEST_0_SHIPTOCITY'] = 'testCitybla';
$details->setData($payPalData);
$this->assertFalse($user->isSamePayPalUser($details));
}
/**
* Test case for \OxidEsales\PayPalModule\Model\User::isSamePayPalUser()
*/
public function testIsSameAddressPayPalUser_decoding_html()
{
$payPalData = $this->getPayPalData();
$details = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$details->setData($payPalData);
$this->addModuleObject(\OxidEsales\Eshop\Application\Model\Address::class, new \OxidEsales\PayPalModule\Model\Address());
$user = new \OxidEsales\PayPalModule\Model\User();
$user->createPayPalUser($details);
// by default single quote ' will be convrted to &#039;
$user->oxuser__oxstreet = new \OxidEsales\Eshop\Core\Field("test'StreetName");;
$user->oxuser__oxstreetnr = new \OxidEsales\Eshop\Core\Field("5");
$user->oxuser__oxcity = new \OxidEsales\Eshop\Core\Field("test'City");
$payPalData['PAYMENTREQUEST_0_SHIPTOSTREET'] = "test'StreetName 5";
$payPalData["PAYMENTREQUEST_0_SHIPTOCITY"] = "test'City";
$details->setData($payPalData);
$this->assertTrue($user->isSamePayPalUser($details));
}
/**
* Test case for \OxidEsales\PayPalModule\Model\User::isRealPayPalUser()
* In single shop
*/
public function testIsRealPayPalUser()
{
\OxidEsales\Eshop\Core\Registry::getConfig()->setConfigParam('blMallUsers', true);
$user = new \OxidEsales\Eshop\Application\Model\User();
$user->oxuser__oxusername = new \OxidEsales\Eshop\Core\Field('test@test.test');
$user->oxuser__oxpassword = new \OxidEsales\Eshop\Core\Field('paswd');
$user->setId('_testId');
$user->setShopId('_testShop2');
$user->save();
$user = new \OxidEsales\Eshop\Application\Model\User();
$user->oxuser__oxusername = new \OxidEsales\Eshop\Core\Field('test1@test.test');
$user->oxuser__oxpassword = new \OxidEsales\Eshop\Core\Field('');
$user->setShopId('_testShop1');
$user->save();
$userMock = $this->getMockBuilder(\OxidEsales\Eshop\Application\Model\User::class)
->setMethods(['getShopIdQueryPart'])
->getMock();
$userMock->expects($this->never())->method('getShopIdQueryPart');
$this->assertEquals('_testId', $userMock->isRealPayPalUser('test@test.test'));
$this->assertFalse($userMock->isRealPayPalUser('test1@test.test'));
$this->assertFalse($userMock->isRealPayPalUser('blabla@bla.bla'));
}
/**
* Test case for \OxidEsales\PayPalModule\Model\User::isRealPayPalUser()
* In multi shop
*/
public function testIsRealPayPalUserMultiShop()
{
$user = new \OxidEsales\Eshop\Application\Model\User();
$user->oxuser__oxusername = new \OxidEsales\Eshop\Core\Field('test@test.test');
$user->oxuser__oxpassword = new \OxidEsales\Eshop\Core\Field('paswd');
$user->oxuser__oxshopid = new \OxidEsales\Eshop\Core\Field(1);
$user->setId('_testId');
$user->save();
$user = new \OxidEsales\Eshop\Application\Model\User();
$user->oxuser__oxusername = new \OxidEsales\Eshop\Core\Field('test3@test.test');
$user->oxuser__oxpassword = new \OxidEsales\Eshop\Core\Field('paswd');
$user->oxuser__oxshopid = new \OxidEsales\Eshop\Core\Field(2);
$user->setId('_testId2');
$user->save();
$user = new \OxidEsales\Eshop\Application\Model\User();
$user->oxuser__oxusername = new \OxidEsales\Eshop\Core\Field('test1@test.test');
$user->oxuser__oxpassword = new \OxidEsales\Eshop\Core\Field('');
$user->oxuser__oxshopid = new \OxidEsales\Eshop\Core\Field(1);
$user->save();
$user = new \OxidEsales\PayPalModule\Model\User();
$mockBuilder = $this->getMockBuilder(\OxidEsales\Eshop\Core\Config::class);
$mockBuilder->setMethods(['getShopId']);
$config = $mockBuilder->getMock();
$config->expects($this->any())->method('getShopId')->will($this->returnValue('1'));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Config::class, $config);
\OxidEsales\Eshop\Core\Registry::getConfig()->setConfigParam('blMallUsers', true);
$this->assertEquals('_testId', $user->isRealPayPalUser('test@test.test'));
$this->assertFalse($user->isRealPayPalUser('test1@test.test'));
$this->assertEquals('_testId2', $user->isRealPayPalUser('test3@test.test'));
$this->assertFalse($user->isRealPayPalUser('blabla@bla.bla'));
}
/**
* Test case for \OxidEsales\PayPalModule\Model\User::loadUserPayPalUser()
*/
public function testLoadUserPayPalUser()
{
//session empty
$user = oxNew(\OxidEsales\Eshop\Application\Model\User::class);
$this->assertFalse($user->loadUserPayPalUser());
$this->assertEmpty($user->oxuser__oxid->value);
$user = oxNew(\OxidEsales\Eshop\Application\Model\User::class);
$user->oxuser__oxusername = new \OxidEsales\Eshop\Core\Field('test@test.test');
$user->oxuser__oxpassword = new \OxidEsales\Eshop\Core\Field('paswd');
$user->setId('_testId');
$user->save();
// user id in session
$this->getSession()->setVariable('oepaypal-userId', '_testId');
$user = oxNew(\OxidEsales\Eshop\Application\Model\User::class);
$this->assertTrue($user->loadUserPayPalUser());
$this->assertEquals('_testId', $user->oxuser__oxid->value);
}
/**
* Test case for \OxidEsales\PayPalModule\Model\User::initializeUserForCallBackPayPalUser()
* Creating user
*/
public function testInitializeUserForCallBackPayPalUser()
{
$this->addModuleObject(\OxidEsales\Eshop\Application\Model\Address::class, new \OxidEsales\PayPalModule\Model\Address());
$payPalData["SHIPTOSTREET"] = "testStreetName str. 12a";
$payPalData["SHIPTOCITY"] = "testCity";
$payPalData["SHIPTOSTATE"] = "SS";
$payPalData["SHIPTOCOUNTRY"] = "US";
$payPalData["SHIPTOZIP"] = "testZip";
$payPalUser = new \OxidEsales\PayPalModule\Model\User();
$payPalUser->initializeUserForCallBackPayPalUser($payPalData);
$this->assertTrue(is_string($payPalUser->getId()));
$this->assertEquals('testStreetName str.', $payPalUser->oxuser__oxstreet->value);
$this->assertEquals('12a', $payPalUser->oxuser__oxstreetnr->value);
$this->assertEquals('testCity', $payPalUser->oxuser__oxcity->value);
$this->assertEquals('testZip', $payPalUser->oxuser__oxzip->value);
$this->assertEquals('8f241f11096877ac0.98748826', $payPalUser->oxuser__oxcountryid->value);
$this->assertEquals('333', $payPalUser->oxuser__oxstateid->value);
}
public function testLoadCustomerFromAnonymousId(): void
{
$anonymousId = 'anonymoususer';
$userId = md5(uniqid());
$username = 'mydummyuseroxid-esales.com';
$user = oxNew(EshopUserModel::class);
$user->assign(
[
'oxid' => $userId,
'oxusername' => $username
]
);
$user->save();
$user = oxNew(EshopUserModel::class);
$this->assertFalse($user->load($anonymousId));
$user = oxNew(EshopUserModel::class);
$user->load($userId);
$user->assign(
[
'OEPAYPAL_ANON_USERID' => $anonymousId
]
);
$user->save();
$user = oxNew(EshopUserModel::class);
$user->setId($anonymousId);
$this->assertTrue($user->load($anonymousId));
$this->assertFalse($user->isLoaded());
$this->assertSame($anonymousId, $user->getId());
$this->assertSame($username, $user->getFieldData('oxusername'));
}
public function testLoadEmptyCustomerId(): void
{
$user = oxNew(EshopUserModel::class);
$success = $user->load('');
$this->assertFalse($success);
$this->assertEmpty($user->getFieldData('oxusername'));
}
public function testSetInvoiceDataFromPayPalResultError()
{
$payPalData = $this->getPayPalData();
$details = new \OxidEsales\PayPalModule\Model\Response\ResponseGetExpressCheckoutDetails();
$details->setData($payPalData);
$user = oxNew(EshopUserModel::class);
$user->load(self::TEST_USER_ID);
$this->expectException(EshopStandardException::class);
$user->setInvoiceDataFromPayPalResult($details);
}
/**
* Mock an object which is created by oxNew.
*
* Attention: please don't use this method, we want to get rid of it - all places can, and should, be replaced
* with plain mocks.
*
* Hint: see also Unit/Controller/ExpressCheckoutDispatcherTest
*
* @param string $className The name under which the object will be created with oxNew.
* @param object $object The mocked object oxNew should return instead of the original one.
*/
protected function addModuleObject($className, $object)
{
\OxidEsales\Eshop\Core\Registry::set($className, null);
\OxidEsales\Eshop\Core\UtilsObject::setClassInstance($className, $object);
}
}

View File

@@ -0,0 +1,208 @@
<?php
/**
* This file is part of O3-Shop Paypal module.
*
* O3-Shop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* O3-Shop is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with O3-Shop. If not, see <http://www.gnu.org/licenses/>
*
* @copyright Copyright (c) 2022 OXID eSales AG (https://www.oxid-esales.com)
* @copyright Copyright (c) 2022 O3-Shop (https://www.o3-shop.com)
* @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License 3 (GPLv3)
*/
namespace OxidEsales\PayPalModule\Tests\Unit;
use OxidEsales\TestingLibrary\Services\Files\Remove;
use OxidEsales\TestingLibrary\Services\Library\Request;
use OxidEsales\TestingLibrary\Services\Library\ServiceConfig;
class PayPalLogHelper
{
/**
* Holds the parsed log information.
*
* @var array
*/
private $logData = [];
/**
* Test helper to get PayPal log path.
*
* @return string
*/
public function getPathToPayPalLog()
{
return \OxidEsales\Eshop\Core\Registry::getConfig()->getLogsDir() . DIRECTORY_SEPARATOR . 'oepaypal.log';
}
/**
* Make sure log is writable.
*/
public function setLogPermissions()
{
$pathToLog = $this->getPathToPayPalLog();
if (file_exists($pathToLog) && !is_writable($pathToLog)){
\OxidEsales\TestingLibrary\Services\Library\CliExecutor::executeCommand("sudo chmod 777 $pathToLog");
}
}
/**
* Test helper, cleans PayPal log.
*/
public function cleanPayPalLog()
{
$pathToLog = $this->getPathToPayPalLog();
if (file_exists($pathToLog)) {
unlink($pathToLog);
}
}
/**
* Move PayPal log to different name for test debugging.
*/
public function renamePayPalLog()
{
$pathToLog = $this->getPathToPayPalLog();
if (file_exists($pathToLog)) {
rename($pathToLog, $pathToLog . ('_' . microtime(true)));
}
}
/**
* Get data from log.
*
* @return array
*/
public function getLogData()
{
$this->logData = [];
$this->parsePayPalLog();
return $this->logData;
}
/**
* Test helper, parses PayPal log.
*/
private function parsePayPalLog()
{
$handle = null;
if (file_exists($this->getPathToPayPalLog())) {
$handle = fopen($this->getPathToPayPalLog(), 'r');
}
if ($handle) {
while (($line = fgets($handle)) !== false) {
if (false !== strpos($line, 'Request to PayPal')) {
$date = $this->parseDate($line);
$handle = $this->handleLogData($handle, $date, 'request');
}
if (false !== strpos($line, 'Response from PayPal')) {
$date = $this->parseDate($line);
$handle = $this->handleLogData($handle, $date, 'response');
}
if (false !== strpos($line, 'IPN Process result')) {
$date = $this->parseDate($line);
$handle = $this->handleLogData($handle, $date, 'ipn_handle_result');
}
}
fclose($handle);
}
}
/**
* Parse data set until line containing a single ')' is hit.
*
* @param ressource $handle log file handle
* @param string $date date of action
* @param string $type type can be request or reponse
*
* @return mixed
*/
private function handleLogData($handle, $date, $type)
{
$sessionId = null;
$object = new \StdClass;
$object->date = $date;
$object->type = $type;
$object->data = [];
while ((($line = fgets($handle)) !== false) && (false === strpos($line, ')'))) {
if (false !== strpos($line, 'SESS ID')) {
$object->sid = $this->parseSessionId($line);
}
if (false !== strpos($line, "' =>")) {
$keyValue = $this->parseArray($line);
$object->data[$keyValue->key] = $keyValue->value;
}
}
$this->register($object);
return $handle;
}
/**
* Add result to parsed data.
*
* @param $object
*/
private function register($object)
{
$this->logData[] = $object;
}
/**
* Parse for date.
* Returns first match in given string.
*
* @param string $line
*
* @return string
*/
private function parseDate($line)
{
$matches=null;
$ret = null;
preg_match_all("/\[((\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}))\]/", $line, $matches);
if (is_array($matches) && !empty($matches)) {
$ret = $matches[1][0];
}
return $ret;
}
/**
* Parse for session id.
*
* Returns first match in given string.
*/
private function parseSessionId($line)
{
$tmp = explode('SESS ID:', $line);
return trim($tmp[1]);
}
/**
* @param string $line
*
* @return \StdClass
*/
private function parseArray($line)
{
$matches = null;
$object = new \StdClass;
preg_match_all("/\'(.*)\'(\s*=>\s*)\'*(.*)\'*/", $line, $matches);
if (is_array($matches) && isset($matches[1])) {
$object->key = isset($matches[1][0]) ? $matches[1][0] : null;
$object->value = isset($matches[3][0]) ? rtrim(rtrim($matches[3][0], ','), "'") : null;
}
return $object;
}
}