2013-05-10 66 views
6

考虑以下代码:CakePHP的控制器测试与安全组件

控制器代码

<?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'); 

因为我已经制定了安全组件,篡改以任何方式(如向其添加字段)都会导致请求为黑色-h OLED。我想测试:

测试代码

<?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

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

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

如果你坚持,虽然,检查出的核心蛋糕测试指导:

具体做法是:

/** 
* 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

+0

这个答案让我想起只检查视图在GET上返回的内容的可能性,并查看它是否包含不应该可编辑的字段。然后,知道安全组件已启用,我知道我很安全。但我认为我的测试仍然有意义,因为测试不关心你的实现是什么;测试只关心结果。因此,发布不应该可编辑的字段的结果应该导致错误,无论是否由安全组件生成(测试不关心)。但我认为这个答案足够了。谢谢! – Nick 2013-05-28 05:44:01