jeudi 27 septembre 2018

PHPUnit test coverage for condition triggered by reference

I have a method that makes a call to a builtin PHP function, openssl_random_pseudo_bytes.

public function generateRandomBytes()
{
    $crypto_secure = TRUE;
    $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;
}

I have one PHPUnit test case to test this method (all it does is verify that the randomly generated string is 16 bytes long).

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

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

My question is, how do I test the case in which $crypto_secure is FALSE and an exception must be thrown? Since this value is passed in and modified as a reference to openssl_random_pseudo_bytes, I'm not sure how I could get test coverage for this execution path. My first thought was that maybe there's a php.ini configuration that I could use to force openssl_random_pseudo_bytes to use a cryptographically insecure algorithm (via ini_set in the test case). Any suggestions?




Aucun commentaire:

Enregistrer un commentaire