我正在为UsersController编写单元测试,以便用户只能编辑自己的配置文件。我正在使用CakePHP 2.4.2和AuthComponent与Controller授权来执行此操作。
验证配置:
public $components = array(
'Auth' => array(
'loginRedirect' => '/',
'logoutRedirect' => '/',
'authenticate' => array('Ldap'),
'authError' => 'You are not allowed to access this page',
'authorize' => 'Controller'));
用户控制器中的isAuthorized():
public function isAuthorized($user = null) {
if($this->Auth->loggedIn()) {
return $this->request->params['pass'][0] == $user['id'];
}
return false;
}
编辑的单元测试:
public function testEdit() {
$result = $this->testAction('/users/view/1', array('return' => 'view'));
$this->assertRegExp('/Adam C Hobaugh/', $result);
$user = $this->generate('Users', array(
'components' => array(
'Session',
'Auth' => array('user'))));
$test = array('id' => 1);
$user->Auth->expects($this->once())->method('loggedIn')
->with($this->returnValue(true));
$user->Auth->expects($this->any())->method('user')
->with($this->returnValue($test));
$user->Session->expects($this->any())->method('setFlash');
$result = $this->testAction('/users/edit/1', array(
'return' => 'headers',
'data' => array('User' => array( {user array} ))));
debug($result);
$this->assertContains('/users', @$result['Location']);
$result = $this->testAction('/users/view/1', array('return' => 'view'));
$this->assertRegExp('/John Jacob Doe/', $result);
}
我在运行测试时得到Expectation failed for method name is equal to <string:loggedIn> when invoked 1 time(s). Method was expected to be called 1 times, actually called 0 times.
。此外,当我将this-&gt; once()更改为$ this-&gt; any()并将$ test数组中的id更改为2时,这种情况应该失败并且从浏览器中执行,它成功通过了测试。
有了这些组合,似乎在单元测试期间没有调用isAuthorized()。我很茫然。感谢您提供的任何帮助。
答案 0 :(得分:-2)
首先:在测试代码中,您调用view方法而不是编辑方法
第二:isAuthorized()不是为了这个。使用此方法,您应该只定义谁可以访问哪些函数,不应该有任何应用程序业务逻辑。
第三:如果你想限制普通用户只编辑他们自己的个人资料,你应该将dit()方法改为这样的。
public function edit() {
$this->request->data['User']['id'] = $this->Auth->User('id');
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = array('User' => $this->Auth->User());
}
}
并删除echo $ this-&gt; Form-&gt; input('id');从你的编辑视图。
我正在写一本关于这个主题的书。它很快就会出现:https://leanpub.com/CakePHPUserAuthentication/