SecurityComponent 黑洞我的 Controller 测试用例

标签 security unit-testing cakephp phpunit

这是我的UsersController测试用例:

<?php
App::uses('UsersController', 'Controller');

class TestUsersController extends UsersController {

    public $autoRender = false;

    public function redirect($url, $status = null, $exit = true) {
        $this->redirectUrl = $url;
    }

    public function render($action = null, $layout = null, $file = null) {
        $this->renderedAction = $action;
    }

    public function _stop($status = 0) {
        $this->stopped = $status;
    }
}

class UsersControllerTestCase extends ControllerTestCase {

    public $fixtures = array('app.user');

    public function setUp() {
        parent::setUp();
        $this->Users = new TestUsersController();
        $this->Users->constructClasses();
    }

    public function tearDown() {
        unset($this->Users);

        parent::tearDown();
    }

    public function testAdminSearchStudents() {
        $data = array('User' => array('search' => 'Ipsum'));
        $result = $this->testAction('/admin', array('return' => 'vars', 'method' => 'post', 'data' => $data));
        $this->assertCount(1, $result['users']);
    }

}

我的 UsersController 没有什么特别的,但它使用了 SecurityComponent(继承自 AppController)。

当我运行测试时,我得到了臭名昭著的结果:

The request has been black-holed Test case: UsersControllerTestCase(testAdminSearchStudents)

我认为这是因为我在没有 CSRF token 和引用的情况下伪造了 POST 请求?

我应该怎样做才能在不从 Controller 中删除安全组件的情况下完成这项工作?

我不确定这是否有帮助,但这是堆栈跟踪的重要部分:

/var/www/source/cakephp/lib/Cake/Controller/Component/SecurityComponent.php : 230
SecurityComponent::startup
/var/www/source/cakephp/lib/Cake/Utility/ObjectCollection.php : 130
ObjectCollection::trigger
/var/www/source/cakephp/lib/Cake/Event/CakeEventManager.php : 246
/var/www/source/cakephp/lib/Cake/Controller/Controller.php : 671
/var/www/source/cakephp/lib/Cake/Routing/Dispatcher.php : 183
/var/www/source/cakephp/lib/Cake/Routing/Dispatcher.php : 161
/var/www/source/cakephp/lib/Cake/TestSuite/ControllerTestCase.php : 271
ControllerTestCase::_testAction
/var/www/source/cakephp/lib/Cake/TestSuite/ControllerTestCase.php : 189

问候

最佳答案

我解决了模拟 SecurityComponent::_validatePost 方法的问题:

$this->Users = $this->generate('Users', array(
    'components' => array(
        'Security' => array('_validatePost'),
    )
));

灵感来自Dealing with Security component in a CakePHP 2 test case

关于SecurityComponent 黑洞我的 Controller 测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12117598/

相关文章:

asp.net-mvc - 使用 Asp Net SqlRoleProvider 处理 ASP.NET MVC 中拒绝的安全性

java - 在Java控制面板中隐藏 "security warning message"

c# - 使用 Moq 验证委托(delegate)

unit-testing - 实体的模拟 RestTemplate 帖子

php - 即使 CakePhp3 中没有错误也无法保存实体

java - 为什么 String 是 Final 使应用程序更安全?

javascript - 使用 jwt 正确验证用户身份并防止攻击

c# - 使用 nMoq,人们对给定的事件有何期望?

php - 将带过滤器的 SVG 图像转换为 PNG/PDF

mysql - cakephp 变量在索引/ View 中可用,但在 Controller 中不可用