ControllerAuthorizeTest.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. * setup
  31. *
  32. * @return void
  33. */
  34. public function setUp(): void
  35. {
  36. parent::setUp();
  37. $this->controller = $this->getMockBuilder(Controller::class)
  38. ->setMethods(['isAuthorized'])
  39. ->disableOriginalConstructor()
  40. ->getMock();
  41. $this->components = $this->getMockBuilder(ComponentRegistry::class)->getMock();
  42. $this->components->expects($this->any())
  43. ->method('getController')
  44. ->will($this->returnValue($this->controller));
  45. $this->auth = new ControllerAuthorize($this->components);
  46. }
  47. /**
  48. * @return void
  49. */
  50. public function testControllerErrorOnMissingMethod(): void
  51. {
  52. $this->expectException(\Cake\Core\Exception\Exception::class);
  53. $this->auth->controller(new Controller());
  54. $this->auth->authorize([], new ServerRequest());
  55. }
  56. /**
  57. * test failure
  58. *
  59. * @return void
  60. */
  61. public function testAuthorizeFailure(): void
  62. {
  63. $user = [];
  64. $request = new ServerRequest(['url' => '/posts/index']);
  65. $this->assertFalse($this->auth->authorize($user, $request));
  66. }
  67. /**
  68. * test isAuthorized working.
  69. *
  70. * @return void
  71. */
  72. public function testAuthorizeSuccess(): void
  73. {
  74. $user = ['User' => ['username' => 'mark']];
  75. $request = new ServerRequest(['url' => '/posts/index']);
  76. $this->controller->expects($this->once())
  77. ->method('isAuthorized')
  78. ->with($user)
  79. ->will($this->returnValue(true));
  80. $this->assertTrue($this->auth->authorize($user, $request));
  81. }
  82. }