mardi 23 décembre 2014

CakePHP2: Writing test for Controller which uses Auth and Session component

I've a controller for managing user authentication and related actions and want to test their combined functionality with Cakes unit test on the terminal:



  • login with "old" password

  • reset the password (will receive a reset token)

  • reset password with the token

  • login in with "new" password


Here's a simple snipped I'm trying to get work:



$this->_testAction('/user/login', [
'data' => [
'User' => [
'username' => '...',
'passwd' => '...',
...
]);


I'm running into problems with the AuthComponent. Through debugging so far I found that \AuthComponent::login() properly "gets" the user when calling ->identify() but $this->Session->write() doesn't actually work which later prevents \AuthComponent::user() from properly returning the user.


Under the hood it's calling \CakeSession::write() which in turn works directly with $_SESSION which probably does not work on the CLI. The write() method returns false but this isn't caught anywhere.


I've read Unit testing the Auth Component which mocks a specific user id in the callback, but I truly want the AuthComponent to succeed on its own for my tests and return my what it gets from the fixture; on it's own. This is important for when logging in with the new/changed password.


On top of my head I see two possibilities:



  • replace existing components with my own which handle these cases more gracefully, e.g. trying to override the SessionComponent used my the AuthComponent

  • mock the hell out of the classes to get to my goal


I've a few ideas but no actual starting point for either way. I'm not aware how or if it's possible to "replace" components with my own implementation, e.g. replace SessionComponent everywhere with my OwnSessionComponent.


Or when mocking e.g. the AuthComponent, I'm not sure what I should mock for e.g. \AuthComponent::user() to get the real authenticated user of my tests back and not force a hardcoded return user value.


Aucun commentaire:

Enregistrer un commentaire