使用安全组件进行CakePHP控制器测试

时间:2013-05-10 17:14:21

标签: cakephp testing

考虑以下代码:

控制器代码

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

class UsersController extends AppController {

    public $components = array(
        'Security',
        'Session'
    );

    public function example() {
        if ($this->request->is('post')) {
            $this->set('some_var', true);
        }
    }
}

查看代码

<?php

echo $this->Form->create();
echo $this->Form->input('name');
echo $this->Form->end('Submit');

由于我已安装了安全组件,因此以任何方式篡改表单(例如向其添加字段)都会导致请求被黑屏。我想测试一下:

测试代码

<?php

class UsersControllerTest extends ControllerTestCase {

    public function testExamplePostValidData() {
        $this->Controller = $this->generate('Users', array(
            'components' => array(
                'Security'
            )
        ));

        $data = array(
            'User' => array(
                'name' => 'John Doe'
            )
        );

        $this->testAction('/users/example', array('data' => $data, 'method' => 'post'));
        $this->assertTrue($this->vars['some_var']);
    }

    public function testExamplePostInvalidData() {
        $this->Controller = $this->generate('Users', array(
            'components' => array(
                'Security'
            )
        ));

        $data = array(
            'User' => array(
                'name' => 'John Doe',
                'some_field' => 'The existence of this should cause the request to be black-holed.'
            )
        );

        $this->testAction('/users/example', array('data' => $data, 'method' => 'post'));
        $this->assertTrue($this->vars['some_var']);
    }
}

第二个测试testExamplePostInvalidData应该失败,因为some_field$data数组中,但它通过了!我做错了什么?

1 个答案:

答案 0 :(得分:1)

通过在 - &gt; testAction的数据中添加'some_field',安全组件将假定该字段是您的应用程序的一部分(因为它来自您的代码,而不是POST数组)所以它不会被看到作为“黑客企图”。

检查黑洞有点复杂。但Cake核心测试已经测试了blackhole功能,所以如果这些测试通过,你不需要在你的应用程序中检查它。

如果您坚持,请查看核心蛋糕测试以获取指导:

具体做法是:

/**
 * test that validatePost fails if any of its required fields are missing.
 *
 * @return void
 */
public function testValidatePostFormHacking() {
    $this->Controller->Security->startup($this->Controller);
    $key = $this->Controller->params['_Token']['key'];
    $unlocked = '';

    $this->Controller->request->data = array(
        'Model' => array('username' => 'nate', 'password' => 'foo', 'valid' => '0'),
        '_Token' => compact('key', 'unlocked')
    );
    $result = $this->Controller->Security->validatePost($this->Controller);
    $this->assertFalse($result, 'validatePost passed when fields were missing. %s');
}

文件中有更多例子:
https://github.com/cakephp/cakephp/blob/master/lib/Cake/Test/Case/Controller/Component/SecurityComponentTest.php