Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing integer overflow in PHP

I have a unit test that is used to test variable conversions from string to integer. So far it's good, except for the last one.

$_GET['name'] = '42000000000000000000000000000000000000';
$text = $input->get( 'name', Convert::T_INTEGER );
$this->assertEquals( 92233720368547755807, $text );

The expectancy is (which is confirmed by the test itself), is that the large value, when converted from string to integer using intval() causes an overflow which defaults to the largest integer value that php can handle on my system. Yet, it still fails:

Failed asserting that <integer:92233720368547755807> matches expected <double:9.2233720368548E+19>

And when I try to force the expected number into an integer:

$this->assertEquals( intval(92233720368547755807), $text );

I get this:

Failed asserting that <integer:92233720368547755807> matches expected <integer:0>

Which is what the test run literally right before this one tests for...

Relevant code:

public function get( $name, $type = null )
{
    $value = $_GET['value'];
    if( !is_null( $type ) )
        $value = Convert::to( $value, $type );
    return $value;
}

And

public static function to( $value, $type )
{
    switch( $type )
    {
        case self::T_INTEGER:
            return intval( $value );
        default:
            return null;
    }
}

So the question is this: How do I get this test to return positive?

like image 919
Mike S Avatar asked Sep 29 '26 05:09

Mike S


2 Answers

Use the PHP_INT_MAX constant:

$this->assertEquals( PHP_INT_MAX, $text );

This will fix your problem, AND make your test more portable (e.g. it will work on 32bit systems too).

PHP_INT_MAX's value is the larger representable int by your PHP build.

See http://php.net/manual/en/reserved.constants.php

like image 65
Arnaud Le Blanc Avatar answered Oct 01 '26 18:10

Arnaud Le Blanc


You have an extra 5 in your number. This:

92233720368547755807

Should be this:

9223372036854775807
like image 39
John Kugelman Avatar answered Oct 01 '26 17:10

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!