/** * Print Shipment Action * * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page */ public function execute() { $shipmentId = (int) $this->getRequest()->getParam('shipment_id'); if ($shipmentId) { $shipment = $this->_objectManager->create('Magento\\Sales\\Model\\Order\\Shipment')->load($shipmentId); $order = $shipment->getOrder(); } else { $orderId = (int) $this->getRequest()->getParam('order_id'); $order = $this->_objectManager->create('Magento\\Sales\\Model\\Order')->load($orderId); } if ($this->orderAuthorization->canView($order)) { $this->_coreRegistry->register('current_order', $order); if (isset($shipment)) { $this->_coreRegistry->register('current_shipment', $shipment); } /** @var \Magento\Framework\View\Result\Page $resultPage */ $resultPage = $this->resultPageFactory->create(); $resultPage->addHandle('print'); return $resultPage; } else { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); if ($this->_objectManager->get('Magento\\Customer\\Model\\Session')->isLoggedIn()) { $resultRedirect->setPath('*/*/history'); } else { $resultRedirect->setPath('sales/guest/form'); } return $resultRedirect; } }
/** * Action for reorder * * @return \Magento\Framework\Controller\ResultInterface */ public function execute() { $result = $this->orderLoader->load($this->_request); if ($result instanceof \Magento\Framework\Controller\ResultInterface) { return $result; } $order = $this->_coreRegistry->registry('current_order'); /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); /* @var $cart \Magento\Checkout\Model\Cart */ $cart = $this->_objectManager->get('Magento\\Checkout\\Model\\Cart'); $items = $order->getItemsCollection(); foreach ($items as $item) { try { $cart->addOrderItem($item); } catch (\Magento\Framework\Exception\LocalizedException $e) { if ($this->_objectManager->get('Magento\\Checkout\\Model\\Session')->getUseNotice(true)) { $this->messageManager->addNotice($e->getMessage()); } else { $this->messageManager->addError($e->getMessage()); } return $resultRedirect->setPath('*/*/history'); } catch (\Exception $e) { $this->messageManager->addException($e, __('We cannot add this item to your shopping cart.')); return $resultRedirect->setPath('checkout/cart'); } } $cart->save(); return $resultRedirect->setPath('checkout/cart'); }
/** * Set back redirect url to response * * @param null|string $backUrl * * @return \Magento\Framework\Controller\Result\Redirect */ protected function _goBack($backUrl = null) { $resultRedirect = $this->resultRedirectFactory->create(); if ($backUrl || ($backUrl = $this->getBackUrl($this->_redirect->getRefererUrl()))) { $resultRedirect->setUrl($backUrl); } return $resultRedirect; }
/** * @return void */ public function testCreateActionRegistrationDisabled() { $this->customerSession->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); $this->registrationMock->expects($this->once())->method('isAllowed')->will($this->returnValue(false)); $this->redirectFactoryMock->expects($this->once())->method('create')->willReturn($this->redirectResultMock); $this->redirectResultMock->expects($this->once())->method('setPath')->with('*/*')->willReturnSelf(); $this->resultPageMock->expects($this->never())->method('getLayout'); $this->object->execute(); }
/** * Retrieve redirect * * @return ResultRedirect */ public function getRedirect() { $this->updateLastCustomerId(); $this->prepareRedirectUrl(); /** @var ResultRedirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setUrl($this->session->getBeforeAuthUrl(true)); return $resultRedirect; }
/** * Order view form page * * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page */ public function execute() { if ($this->_objectManager->get('Magento\\Customer\\Model\\Session')->isLoggedIn()) { return $this->resultRedirectFactory->create()->setPath('customer/account/'); } $resultPage = $this->resultPageFactory->create(); $resultPage->getConfig()->getTitle()->set(__('Orders and Returns')); $this->_objectManager->get('Magento\\Sales\\Helper\\Guest')->getBreadcrumbs($resultPage); return $resultPage; }
public function testDispatchButtonNotEnabled() { $resultRedirect = new \Magento\Framework\DataObject(); $this->braintreePayPalConfigMock->expects($this->once())->method('isActive')->willReturn(true); $this->braintreePayPalConfigMock->expects($this->once())->method('isShortcutCheckoutEnabled')->willReturn(false); $this->actionFlagMock->expects($this->once())->method('set')->with('', \Magento\Framework\App\ActionInterface::FLAG_NO_DISPATCH); $this->resultRedirectFactoryMock->expects($this->once())->method('create')->willReturn($resultRedirect); $this->assertEquals($resultRedirect, $this->controller->execute($this->requestMock)); $this->assertEquals('noRoute', $resultRedirect->getPath()); }
/** * Executes the dispatch override */ public function testDispatchNotLoggedIn() { $objectManager = new ObjectManagerHelper($this); $this->resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirect); $this->resultRedirect->expects($this->any())->method('setPath')->willReturnSelf(); $this->customerSession->expects($this->any())->method('authenticate')->willReturn(false); $this->config->expects($this->any())->method('useVault')->willReturn(true); /** * @var \Magento\Framework\App\RequestInterface $requestInterface */ $requestInterface = $this->getMockBuilder('\\Magento\\Framework\\App\\Request\\Http')->disableOriginalConstructor()->getMock(); $notification = $objectManager->getObject('Magento\\Braintree\\Controller\\MyCreditCards', ['customerSession' => $this->customerSession, 'resultRedirectFactory' => $this->resultRedirectFactory, 'config' => $this->config, 'customerUrl' => $this->customerUrl, 'response' => $this->_response]); $this->assertSame($this->_response, $notification->dispatch($requestInterface)); }
public function testExecuteWithException() { $token = 'token'; $customerId = '11'; $this->requestMock->expects($this->exactly(2))->method('getParam')->willReturnMap([['token', null, $token], ['id', null, null]]); $this->sessionMock->expects($this->once())->method('getRpToken')->willReturn($token); $this->sessionMock->expects($this->once())->method('getRpCustomerId')->willReturn($customerId); $this->accountManagementMock->expects($this->once())->method('validateResetPasswordLinkToken')->with($customerId, $token)->willThrowException(new \Exception('Exception.')); $this->messageManagerMock->expects($this->once())->method('addError')->with(__('Your password reset link has expired.'))->willReturnSelf(); /** @var Redirect|\PHPUnit_Framework_MockObject_MockObject $redirectMock */ $redirectMock = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\Redirect')->disableOriginalConstructor()->getMock(); $this->redirectFactoryMock->expects($this->once())->method('create')->with([])->willReturn($redirectMock); $redirectMock->expects($this->once())->method('setPath')->with('*/*/forgotpassword', [])->willReturnSelf(); $this->assertEquals($redirectMock, $this->model->executeInternal()); }
/** * Executes the controller action */ public function testExecute() { $objectManager = new ObjectManagerHelper($this); $phrase = new \Magento\Framework\Phrase('There was error during saving card data'); $this->request->expects($this->any())->method('getParam')->willReturn('token'); $this->resultRedirectFactory->expects($this->once())->method('create')->willReturn($this->resultRedirect); $this->resultRedirect->expects($this->once())->method('setPath')->willReturnSelf(); /** * @var \Magento\Framework\Message\ManagerInterface $messageManager */ $messageManager = $this->getMockBuilder('\\Magento\\Framework\\Message\\ManagerInterface')->getMock(); $messageManager->expects($this->once())->method('addError')->with($phrase); $notification = $objectManager->getObject('Magento\\Braintree\\Controller\\Creditcard\\Save', ['request' => $this->request, 'resultRedirectFactory' => $this->resultRedirectFactory, 'messageManager' => $messageManager]); $this->assertSame($this->resultRedirect, $notification->execute()); }
/** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function testEditPostActionWithoutErrors() { $customerId = 24; $address = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\AddressInterface', [], '', false); $loadedCustomer = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\CustomerInterface', [], 'loadedCustomer', false); $loadedCustomer->expects($this->once())->method('getAddresses')->willReturn([$address, $address]); $this->resultRedirectFactory->expects($this->once())->method('create')->willReturn($this->redirectResultMock); $this->formKeyValidator->expects($this->once())->method('validate')->willReturn(true); $this->request->expects($this->once())->method('isPost')->willReturn(true); $this->customerSession->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->customerExtractor->expects($this->once())->method('extract')->willReturn($this->customer); $this->customer->expects($this->once())->method('setId')->with($customerId); $this->customer->expects($this->once())->method('getAddresses')->willReturn(null); $this->customerRepository->expects($this->exactly(2))->method('getById')->with($customerId)->willReturn($loadedCustomer); $this->customer->expects($this->once())->method('setAddresses')->with([$address, $address]); $this->request->expects($this->once())->method('getParam')->with('change_password')->willReturn(true); $this->request->expects($this->at(2))->method('getPost')->with('current_password', null)->willReturn(123); $this->request->expects($this->at(3))->method('getPost')->with('password', null)->willReturn(321); $this->request->expects($this->at(4))->method('getPost')->with('password_confirmation', null)->willReturn(321); $this->customerAccountManagement->expects($this->once())->method('changePassword'); $this->customerRepository->expects($this->once())->method('save'); $messageCollection = $this->getMock('Magento\\Framework\\Message\\Collection', [], [], '', false); $messageCollection->expects($this->once())->method('getCount')->willReturn(0); $this->messageManager->expects($this->once())->method('getMessages')->willReturn($messageCollection); $this->messageManager->expects($this->once())->method('addSuccess')->with('You saved the account information.'); $this->redirectResultMock->expects($this->once())->method('setPath')->with('customer/account')->willReturn('http://test.com/customer/account/edit'); $this->assertSame($this->redirectResultMock, $this->getController()->execute()); }
/** * @param \Magento\Backend\App\AbstractAction $subject * @param callable $proceed * @param \Magento\Framework\App\RequestInterface $request * * @return mixed * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundDispatch(\Magento\Backend\App\AbstractAction $subject, \Closure $proceed, \Magento\Framework\App\RequestInterface $request) { $requestedActionName = $request->getActionName(); if (in_array($requestedActionName, $this->_openActions)) { $request->setDispatched(true); } else { if ($this->_auth->getUser()) { $this->_auth->getUser()->reload(); } if (!$this->_auth->isLoggedIn()) { $this->_processNotLoggedInUser($request); } else { $this->_auth->getAuthStorage()->prolong(); $backendApp = null; if ($request->getParam('app')) { $backendApp = $this->backendAppList->getCurrentApp(); } if ($backendApp) { $resultRedirect = $this->resultRedirectFactory->create(); $baseUrl = \Magento\Framework\App\Request\Http::getUrlNoScript($this->backendUrl->getBaseUrl()); $baseUrl = $baseUrl . $backendApp->getStartupPage(); return $resultRedirect->setUrl($baseUrl); } } } $this->_auth->getAuthStorage()->refreshAcl(); return $proceed($request); }
/** * Test for execute method * * @return void */ public function testExecuteWithSuccessOrderSave() { $testData = $this->getExecuteWithSuccessOrderSaveTestData(); $redirectMock = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\Redirect')->disableOriginalConstructor()->getMock(); $paymentMock = $this->getMockBuilder('Magento\\Quote\\Model\\Quote\\Payment')->disableOriginalConstructor()->getMock(); $checkoutMock = $this->getMockBuilder('Magento\\Checkout\\Model\\Session')->disableOriginalConstructor()->setMethods(['getRedirectUrl'])->getMock(); $resultJsonMock = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\Json')->disableOriginalConstructor()->getMock(); $redirectMock->expects($this->never())->method('setPath')->with('*/*/')->willReturn('redirect'); $this->formKeyValidatorMock->expects($this->once())->method('validate')->with($this->requestMock)->willReturn(true); $this->resultRedirectFactoryMock->expects($this->never())->method('create')->willReturn($redirectMock); $this->objectManagerMock->expects($this->atLeastOnce())->method('get')->willReturnMap($testData['objectManager.get']); // call _expireAjax method $this->expireAjaxFlowHasItemsFalse(); $this->requestMock->expects($this->atLeastOnce())->method('getPost')->willReturnMap($testData['request.getPost']); $this->agreementsValidatorMock->expects($this->once())->method('isValid')->with($testData['agreementsValidator.isValid'])->willReturn(true); $this->quoteMock->expects($this->atLeastOnce())->method('getPayment')->willReturn($paymentMock); $paymentMock->expects($this->once())->method('setQuote')->with($this->quoteMock); $paymentMock->expects($this->once())->method('importData')->with($testData['payment.importData']); $this->onepageMock->expects($this->once())->method('saveOrder'); $this->onepageMock->expects($this->once())->method('getCheckout')->willReturn($checkoutMock); $checkoutMock->expects($this->once())->method('getRedirectUrl')->willReturn(null); $this->eventManagerMock->expects($this->once())->method('dispatch')->withConsecutive($this->equalTo('checkout_controller_onepage_saveOrder'), $this->countOf(2)); $this->resultJsonFactoryMock->expects($this->once())->method('create')->willReturn($resultJsonMock); $resultJsonMock->expects($this->once())->method('setData')->with($testData['resultJson.setData'])->willReturnSelf(); $this->assertEquals($resultJsonMock, $this->controller->execute()); }
public function testExecuteWithException() { $addressId = 1; $customerId = 2; $this->resultRedirectFactory->expects($this->once())->method('create')->willReturn($this->resultRedirect); $this->request->expects($this->once())->method('getParam')->with('id', false)->willReturn($addressId); $this->validatorMock->expects($this->once())->method('validate')->with($this->request)->willReturn(true); $this->addressRepositoryMock->expects($this->once())->method('getById')->with($addressId)->willReturn($this->address); $this->sessionMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->address->expects($this->once())->method('getCustomerId')->willReturn(34); $exception = new \Exception('Exception'); $this->messageManager->expects($this->once())->method('addError')->with(__('We can\'t delete the address right now.'))->willThrowException($exception); $this->messageManager->expects($this->once())->method('addException')->with($exception, __('We can\'t delete the address right now.')); $this->resultRedirect->expects($this->once())->method('setPath')->with('*/*/index')->willReturnSelf(); $this->assertSame($this->resultRedirect, $this->model->execute()); }
public function testExecute() { $customerId = 1; $refererUrl = 'http://referer.url'; $this->sessionMock->expects($this->once())->method('getId')->willReturn($customerId); $this->sessionMock->expects($this->once())->method('logout')->willReturnSelf(); $this->redirect->expects($this->once())->method('getRefererUrl')->willReturn($refererUrl); $this->sessionMock->expects($this->once())->method('setBeforeAuthUrl')->with($refererUrl)->willReturnSelf(); $this->sessionMock->expects($this->once())->method('setLastCustomerId')->with($customerId); $this->cookieManager->expects($this->once())->method('getCookie')->with('mage-cache-sessid')->willReturn(true); $this->cookieMetadataFactory->expects($this->once())->method('createCookieMetadata')->willReturn($this->cookieMetadata); $this->cookieMetadata->expects($this->once())->method('setPath')->with('/'); $this->cookieManager->expects($this->once())->method('deleteCookie')->with('mage-cache-sessid', $this->cookieMetadata); $this->redirectFactory->expects($this->once())->method('create')->willReturn($this->resultRedirect); $this->resultRedirect->expects($this->once())->method('setPath')->with('*/*/logoutSuccess'); $this->assertSame($this->resultRedirect, $this->controller->execute()); }
/** * @param RequestInterface $request * @return bool|\Magento\Framework\Controller\Result\Forward|\Magento\Framework\Controller\Result\Redirect */ public function load(RequestInterface $request) { $orderId = (int) $request->getParam('order_id'); if (!$orderId) { /** @var \Magento\Framework\Controller\Result\Forward $resultForward */ $resultForward = $this->resultForwardFactory->create(); return $resultForward->forward('noroute'); } $order = $this->orderFactory->create()->load($orderId); if ($this->orderAuthorization->canView($order)) { $this->registry->register('current_order', $order); return true; } /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->redirectFactory->create(); return $resultRedirect->setUrl($this->url->getUrl('*/*/history')); }
public function testExecuteWhenFormKeyValidationFailed() { $resultRedirect = $this->getMock(\Magento\Framework\Controller\Result\Redirect::class, [], [], '', false); $resultRedirect->expects($this->once())->method('setPath')->with('*/cart/')->willReturnSelf(); $this->resultRedirectFactory->expects($this->once())->method('create')->willReturn($resultRedirect); $this->getPropertyValue($this->removeItem, 'formKeyValidator')->expects($this->once())->method('validate')->with($this->requestMock)->willReturn(false); $this->assertEquals($resultRedirect, $this->removeItem->execute()); }
/** * Try to load valid order by $_POST or $_COOKIE * * @param App\RequestInterface $request * @return \Magento\Framework\Controller\Result\Redirect|bool * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function loadValidOrder(App\RequestInterface $request) { if ($this->customerSession->isLoggedIn()) { return $this->resultRedirectFactory->create()->setPath('sales/order/history'); } $post = $request->getPostValue(); $errors = false; /** @var $order \Magento\Sales\Model\Order */ $order = $this->orderFactory->create(); $fromCookie = $this->cookieManager->getCookie(self::COOKIE_NAME); if (empty($post) && !$fromCookie) { return $this->resultRedirectFactory->create()->setPath('sales/guest/form'); } elseif (!empty($post) && isset($post['oar_order_id']) && isset($post['oar_type'])) { $type = $post['oar_type']; $incrementId = $post['oar_order_id']; $lastName = $post['oar_billing_lastname']; $email = $post['oar_email']; $zip = $post['oar_zip']; $storeId = $this->_storeManager->getStore()->getId(); if (empty($incrementId) || empty($lastName) || empty($type) || empty($storeId) || !in_array($type, ['email', 'zip']) || $type == 'email' && empty($email) || $type == 'zip' && empty($zip)) { $errors = true; } if (!$errors) { $order = $order->loadByIncrementIdAndStoreId($incrementId, $storeId); } $errors = true; if ($order->getId()) { $billingAddress = $order->getBillingAddress(); if (strtolower($lastName) == strtolower($billingAddress->getLastname()) && ($type == 'email' && strtolower($email) == strtolower($billingAddress->getEmail()) || $type == 'zip' && strtolower($zip) == strtolower($billingAddress->getPostcode()))) { $errors = false; } } if (!$errors) { $toCookie = base64_encode($order->getProtectCode() . ':' . $incrementId); $this->setGuestViewCookie($toCookie); } } elseif ($fromCookie) { $cookieData = explode(':', base64_decode($fromCookie)); $protectCode = isset($cookieData[0]) ? $cookieData[0] : null; $incrementId = isset($cookieData[1]) ? $cookieData[1] : null; $errors = true; if (!empty($protectCode) && !empty($incrementId)) { $order->loadByIncrementId($incrementId); if ($order->getProtectCode() === $protectCode) { // renew cookie $this->setGuestViewCookie($fromCookie); $errors = false; } } } if (!$errors && $order->getId()) { $this->coreRegistry->register('current_order', $order); return true; } $this->messageManager->addError(__('You entered incorrect data. Please try again.')); return $this->resultRedirectFactory->create()->setPath('sales/guest/form'); }
public function testExecuteWithItems() { $this->request->expects($this->any())->method('getParam')->willReturnMap([['items', null, '1,2,3'], ['uenc', null, null]]); $this->decoderMock->expects($this->never())->method('decode'); $this->catalogSession->expects($this->never())->method('setBeforeCompareUrl'); $this->listCompareMock->expects($this->once())->method('addProducts')->with([1, 2, 3]); $redirect = $this->getMock('Magento\\Framework\\Controller\\Result\\Redirect', ['setPath'], [], '', false); $redirect->expects($this->once())->method('setPath')->with('*/*/*'); $this->redirectFactoryMock->expects($this->once())->method('create')->willReturn($redirect); $this->index->execute(); }
public function testLoginPostActionWhenRefererSetBeforeAuthUrl() { $this->_formKeyValidator->expects($this->once())->method('validate')->will($this->returnValue(true)); $this->objectManager->expects($this->any())->method('get')->will($this->returnValueMap([['Magento\\Framework\\App\\Config\\ScopeConfigInterface', new \Magento\Framework\Object(['config_flag' => 1])], ['Magento\\Core\\Helper\\Data', $this->getMock('Magento\\Core\\Helper\\Data', [], [], '', false)]])); $this->customerSession->expects($this->at(0))->method('isLoggedIn')->with()->will($this->returnValue(0)); $this->customerSession->expects($this->at(4))->method('isLoggedIn')->with()->will($this->returnValue(1)); $this->request->expects($this->once())->method('getParam')->with(Url::REFERER_QUERY_PARAM_NAME)->will($this->returnValue('referer')); $this->url->expects($this->once())->method('isOwnOriginUrl')->with(); $this->redirectFactoryMock->expects($this->once())->method('create')->willReturn($this->redirectResultMock); $this->redirectResultMock->expects($this->once())->method('setUrl')->willReturnSelf(); $this->object->execute(); }
public function testExecuteWithTaxClassAndException() { $taxClass = '3'; $groupId = 0; $code = 'NOT LOGGED IN'; $this->request->expects($this->exactly(3))->method('getParam')->withConsecutive(['tax_class'], ['id'], ['code'])->willReturnOnConsecutiveCalls($taxClass, $groupId, null); $this->resultRedirectFactory->expects($this->once())->method('create')->willReturn($this->resultRedirect); $this->groupRepositoryMock->expects($this->once())->method('getById')->with($groupId)->willReturn($this->group); $this->group->expects($this->once())->method('getCode')->willReturn($code); $this->group->expects($this->once())->method('setCode')->with($code); $this->group->expects($this->once())->method('setTaxClassId')->with($taxClass); $this->groupRepositoryMock->expects($this->once())->method('save')->with($this->group); $this->messageManager->expects($this->once())->method('addSuccess')->with(__('You saved the customer group.')); $exception = new \Exception('Exception'); $this->resultRedirect->expects($this->at(0))->method('setPath')->with('customer/group')->willThrowException($exception); $this->messageManager->expects($this->once())->method('addError')->with('Exception'); $this->dataObjectProcessorMock->expects($this->once())->method('buildOutputDataArray')->with($this->group, '\\Magento\\Customer\\Api\\Data\\GroupInterface')->willReturn(['code' => $code]); $this->session->expects($this->once())->method('setCustomerGroupData')->with(['customer_group_code' => $code]); $this->resultRedirect->expects($this->at(1))->method('setPath')->with('customer/group/edit', ['id' => $groupId]); $this->assertSame($this->resultRedirect, $this->controller->execute()); }
protected function prepareContext() { $this->context = $this->getMockBuilder('Magento\\Framework\\App\\Action\\Context')->disableOriginalConstructor()->getMock(); $this->resultRedirectFactory = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\RedirectFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $this->resultRedirect = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\Redirect')->disableOriginalConstructor()->getMock(); $this->request = $this->getMockBuilder('Magento\\Framework\\App\\Request\\Http')->disableOriginalConstructor()->getMock(); $this->messageManager = $this->getMockBuilder('Magento\\Framework\\Message\\ManagerInterface')->getMockForAbstractClass(); $this->context->expects($this->any())->method('getResultRedirectFactory')->willReturn($this->resultRedirectFactory); $this->context->expects($this->any())->method('getRequest')->willReturn($this->request); $this->context->expects($this->any())->method('getMessageManager')->willReturn($this->messageManager); $this->eventManager = $this->getMockBuilder('Magento\\Framework\\Event\\ManagerInterface')->getMockForAbstractClass(); $this->context->expects($this->any())->method('getEventManager')->willReturn($this->eventManager); $this->resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirect); }
/** * Set up */ protected function setUp() { $this->request = $this->getMock('Magento\\Framework\\App\\Request\\Http', ['getParam'], [], '', false); $this->request->expects($this->any())->method('getParam')->with('filename')->willReturn('filename'); $this->reportHelper = $this->getMock('Magento\\ImportExport\\Helper\\Report', ['importFileExists', 'getReportSize', 'getReportOutput'], [], '', false); $this->reportHelper->expects($this->any())->method('getReportSize')->willReturn(1); $this->reportHelper->expects($this->any())->method('getReportOutput')->willReturn('output'); $this->objectManager = $this->getMock('Magento\\Framework\\ObjectManager\\ObjectManager', ['get'], [], '', false); $this->objectManager->expects($this->any())->method('get')->with('Magento\\ImportExport\\Helper\\Report')->willReturn($this->reportHelper); $this->context = $this->getMock('Magento\\Backend\\App\\Action\\Context', ['getRequest', 'getObjectManager', 'getResultRedirectFactory'], [], '', false); $this->fileFactory = $this->getMock('Magento\\Framework\\App\\Response\\Http\\FileFactory', ['create'], [], '', false); $this->resultRaw = $this->getMock('Magento\\Framework\\Controller\\Result\\Raw', ['setContents'], [], '', false); $this->resultRawFactory = $this->getMock('\\Magento\\Framework\\Controller\\Result\\RawFactory', ['create'], [], '', false); $this->resultRawFactory->expects($this->any())->method('create')->willReturn($this->resultRaw); $this->redirect = $this->getMock('\\Magento\\Backend\\Model\\View\\Result\\Redirect', ['setPath'], [], '', false); $this->resultRedirectFactory = $this->getMock('Magento\\Framework\\Controller\\Result\\RedirectFactory', ['create'], [], '', false); $this->resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->redirect); $this->context->expects($this->any())->method('getRequest')->willReturn($this->request); $this->context->expects($this->any())->method('getObjectManager')->willReturn($this->objectManager); $this->context->expects($this->any())->method('getResultRedirectFactory')->willReturn($this->resultRedirectFactory); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->downloadController = $this->objectManagerHelper->getObject('Magento\\ImportExport\\Controller\\Adminhtml\\History\\Download', ['context' => $this->context, 'fileFactory' => $this->fileFactory, 'resultRawFactory' => $this->resultRawFactory, 'reportHelper' => $this->reportHelper]); }
/** * Make sure customer is valid, if logged in * * By default will add error messages and redirect to customer edit form * * @param bool $redirect - stop dispatch and redirect? * @param bool $addErrors - add error messages? * @return bool|\Magento\Framework\Controller\Result\Redirect */ protected function _preDispatchValidateCustomer($redirect = true, $addErrors = true) { try { $customer = $this->customerRepository->getById($this->_customerSession->getCustomerId()); } catch (NoSuchEntityException $e) { return true; } if (isset($customer)) { $validationResult = $this->accountManagement->validate($customer); if (!$validationResult->isValid()) { if ($addErrors) { foreach ($validationResult->getMessages() as $error) { $this->messageManager->addError($error); } } if ($redirect) { $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true); return $this->resultRedirectFactory->create()->setPath('customer/account/edit'); } return false; } } return true; }
public function testExecuteWithEmptyPassword() { $token = 'token'; $customerId = '11'; $password = ''; $passwordConfirmation = ''; $this->requestMock->expects($this->exactly(2))->method('getQuery')->willReturnMap([['token', $token], ['id', $customerId]]); $this->requestMock->expects($this->exactly(2))->method('getPost')->willReturnMap([['password', $password], ['password_confirmation', $passwordConfirmation]]); $this->messageManagerMock->expects($this->once())->method('addError')->with(__('Please enter a new password.'))->willReturnSelf(); /** @var Redirect|\PHPUnit_Framework_MockObject_MockObject $redirectMock */ $redirectMock = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\Redirect')->disableOriginalConstructor()->getMock(); $this->redirectFactoryMock->expects($this->once())->method('create')->with([])->willReturn($redirectMock); $redirectMock->expects($this->once())->method('setPath')->with('*/*/createPassword', ['id' => $customerId, 'token' => $token])->willReturnSelf(); $this->assertEquals($redirectMock, $this->model->execute()); }
/** * Executes the controller action and asserts failed deletion */ public function testExecuteInternalSaveFail() { $objectManager = new ObjectManagerHelper($this); $phrase = new \Magento\Framework\Phrase('There was error deleting the credit card'); $this->vault->expects($this->once())->method('deleteCard')->willReturn(false); $this->request->expects($this->any())->method('getParam')->willReturn('token'); $this->resultRedirectFactory->expects($this->once())->method('create')->willReturn($this->resultRedirect); /** * @var \Magento\Framework\Message\ManagerInterface $messageManager */ $messageManager = $this->getMockBuilder('\\Magento\\Framework\\Message\\ManagerInterface')->getMock(); $messageManager->expects($this->any())->method('addError')->with($phrase); /** @var \Magento\Braintree\Controller\Creditcard\DeleteConfirm $controller */ $controller = $objectManager->getObject('Magento\\Braintree\\Controller\\Creditcard\\DeleteConfirm', ['request' => $this->request, 'resultRedirectFactory' => $this->resultRedirectFactory, 'vault' => $this->vault, 'messageManager' => $messageManager]); $this->assertSame($this->resultRedirect, $controller->executeInternal()); }
/** * Executes the controller action and asserts with redirects for non existing logic */ public function testExecuteNonExistingTokenRedirect() { $objectManager = new ObjectManagerHelper($this); $phrase = new \Magento\Framework\Phrase('Credit card does not exist'); $this->vault->expects($this->once())->method('storedCard')->willReturn(false); $this->request->expects($this->any())->method('getParam')->willReturn('token'); $this->resultRedirectFactory->expects($this->once())->method('create')->willReturn($this->resultRedirect); $this->resultPageFactory->expects($this->never())->method('create')->willReturn($this->resultPage); $this->resultRedirect->expects($this->once())->method('setPath')->willReturnSelf(); /** * @var \Magento\Framework\Message\ManagerInterface $messageManager */ $messageManager = $this->getMockBuilder('\\Magento\\Framework\\Message\\ManagerInterface')->getMock(); $messageManager->expects($this->once())->method('addError')->with($phrase); $notification = $objectManager->getObject('Magento\\Braintree\\Controller\\Creditcard\\Delete', ['request' => $this->request, 'resultPageFactory' => $this->resultPageFactory, 'resultRedirectFactory' => $this->resultRedirectFactory, 'vault' => $this->vault, 'messageManager' => $messageManager]); $this->assertSame($this->resultRedirect, $notification->execute()); }
/** * Category view action * * @return \Magento\Framework\Controller\ResultInterface * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function execute() { if ($this->_request->getParam(\Magento\Framework\App\Action\Action::PARAM_NAME_URL_ENCODED)) { return $this->resultRedirectFactory->create()->setUrl($this->_redirect->getRedirectUrl()); } $category = $this->_initCategory(); if ($category) { $this->layerResolver->create(Resolver::CATALOG_LAYER_CATEGORY); $settings = $this->_catalogDesign->getDesignSettings($category); // apply custom design if ($settings->getCustomDesign()) { $this->_catalogDesign->applyCustomDesign($settings->getCustomDesign()); } $this->_catalogSession->setLastViewedCategoryId($category->getId()); $page = $this->resultPageFactory->create(); // apply custom layout (page) template once the blocks are generated if ($settings->getPageLayout()) { $page->getConfig()->setPageLayout($settings->getPageLayout()); } if ($category->getIsAnchor()) { $type = $category->hasChildren() ? 'layered' : 'layered_without_children'; } else { $type = $category->hasChildren() ? 'default' : 'default_without_children'; } if (!$category->hasChildren()) { // Two levels removed from parent. Need to add default page type. $parentType = strtok($type, '_'); $page->addPageLayoutHandles(['type' => $parentType]); } $page->addPageLayoutHandles(['type' => $type, 'id' => $category->getId()]); // apply custom layout update once layout is loaded $layoutUpdates = $settings->getLayoutUpdates(); if ($layoutUpdates && is_array($layoutUpdates)) { foreach ($layoutUpdates as $layoutUpdate) { $page->addUpdate($layoutUpdate); } } $page->getConfig()->addBodyClass('page-products')->addBodyClass('categorypath-' . $this->categoryUrlPathGenerator->getUrlPath($category))->addBodyClass('category-' . $category->getUrlKey()); $page->getLayout()->initMessages(); return $page; } elseif (!$this->getResponse()->isRedirect()) { return $this->resultForwardFactory->create()->forward('noroute'); } }
/** * Product view action * * @return \Magento\Framework\Controller\Result\Forward|\Magento\Framework\Controller\Result\Redirect */ public function execute() { // Get initial data from request $categoryId = (int) $this->getRequest()->getParam('category', false); $productId = (int) $this->getRequest()->getParam('id'); $specifyOptions = $this->getRequest()->getParam('options'); if ($this->getRequest()->isPost() && $this->getRequest()->getParam(self::PARAM_NAME_URL_ENCODED)) { $product = $this->_initProduct(); if (!$product) { return $this->noProductRedirect(); } if ($specifyOptions) { $notice = $product->getTypeInstance()->getSpecifyOptionMessage(); $this->messageManager->addNotice($notice); } if ($this->getRequest()->isAjax()) { $this->getResponse()->representJson($this->_objectManager->get('Magento\\Framework\\Json\\Helper\\Data')->jsonEncode(['backUrl' => $this->_redirect->getRedirectUrl()])); return; } $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setRefererOrBaseUrl(); return $resultRedirect; } // Prepare helper and params $params = new \Magento\Framework\Object(); $params->setCategoryId($categoryId); $params->setSpecifyOptions($specifyOptions); // Render page try { $page = $this->resultPageFactory->create(false, ['isIsolated' => true]); $this->viewHelper->prepareAndRender($page, $productId, $this, $params); return $page; } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { return $this->noProductRedirect(); } catch (\Exception $e) { $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e); $resultForward = $this->resultForwardFactory->create(); $resultForward->forward('noroute'); return $resultForward; } }
/** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function setUp() { $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); /** * This test can be unskipped when the Unit test object manager helper is enabled to return correct DataBuilders * For now the \Magento\Customer\Test\Unit\Controller\AccountTest sufficiently covers the SUT */ $this->markTestSkipped('Cannot be unit tested with the auto generated builder dependencies'); $this->customerSessionMock = $this->getMock('\\Magento\\Customer\\Model\\Session', [], [], '', false); $this->redirectMock = $this->getMock('Magento\\Framework\\App\\Response\\RedirectInterface'); $this->responseMock = $this->getMock('Magento\\Framework\\Webapi\\Response'); $this->requestMock = $this->getMock('Magento\\Framework\\App\\Request\\Http', [], [], '', false); $this->urlMock = $this->getMock('Magento\\Framework\\Url', [], [], '', false); $urlFactoryMock = $this->getMock('Magento\\Framework\\UrlFactory', [], [], '', false); $urlFactoryMock->expects($this->once())->method('create')->will($this->returnValue($this->urlMock)); $this->customerMock = $this->getMock('Magento\\Customer\\Api\\Data\\CustomerInterface', [], [], '', false); $this->customerDetailsMock = $this->getMock('Magento\\Customer\\Api\\Data\\CustomerInterface', [], [], '', false); $this->customerDetailsFactoryMock = $this->getMock('Magento\\Customer\\Api\\Data\\CustomerInterfaceFactory', [], [], '', false); $this->messageManagerMock = $this->getMock('Magento\\Framework\\Message\\Manager', [], [], '', false); $this->scopeConfigMock = $this->getMock('Magento\\Framework\\App\\Config\\ScopeConfigInterface'); $this->storeManagerMock = $this->getMock('Magento\\Store\\Model\\StoreManager', [], [], '', false); $this->storeMock = $this->getMock('Magento\\Store\\Model\\Store', [], [], '', false); $this->customerRepository = $this->getMock('Magento\\Customer\\Api\\CustomerRepositoryInterface'); $this->accountManagement = $this->getMock('Magento\\Customer\\Api\\AccountManagementInterface'); $this->addressHelperMock = $this->getMock('Magento\\Customer\\Helper\\Address', [], [], '', false); $formFactoryMock = $this->getMock('Magento\\Customer\\Model\\Metadata\\FormFactory', [], [], '', false); $this->subscriberMock = $this->getMock('Magento\\Newsletter\\Model\\Subscriber', [], [], '', false); $subscriberFactoryMock = $this->getMock('Magento\\Newsletter\\Model\\SubscriberFactory', ['create'], [], '', false); $subscriberFactoryMock->expects($this->any())->method('create')->will($this->returnValue($this->subscriberMock)); $regionFactoryMock = $this->getMock('Magento\\Customer\\Api\\Data\\RegionInterfaceFactory', [], [], '', false); $addressFactoryMock = $this->getMock('Magento\\Customer\\Api\\Data\\AddressInterfaceFactory', [], [], '', false); $this->customerUrl = $this->getMock('Magento\\Customer\\Model\\Url', [], [], '', false); $this->registration = $this->getMock('Magento\\Customer\\Model\\Registration', [], [], '', false); $escaperMock = $this->getMock('Magento\\Framework\\Escaper', [], [], '', false); $this->customerExtractorMock = $this->getMock('Magento\\Customer\\Model\\CustomerExtractor', [], [], '', false); $this->dataObjectHelperMock = $this->getMock('Magento\\Framework\\Api\\DataObjectHelper', [], [], '', false); $eventManagerMock = $this->getMock('Magento\\Framework\\Event\\ManagerInterface', [], [], '', false); $this->resultRedirectFactoryMock = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\RedirectFactory')->setMethods(['create'])->getMock(); $this->resultRedirectFactoryMock->expects($this->any())->method('create')->willReturn($this->redirectMock); $contextMock = $this->getMock('Magento\\Framework\\App\\Action\\Context', [], [], '', false); $contextMock->expects($this->any())->method('getRequest')->willReturn($this->requestMock); $contextMock->expects($this->any())->method('getResponse')->willReturn($this->responseMock); $contextMock->expects($this->any())->method('getRedirect')->willReturn($this->redirectMock); $contextMock->expects($this->any())->method('getMessageManager')->willReturn($this->messageManagerMock); $contextMock->expects($this->any())->method('getEventManager')->willReturn($eventManagerMock); $contextMock->expects($this->any())->method('getResultRedirectFactory')->willReturn($this->resultRedirectFactoryMock); $this->model = $objectManager->getObject('Magento\\Customer\\Controller\\Account\\CreatePost', ['context' => $contextMock, 'customerSession' => $this->customerSessionMock, 'scopeConfig' => $this->scopeConfigMock, 'storeManager' => $this->storeManagerMock, 'accountManagement' => $this->accountManagement, 'addressHelper' => $this->addressHelperMock, 'urlFactory' => $urlFactoryMock, 'formFactory' => $formFactoryMock, 'subscriberFactory' => $subscriberFactoryMock, 'regionDataFactory' => $regionFactoryMock, 'addressDataFactory' => $addressFactoryMock, 'customerDetailsFactory' => $this->customerDetailsFactoryMock, 'customerUrl' => $this->customerUrl, 'registration' => $this->registration, 'escape' => $escaperMock, 'customerExtractor' => $this->customerExtractorMock, 'dataObjectHelper' => $this->dataObjectHelperMock]); }