Page 1 of 1

Testing sending headers

Posted: Sat May 10, 2008 2:54 pm
by onion2k
I'm attempting to write a test to check a method that should send an image Content-Type header to the user's browser, but I'm running into an exception..

Code: Select all

Exception: All DataStore tests -> C:\xampp\htdocs\pictooer\version1\test/unit/image.test.php -> ImageTest -> testOpenAndOutputImage_JPEG -> Unexpected PHP error [Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\simpletest\reporter.php:43)] severity [E_WARNING] in [C:\xampp\htdocs\pictooer\version1\base\image\image.class.php line 52]
How can I either test the method without getting the exception, or suppress the header being sent (not ideal really..).

My test code:

Code: Select all

 
public function testOpenAndOutputImage_JPEG() {
 
    $image = new image();
    $image->openImage(TEST_BASE.DIRECTORY_SEPARATOR."image.jpg");
    $this->assertEqual(get_resource_type($image->image), "gd");
    ob_start();
    $image->imageJpeg();
    $image_data = ob_get_contents();
    ob_end_clean();
 
}
The imageJpeg() method is what's sending the header. I'm planning on comparing the image data in $image_data to the contents of a file containing what imageJpeg should make, but I haven't got that far yet.

Re: Testing sending headers

Posted: Sat May 10, 2008 7:46 pm
by Chris Corbyn
That's a problem really. I don't know if it's going to be possible for you to do, but having a Response object solves that. You "queue" headers in the response (just an array), and you add content. Then when you're done you commit it and send it to the browser. For the purposes of testing you'd want to mock the response and check what headers are set in it, or use a real response but never commit it.

Code: Select all

public function testOpenAndOutputImage_JPEG() {
 
    $response = new Response(); //Using a real response here
    $image = new image($response);
    $image->openImage(TEST_BASE.DIRECTORY_SEPARATOR."image.jpg");
    $this->assertEqual(get_resource_type($image->image), "gd");
    $image->imageJpeg();
    $image_data = $response->getContent();
 
}
If you were using a mock you'd expectOnce('setContent').

I'm guessing this is sort of beyond your control if the GD functions send headers?

Re: Testing sending headers

Posted: Sun May 11, 2008 9:40 pm
by Jenk
Has been ages since I have used it, but are headers retrievable from ob_get_contents() ?

Perhaps even if they are, write yourself a very basic wrapper class that you can functionally test (i.e. manually) and then mock it. Something like:

Code: Select all

class HeaderWrapper {
  public function sendHeader($aString) {
    header($aString);
  }
}
Not all testing has to be automated :)

Re: Testing sending headers

Posted: Tue May 13, 2008 1:55 pm
by McGruff
Maybe the SimpleTest web tester and assertHeader() can help.