Here are some tests functions I wrote for testing the validity of the access control lists of my website. Nothing fancy but it’s an exemple that may be usefull for begginners.

  1. private function CanAccess($url)
  2. {
  3. $this->dispatch($url);
  4. $this->assertNotResponseCode(‘404’);
  5. list($controller, $action) = explode(“/”, ereg_replace(“^/”, “”, $url));
  6. $this->assertController($controller);
  7. $this->assertAction($action);
  8. }
  9. private function CanNotAccess($url)
  10. {
  11. $this->dispatch($url);
  12. // if the user is Guest
  13. if(!Zend_Auth::getInstance()->hasIdentity())
  14. {
  15. $this->assertController(‘user’);
  16. $this->assertAction(‘login’);
  17. // CustomAclManager Should show a Login form
  18. $this->assertQueryCountMin(‘form’, 1);
  19. $this->assertQueryCountMin(‘input[name~=”email”]’, 1);
  20. $this->assertQueryCountMin(‘input[name~=”password”]’, 1);
  21. $this->assertQueryCountMin(‘input[name~=”submit”]’, 1);
  22. }
  23. // If user is logged In he’ll only get redirected
  24. else
  25. $this->assertRedirect;
  26. }
  27. private function LoginRealUser()
  28. {
  29. $this->request->setMethod(‘POST’)
  30. ->setPost(array(
  31. ’email’ => ‘regularuser@nowhere.com’,
  32. ‘password’ => ‘usertests’,
  33. ));
  34. $this->dispatch(‘/user/login’);
  35. $this->assertRedirect;
  36. $this->assertTrue(Zend_Auth::getInstance()->hasIdentity());
  37. }
  38. // ok, now let’s run some tests
  39. public function testGuestAccessRightsAreOk()
  40. {
  41. $this->CanAccess(‘/user/login’);
  42. }
  43. public function testLoggedInUserAccessRightsAreOk()
  44. {
  45. $this->LoginRealUser();
  46. $this->CanAccess(‘/user/logout’);
  47. }
  48. // testing where users can not go
  49. public function testGuestRestrictionsAreOk()
  50. {
  51. $this->CanNotAccess(‘/user/logout’);
  52. $this->CanNotAccess(‘/user/index’);
  53. }
  54. public function testLoggedInRestrictionsAreOk()
  55. {
  56. $this->LoginRealUser();
  57. $this->CanNotAccess(‘/user/login’);
  58. }

A simple way to test your user access rights !

Advertisements