Ata*_*xia 4 php random phpunit unit-testing pass-by-reference
我有一个方法可以调用内置的 PHP 函数openssl_random_pseudo_bytes.
public function generateRandomBytes()
{
$crypto_secure = TRUE;
// $crypto_secure is passed by reference and will be set to FALSE by
// openssl_random_pseudo_bytes if it uses an insecure algorithm
$random_bytes = openssl_random_pseudo_bytes(16, $crypto_secure);
if (!$crypto_secure)
{
throw new Security_Exception('Random bytes not generated by a cryptographically secure PRNG algorithm');
}
return $random_bytes;
}
Run Code Online (Sandbox Code Playgroud)
我有一个 PHPUnit 测试用例来测试这个方法(它所做的只是验证随机生成的字符串是 16 个字节长)。
public function testRandomBytesLength()
{
$myclass = new MyClass();
$this->assertEquals(16, strlen($myclass->generateRandomBytes()));
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何测试$crypto_secureFALSE 并且必须抛出异常的情况?由于此值作为对 的引用传入并修改openssl_random_pseudo_bytes,因此我不确定如何获得此执行路径的测试覆盖率。我的第一个想法是,也许有一个 php.ini 配置可以用来强制openssl_random_pseudo_bytes使用加密不安全的算法(通过ini_set在测试用例中)。有什么建议?
一种选择是将您的代码抽象出来,以便您可以模拟 openssl 方法的返回值:
public function generateRandomBytes()
{
$crypto_secure = TRUE;
$random_bytes = $this->randomPseudoBytes(16, $crypto_secure);
if (!$crypto_secure)
{
throw new Security_Exception('Random bytes not generated by a cryptographically secure PRNG algorithm');
}
return $random_bytes;
}
protected function randomPseudoBytes($length, &$crypto_secure)
{
return openssl_random_pseudo_bytes(16, $crypto_secure);
}
Run Code Online (Sandbox Code Playgroud)
然后你可以控制核心函数周围的包装器来测试你的代码如何对它的变化做出反应:
/**
* @expectedException Security_Exception
* @expectedExceptionMessage Random bytes not generated by a cryptographically secure PRNG algorithm
*/
public function testCryptoIsNotSecure()
{
$myclass = $this->getMockBuilder(MyClass::class)->setMethods(['randomPseudoBytes'])->getMock();
$myclass->expects($this->once())
->method('randomPseudoBytes')
->will($this->returnCallback(function ($length, &$secure) {
// Mock variable assignment via reference
$secure = false;
});
$myclass->generateRandomBytes();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
348 次 |
| 最近记录: |