A typical Developer Blog
by Gordon Franke
Icon

How can i override user attribute in my functional test?

Some times your code depend on a user attribute, so you want set the user attribute in your functional test.

The Problem is that the doCall method in the sfBrowser class rebuild the context and in the end calls theshutdown method from user and storage object to write the session data.

So you must create your own Browser class and override the doCall function and simple move the shutdown calls to the beginning.

Browser Class:

class myBrowser extends sfBrowser
{
  /**
   * Calls a request to a uri.
   */
  protected function doCall()
  {
    // manually shutdown user to save current session data
    if (isset($this->context) AND $this->context->getUser())
    {
      $this->context->getUser()->shutdown();
      $this->context->getStorage()->shutdown();
    }
 
    // recycle our context object
    $this->context = $this->getContext(true);
 
    sfConfig::set('sf_test', true);
 
    // we register a fake rendering filter
    sfConfig::set('sf_rendering_filter', array('sfFakeRenderingFilter', null));
 
    $this->resetCurrentException();
 
    // dispatch our request
    ob_start();
    $this->context->getController()->dispatch();
    $retval = ob_get_clean();
 
    // append retval to the response content
    $this->context->getResponse()->setContent($retval);
  }
}

Test code:

include dirname(__FILE__).'/../../bootstrap/functional.php';
 
$browser = new sfTestFunctional(new myBrowser());
 
$browser->
  get('/site-one');
 
// override the session data
$browser->getUser()->setAttribute('key', $value);
 
$browser->
  get('/site-one');

How can i unit test my own User class functions?

Use this in your testcode to create the user object

1
2
3
4
5
6
7
8
$_SERVER['session_id'] = 'test';
 
$dispatcher = new sfEventDispatcher();
$sessionPath = sfToolkit::getTmpDir().'/sessions_'.rand(11111, 99999);
$storage = new sfSessionTestStorage(array('session_path' => $sessionPath));
 
$myUser = new myUser($dispatcher, $storage);
$myUser->setAttribute('user_id', 1, 'sfGuardSecurityUser');