采用int的Python ctypes-wrapped函数无法拒绝大于INT_MAX

时间:2017-03-26 23:48:46

标签: python c ctypes

在64位Linux上使用Python 2.7.13进行测试。

我在共享对象中有一个C函数。此函数需要两个int并返回int。当我尝试从Python端传递一个大于INT_MAX但仍可表示为 unsigned int的整数时,我不会像我那样得到Python端异常期望的。

// add.c
int add(int a, int b)
{
    return a + b;
}

使用以下选项将此文件编译为共享对象。 (来自makefile的片段)

gcc -shared -fPIC add.c -o add.so

我使用以下python脚本test_add.c来测试代码。我可能做了比必要工作更多的工作,手动提供ctypes.c_int的参数类型并手动强制假设生成的整数,但看起来这些操作中的任何一个都不应该导致我的行为I&I #39;我看到了。

以下是我尝试使用xy的不同值的主要测试。失败的测试用例的一个示例是x=0y=2147483648,比INT_MAX大一号。

try:
    s = add(ctypes.c_int(x), ctypes.c_int(y))
except Exception:
    return

# if no exception was thrown, python and C should agree
# about the result of the addition
assert s == (x + y)

为了完整起见,这里的脚本已经完整了:

import ctypes
import os.path
import unittest

from hypothesis import given
import hypothesis.strategies as st

# import shared object from this directory
addso_path = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + "add.so"
addso = ctypes.cdll.LoadLibrary(addso_path)

# extract add symbol, explicitly force its argument types to be
# (int, int)
# and return type to be
# int
add = addso.add
add.argtypes = [ctypes.c_int, ctypes.c_int]
add.restype = ctypes.c_int

class TestAddition(unittest.TestCase):
    @given(x=st.integers(), y=st.integers())
    def test_add(self, x, y):
        # if we catch any error on the python side,
        # then that counts as successfully preventing an
        # out-of-bounds integer before it is passed to C
        try:
            s = add(ctypes.c_int(x), ctypes.c_int(y))
        except Exception:
            return

        # if no exception was thrown, python and C should
        # agree about the result of the addition
        assert s == (x + y)


if __name__ == "__main__":
    unittest.main()

这是测试套件的输出:

Falsifying example: test_add(self=<__main__.TestAddition testMethod=test_add>, x=0, y=2147483648)
F
======================================================================
FAIL: test_add (__main__.TestAddition)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_add.py", line 22, in test_add
    def test_add(self, x, y):
  File "/.../opt/c-add/venv/lib/python2.7/site-packages/hypothesis/core.py", line 525, in wrapped_test
    print_example=True, is_final=True
  File "/...opt/c-add/venv/lib/python2.7/site-packages/hypothesis/executors.py", line 58, in default_new_style_executor
    return function(data)
  File "/.../opt/c-add/venv/lib/python2.7/site-packages/hypothesis/core.py", line 112, in run
    return test(*args, **kwargs)
  File "test_add.py", line 33, in test_add
    assert s == (x + y)
AssertionError

0 个答案:

没有答案