CakePHP的 - 控制器测试失败,因为安全的组成部分(CakePHP - Controller

2019-10-23 07:28发布

我想给测试控制器方法(添加,编辑,...)使用安全组件。

ContactsController

public function initialize() {
    $this->loadComponent('Security');
}

public function add() {
    $contact = $this->Contacts->newEntity();
    if ($this->request->is('post')) {
        $contact = $this->Contacts->patchEntity($contact, $this->request->data);
        if ($this->Contacts->save($contact)) {
            $this->Flash->success(__d('contact_manager', 'The contact has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__d('contact_manager', 'The contact could not be saved. Please, try again.'));
        }
    }
    $this->set(compact('contact'));
    $this->set('_serialize', ['contact']);
}

ContactsControllerTest

public function testAdd() {
    $data = $this->_getData();
    $this->post('/contacts/add', $data);
    $this->assertResponseSuccess();

    $query = $this->Contacts->find()->where([
        'Profiles.lastname' => $data['profile']['lastname'],
        'Profiles.firstname' => $data['profile']['firstname']
    ]);
    $this->assertEquals(1, $query->count());
}

protected function _getData() {
    $data = [
        'id' => '',
        'organization_id' => 2,
        'profile_id' => '',
        'profile' => [
            'lastname' => 'Demo',
            'firstname' => 'Demo',
            'gender' => 'f',
            'birthday' => '1990-05-20',
            'email' => 'demo@demo.com',
            'phone' => '0102030405',
            'phone_mobile' => '0607080900'
        ]
    ];
    return $data;
}

testAdd()总是失败,因为请求是黑色带孔(与“验证”指标),但add()在浏览器中运行良好。

Answer 1:

这是可以预料的,因为你不发送必要的安全令牌,这是安全组件需要。

只要看看你生成的表单,它将包含隐藏的输入为_Token场,与子项fieldsunlocked ,其中fields将包含一个散列并锁定领域的可能名称,并unlocked持有解锁字段的名称。

只需将令牌数据添加到您的要求,一切都应该罚款。 下面是一个例子

$data = [
    'id' => '',
    'organization_id' => 2,
    'profile_id' => '',
    'profile' => [
        'lastname' => 'Demo',
        // ...
    ],
    '_Token' => [
        'fields' => 'e87e3ad9579abcd289ccec2a7a42065b338cacd0%3Aid'
        'unlocked' => ''
    ]
];

需要注意的是unlocked必须存在,即使它不包含任何数据!

你应该能够简单地标记值生成表单副本,如果你有兴趣在如何生成和验证令牌,看看FormHelper::secure() FormHelper::_secure()SecurityComponent::_validatePost()

另见食谱>控制器>组件>安全



Answer 2:

由于蛋糕3.1.2最好的办法是增加

$this->enableCsrfToken();
$this->enableSecurityToken();

您TestFunction。

质地: https://book.cakephp.org/3.0/en/development/testing.html#testing-actions-protected-by-csrfcomponent-or-securitycomponent



文章来源: CakePHP - Controller testing failed because of Security component