Phpunit图像下载测试 [英] Phpunit image download test
本文介绍了Phpunit图像下载测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用php编写的图像下载服务编写测试用例。我们正在使用phpunit。如何检查检索到的二进制数据是否为图像?
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?
推荐答案
使用 exif_imagetype
(参见手册)很不错,但确实需要你本地磁盘上的文件。如果您不介意对某些幻数进行硬编码,可以直接检查图像类型,请参阅下一个示例中的 testFetchWithoutSaving
:
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 '<!doctyp'");
}
/**
* @see http://php.net/manual/en/function.exif-imagetype.php
*/
public function testFetchWithTempFile(){
$s=file_get_contents("https://www.google.com/images/srpr/logo3w.png");
$tempFilename="/tmp/phpunit.testImage.testFetchWithTempFile";
file_put_contents($tempFilename,$s);
$type=exif_imagetype($tempFilename);
unlink($tempFilename);
$this->assertTrue($type!==false); //Any recognized image type
$this->assertEquals(IMAGETYPE_PNG,$type); //A specific image type
}
}
这篇关于Phpunit图像下载测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文