Phalcon\Test\Unit\Security\RandomTest::testRandomBase64 PHP Method

testRandomBase64() public method

Tests the random base64 generation
Since: 2015-08-17
Author: Serghei Iakovlev ([email protected])
public testRandomBase64 ( )
    public function testRandomBase64()
    {
        $this->specify("base64 does not generate a valid string", function () {
            $lens = [2, 12, 16, 24, 48, 100];
            $random = new Random();
            $checkSize = function ($base64, $len) {
                // Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4.
                $formula = round(4 * ($len / 3)) % 4 === 0 ? round(4 * ($len / 3)) : round((4 * ($len / 3) + 4 / 2) / 4) * 4;
                return strlen($base64) == $formula;
            };
            $isValid = function ($base64) {
                return preg_match("#[^a-z0-9+_=/-]+#i", $base64) === 0;
            };
            foreach ($lens as $len) {
                $actual = $random->base64($len);
                expect($checkSize($actual, $len))->true();
                expect($isValid($actual))->true();
            }
            $actual = $random->base64();
            expect($checkSize($actual, 16))->true();
            expect($isValid($actual))->true();
        });
    }