ControllerAuthorizeTest.php 2.5 KB

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