Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

session_regenerate_id() - headers already sent in unit testing Yii controller

I'm trying to unit-test my controller (Yii framework).

/** 
   * @dataProvider provider
   */
  public function testActionEdit_view_login($controller){
    $user = new CWebUser;
    $user->id = 978;
    $identity = new UserIdentity('[email protected]', '123456');
    $user->login($identity);
    $controller->actionEdit();

    $output = ob_get_contents();
    assertContains('Add/Change Profile Picture:', $output);
    assertContains('bio', $output);
    assertContains('specialties', $output);
    assertContains('change login', $output);
    assertContains('New Password', $output);
  }

When I do

$user->login($identity);

in order to login, I get the following error:

session_regenerate_id(): Cannot regenerate session id - headers already sent

I've already tried buffering the output by putting this at the beginning of the class:

public static function setUpBeforeClass(){
  ob_start();
}

I also put ob_clean() in setUp() and ob_end_clean() in tearDownAfterClass().

Still I get the message that headers have already been sent. There are no spaces or newlines in the file, when I comment out the specific test method, it works perfectly. The login() seems to cause the problem.

Anyone got ideas how to prevent this / maybe unit-test the controller differently?

Thanks, MrB

like image 499
MrB Avatar asked Jul 20 '11 01:07

MrB


2 Answers

Before your call to $user->login, add the following code:

$mockSession = $this->getMock('CHttpSession', array('regenerateID'));
Yii::app()->setComponent('session', $mockSession);

This overwrites the regenerateID method with a method that does nothing.

Adding ob_start() to the bootstrap also works, but there is no output from PHPUnit until everything has completed.

With this method, you can still see the progress as it is happening.

I upgraded from Yii 1.1.7 to 1.1.10 and the regenerateID method was added in 1.1.8 so I got this error today.

like image 51
Matt McCormick Avatar answered Oct 23 '22 05:10

Matt McCormick


Got it. I had included some Yii files before the ob_start(), which seem to have printed the headers. Now I buffer that, too.

like image 39
MrB Avatar answered Oct 23 '22 04:10

MrB