在PHP中测试整数溢出

Mik*_*e S 3 php testing integer overflow

我有一个单元测试,用于测试从字符串到整数的变量转换.到目前为止它很好,除了最后一个.

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

预期是(由测试本身确认),是大值,当使用intval()从字符串转换为整数时会导致溢出,默认为php可以在我的系统上处理的最大整数值.然而,它仍然失败:

Failed asserting that <integer:92233720368547755807> matches expected <double:9.2233720368548E+19>
Run Code Online (Sandbox Code Playgroud)

当我尝试将预期数字强制为整数时:

$this->assertEquals( intval(92233720368547755807), $text );
Run Code Online (Sandbox Code Playgroud)

我明白了:

Failed asserting that <integer:92233720368547755807> matches expected <integer:0>
Run Code Online (Sandbox Code Playgroud)

在测试之前,测试运行的正是这个...

相关代码:

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

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

所以问题是:我如何让这个测试返回正面?

Arn*_*anc 5

使用PHP_INT_MAX常量:

$this->assertEquals( PHP_INT_MAX, $text );
Run Code Online (Sandbox Code Playgroud)

这将解决您的问题,并使您的测试更便携(例如,它也适用于32位系统).

PHP_INT_MAX的值是intPHP构建可表示的较大值.

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