PageRenderTime 43ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractController.php

https://gitlab.com/crazybutterfly815/magento2
PHP | 291 lines | 153 code | 30 blank | 108 comment | 14 complexity | 18fed46b668d39a5fd59ad39b2984a40 MD5 | raw file
  1. <?php
  2. /**
  3. * Copyright © 2016 Magento. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. /**
  7. * Abstract class for the controller tests
  8. */
  9. namespace Magento\TestFramework\TestCase;
  10. use Magento\Framework\Stdlib\CookieManagerInterface;
  11. use Magento\Framework\View\Element\Message\InterpretationStrategyInterface;
  12. use Magento\Theme\Controller\Result\MessagePlugin;
  13. /**
  14. * @SuppressWarnings(PHPMD.NumberOfChildren)
  15. */
  16. abstract class AbstractController extends \PHPUnit_Framework_TestCase
  17. {
  18. protected $_runCode = '';
  19. protected $_runScope = 'store';
  20. protected $_runOptions = [];
  21. /**
  22. * @var \Magento\TestFramework\Request
  23. */
  24. protected $_request;
  25. /**
  26. * @var \Magento\TestFramework\Response
  27. */
  28. protected $_response;
  29. /**
  30. * @var \Magento\TestFramework\ObjectManager
  31. */
  32. protected $_objectManager;
  33. /**
  34. * Whether absence of session error messages has to be asserted automatically upon a test completion
  35. *
  36. * @var bool
  37. */
  38. protected $_assertSessionErrors = false;
  39. /**
  40. * Bootstrap instance getter
  41. *
  42. * @return \Magento\TestFramework\Helper\Bootstrap
  43. */
  44. protected function _getBootstrap()
  45. {
  46. return \Magento\TestFramework\Helper\Bootstrap::getInstance();
  47. }
  48. /**
  49. * Bootstrap application before any test
  50. */
  51. protected function setUp()
  52. {
  53. $this->_assertSessionErrors = false;
  54. $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
  55. $this->_objectManager->removeSharedInstance(\Magento\Framework\App\ResponseInterface::class);
  56. $this->_objectManager->removeSharedInstance(\Magento\Framework\App\RequestInterface::class);
  57. }
  58. protected function tearDown()
  59. {
  60. $this->_request = null;
  61. $this->_response = null;
  62. $this->_objectManager = null;
  63. }
  64. /**
  65. * Ensure that there were no error messages displayed on the admin panel
  66. */
  67. protected function assertPostConditions()
  68. {
  69. if ($this->_assertSessionErrors) {
  70. // equalTo() is intentionally used instead of isEmpty() to provide the informative diff
  71. $this->assertSessionMessages(
  72. $this->equalTo([]),
  73. \Magento\Framework\Message\MessageInterface::TYPE_ERROR
  74. );
  75. }
  76. }
  77. /**
  78. * Run request
  79. *
  80. * @param string $uri
  81. */
  82. public function dispatch($uri)
  83. {
  84. $this->getRequest()->setRequestUri($uri);
  85. $this->_getBootstrap()->runApp();
  86. }
  87. /**
  88. * Request getter
  89. *
  90. * @return \Magento\TestFramework\Request
  91. */
  92. public function getRequest()
  93. {
  94. if (!$this->_request) {
  95. $this->_request = $this->_objectManager->get(\Magento\Framework\App\RequestInterface::class);
  96. }
  97. return $this->_request;
  98. }
  99. /**
  100. * Response getter
  101. *
  102. * @return \Magento\TestFramework\Response
  103. */
  104. public function getResponse()
  105. {
  106. if (!$this->_response) {
  107. $this->_response = $this->_objectManager->get(\Magento\Framework\App\ResponseInterface::class);
  108. }
  109. return $this->_response;
  110. }
  111. /**
  112. * Assert that response is '404 Not Found'
  113. */
  114. public function assert404NotFound()
  115. {
  116. $this->assertEquals('noroute', $this->getRequest()->getControllerName());
  117. $this->assertContains('404 Not Found', $this->getResponse()->getBody());
  118. }
  119. /**
  120. * Analyze response object and look for header with specified name, and assert a regex towards its value
  121. *
  122. * @param string $headerName
  123. * @param string $valueRegex
  124. * @throws \PHPUnit_Framework_AssertionFailedError when header not found
  125. */
  126. public function assertHeaderPcre($headerName, $valueRegex)
  127. {
  128. $headerFound = false;
  129. $headers = $this->getResponse()->getHeaders();
  130. foreach ($headers as $header) {
  131. if ($header->getFieldName() === $headerName) {
  132. $headerFound = true;
  133. $this->assertRegExp($valueRegex, $header->getFieldValue());
  134. }
  135. }
  136. if (!$headerFound) {
  137. $this->fail("Header '{$headerName}' was not found. Headers dump:\n" . var_export($headers, 1));
  138. }
  139. }
  140. /**
  141. * Assert that there is a redirect to expected URL.
  142. * Omit expected URL to check that redirect to wherever has been occurred.
  143. * Examples of usage:
  144. * $this->assertRedirect($this->equalTo($expectedUrl));
  145. * $this->assertRedirect($this->stringStartsWith($expectedUrlPrefix));
  146. * $this->assertRedirect($this->stringEndsWith($expectedUrlSuffix));
  147. * $this->assertRedirect($this->stringContains($expectedUrlSubstring));
  148. *
  149. * @param \PHPUnit_Framework_Constraint|null $urlConstraint
  150. */
  151. public function assertRedirect(\PHPUnit_Framework_Constraint $urlConstraint = null)
  152. {
  153. $this->assertTrue($this->getResponse()->isRedirect(), 'Redirect was expected, but none was performed.');
  154. if ($urlConstraint) {
  155. $actualUrl = '';
  156. foreach ($this->getResponse()->getHeaders() as $header) {
  157. if ($header->getFieldName() == 'Location') {
  158. $actualUrl = $header->getFieldValue();
  159. break;
  160. }
  161. }
  162. $this->assertThat($actualUrl, $urlConstraint, 'Redirection URL does not match expectations');
  163. }
  164. }
  165. /**
  166. * Assert that actual session messages meet expectations:
  167. * Usage examples:
  168. * $this->assertSessionMessages($this->isEmpty(), \Magento\Framework\Message\MessageInterface::TYPE_ERROR);
  169. * $this->assertSessionMessages($this->equalTo(['Entity has been saved.'],
  170. * \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS);
  171. *
  172. * @param \PHPUnit_Framework_Constraint $constraint Constraint to compare actual messages against
  173. * @param string|null $messageType Message type filter,
  174. * one of the constants \Magento\Framework\Message\MessageInterface::*
  175. * @param string $messageManagerClass Class of the session model that manages messages
  176. */
  177. public function assertSessionMessages(
  178. \PHPUnit_Framework_Constraint $constraint,
  179. $messageType = null,
  180. $messageManagerClass = \Magento\Framework\Message\Manager::class
  181. ) {
  182. $this->_assertSessionErrors = false;
  183. $messages = $this->getMessages($messageType, $messageManagerClass);
  184. $this->assertThat(
  185. $messages,
  186. $constraint,
  187. 'Session messages do not meet expectations ' . var_export($messages, true)
  188. );
  189. }
  190. /**
  191. * Return all stored messages
  192. *
  193. * @param string|null $messageType
  194. * @param string $messageManagerClass
  195. * @return array
  196. */
  197. protected function getMessages(
  198. $messageType = null,
  199. $messageManagerClass = \Magento\Framework\Message\Manager::class
  200. ) {
  201. return array_merge(
  202. $this->getSessionMessages($messageType, $messageManagerClass),
  203. $this->getCookieMessages($messageType)
  204. );
  205. }
  206. /**
  207. * Return messages stored in session
  208. *
  209. * @param string|null $messageType
  210. * @param string $messageManagerClass
  211. * @return array
  212. */
  213. protected function getSessionMessages(
  214. $messageType = null,
  215. $messageManagerClass = \Magento\Framework\Message\Manager::class
  216. ) {
  217. /** @var $messageManager \Magento\Framework\Message\ManagerInterface */
  218. $messageManager = $this->_objectManager->get($messageManagerClass);
  219. /** @var $messages \Magento\Framework\Message\AbstractMessage[] */
  220. if ($messageType === null) {
  221. $messages = $messageManager->getMessages()->getItems();
  222. } else {
  223. $messages = $messageManager->getMessages()->getItemsByType($messageType);
  224. }
  225. /** @var $messageManager InterpretationStrategyInterface */
  226. $interpretationStrategy = $this->_objectManager->get(InterpretationStrategyInterface::class);
  227. $actualMessages = [];
  228. foreach ($messages as $message) {
  229. $actualMessages[] = $interpretationStrategy->interpret($message);
  230. }
  231. return $actualMessages;
  232. }
  233. /**
  234. * Return messages stored in cookies by type
  235. *
  236. * @param string|null $messageType
  237. * @return array
  238. */
  239. protected function getCookieMessages($messageType = null)
  240. {
  241. /** @var $cookieManager CookieManagerInterface */
  242. $cookieManager = $this->_objectManager->get(CookieManagerInterface::class);
  243. try {
  244. $messages = \Zend_Json::decode(
  245. $cookieManager->getCookie(MessagePlugin::MESSAGES_COOKIES_NAME, \Zend_Json::encode([]))
  246. );
  247. if (!is_array($messages)) {
  248. $messages = [];
  249. }
  250. } catch (\Zend_Json_Exception $e) {
  251. $messages = [];
  252. }
  253. $actualMessages = [];
  254. foreach ($messages as $message) {
  255. if ($messageType === null || $message['type'] == $messageType) {
  256. $actualMessages[] = $message['text'];
  257. }
  258. }
  259. return $actualMessages;
  260. }
  261. }