SecurityComponent黑洞我的控制器测试用例

时间:2012-08-24 22:48:05

标签: 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)。

当我进行测试时,我得到了臭名昭着的声明:

  

请求已被黑洞测试案例:   UsersControllerTestCase(testAdminSearchStudents)

我认为这是因为我在没有CSRF令牌和伪造的情况下伪造了一个POST请求?

如果不从控制器中删除安全组件,我应该怎么做才能

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

/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

此致

1 个答案:

答案 0 :(得分:2)

我解决了问题嘲笑 SecurityComponent::_validatePost方法:

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

Dealing with Security component in a CakePHP 2 test case启发