Phpunit image download test

前端 未结 1 1390
自闭症患者
自闭症患者 2021-01-27 17:19

I\'m writing test case to image downloading service written in php. We\'re using phpunit. How can I check if retrieved binary data is an image?

1条回答
  •  南笙
    南笙 (楼主)
    2021-01-27 17:47

    Using exif_imagetype (see manual) is nice, but does require you have to the file on your local disk. If you don't mind hard-coding some magic numbers, you could check for the image type directly, see testFetchWithoutSaving in the next example:

    class ImageTest extends PHPUnit_Framework_TestCase
    {
    
    /**
    * @see http://stackoverflow.com/a/676975/841830
    */
    public function testFetchWithoutSaving(){
        $s=file_get_contents("https://www.google.com/images/srpr/logo3w.png");
        $this->assertEquals("\x89PNG\x0d\x0a\x1a\x0a",substr($s,0,8));
    
        $s=file_get_contents("https://www.google.com/");
        $this->assertEquals("\x89PNG\x0d\x0a\x1a\x0a",substr($s,0,8),"Fails: first 8 bytes are actually 'assertTrue($type!==false);   //Any recognized image type
        $this->assertEquals(IMAGETYPE_PNG,$type);   //A specific image type
        }
    
    }
    

    0 讨论(0)
提交回复
热议问题