ControllerAuthorizeTest.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * ControllerAuthorizeTest file
  5. *
  6. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  7. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  8. *
  9. * Licensed under The MIT License
  10. * For full copyright and license information, please see the LICENSE.txt
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  14. * @link https://cakephp.org CakePHP(tm) Project
  15. * @since 2.0.0
  16. * @license https://opensource.org/licenses/mit-license.php MIT License
  17. */
  18. namespace Cake\Test\TestCase\Auth;
  19. use Cake\Auth\ControllerAuthorize;
  20. use Cake\Controller\ComponentRegistry;
  21. use Cake\Controller\Controller;
  22. use Cake\Http\ServerRequest;
  23. use Cake\TestSuite\TestCase;
  24. /**
  25. * ControllerAuthorizeTest
  26. */
  27. class ControllerAuthorizeTest extends TestCase
  28. {
  29. /**
  30. * @var \Cake\Controller\Controller|\PHPUnit\Framework\MockObject\MockObject
  31. */
  32. protected $controller;
  33. /**
  34. * @var \Cake\Auth\ControllerAuthorize
  35. */
  36. protected $auth;
  37. /**
  38. * setup
  39. */
  40. public function setUp(): void
  41. {
  42. parent::setUp();
  43. $this->controller = $this->getMockBuilder(Controller::class)
  44. ->addMethods(['isAuthorized'])
  45. ->disableOriginalConstructor()
  46. ->getMock();
  47. $components = new ComponentRegistry($this->controller);
  48. $this->auth = new ControllerAuthorize($components);
  49. }
  50. public function testControllerErrorOnMissingMethod(): void
  51. {
  52. $this->expectException(\Cake\Core\Exception\CakeException::class);
  53. $this->auth->controller(new Controller());
  54. $this->auth->authorize([], new ServerRequest());
  55. }
  56. /**
  57. * test failure
  58. */
  59. public function testAuthorizeFailure(): void
  60. {
  61. $user = [];
  62. $request = new ServerRequest(['url' => '/posts/index']);
  63. $this->assertFalse($this->auth->authorize($user, $request));
  64. }
  65. /**
  66. * test isAuthorized working.
  67. */
  68. public function testAuthorizeSuccess(): void
  69. {
  70. $user = ['User' => ['username' => 'mark']];
  71. $request = new ServerRequest(['url' => '/posts/index']);
  72. $this->controller->expects($this->once())
  73. ->method('isAuthorized')
  74. ->will($this->returnValue(true));
  75. $this->assertTrue($this->auth->authorize($user, $request));
  76. }
  77. }