gpt4 book ai didi

使用安全组件进行 CakePHP Controller 测试

转载 作者:行者123 更新时间:2023-11-28 19:47:40 24 4
gpt4 key购买 nike

考虑这段代码:

Controller 代码

<?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 数组中,但它通过了!我做错了什么?

最佳答案

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

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

如果您坚持,请查看核心 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

关于使用安全组件进行 CakePHP Controller 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16487545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com