gpt4 book ai didi

php - 如何通过更改通过引用传递的参数来对调用具有副作用的函数的方法进行单元测试?

转载 作者:可可西里 更新时间:2023-10-31 22:50:25 26 4
gpt4 key购买 nike

我有一个调用内置 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;
}

我有一个 PHPUnit 测试用例来测试这个方法(它所做的只是验证随机生成的字符串是否为 16 字节长)。

public function testRandomBytesLength()
{
$myclass = new MyClass();

$this->assertEquals(16, strlen($myclass->generateRandomBytes()));
}

我的问题是,如何测试 $crypto_secure 为 FALSE 且必须抛出异常的情况?由于此值是作为对 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);
}

然后您可以控制核心函数周围的包装器来测试您的代码如何对其变化使用react:

/**
* @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();
}

关于php - 如何通过更改通过引用传递的参数来对调用具有副作用的函数的方法进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52540937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com