| 1 |
import sys |
| 2 |
|
| 3 |
import pytest |
| 4 |
|
| 5 |
from pypy.tool.cpyext.extbuild import SystemCompilationInfo, HERE |
| 6 |
from pypy.interpreter.gateway import unwrap_spec, interp2app |
| 7 |
from pypy.interpreter.error import OperationError |
| 8 |
from rpython.rtyper.lltypesystem import lltype |
| 9 |
from pypy.module.cpyext import api |
| 10 |
from pypy.module.cpyext.api import cts, create_extension_module, exec_extension_module |
| 11 |
from pypy.module.cpyext.pyobject import from_ref |
| 12 |
from pypy.module.cpyext.state import State |
| 13 |
from rpython.tool import leakfinder |
| 14 |
from rpython.rlib import rawrefcount |
| 15 |
from rpython.tool.udir import udir |
| 16 |
|
| 17 |
import pypy.module.cpyext.moduledef |
| 18 |
|
| 19 |
only_pypy ="config.option.runappdirect and '__pypy__' not in sys.builtin_module_names" |
| 20 |
|
| 21 |
@api.cpython_api([], api.PyObject) |
| 22 |
def PyPy_Crash1(space): |
| 23 |
1/0 |
| 24 |
|
| 25 |
@api.cpython_api([], lltype.Signed, error=-1) |
| 26 |
def PyPy_Crash2(space): |
| 27 |
1/0 |
| 28 |
|
| 29 |
@api.cpython_api([api.PyObject], api.PyObject, result_is_ll=True) |
| 30 |
def PyPy_Noop(space, pyobj): |
| 31 |
return pyobj |
| 32 |
|
| 33 |
class TestApi: |
| 34 |
def test_signature(self): |
| 35 |
common_functions = api.FUNCTIONS_BY_HEADER[api.pypy_decl] |
| 36 |
assert 'PyModule_Check' in common_functions |
| 37 |
assert common_functions['PyModule_Check'].argtypes == [cts.gettype("void *")] |
| 38 |
assert 'PyModule_GetDict' in common_functions |
| 39 |
assert common_functions['PyModule_GetDict'].argtypes == [api.PyObject] |
| 40 |
|
| 41 |
|
| 42 |
class SpaceCompiler(SystemCompilationInfo): |
| 43 |
"""Extension compiler for regular (untranslated PyPy) mode""" |
| 44 |
def __init__(self, space, *args, **kwargs): |
| 45 |
self.space = space |
| 46 |
SystemCompilationInfo.__init__(self, *args, **kwargs) |
| 47 |
|
| 48 |
def load_module(self, mod, name, use_imp=False): |
| 49 |
space = self.space |
| 50 |
w_path = space.newtext(mod) |
| 51 |
w_name = space.newtext(name) |
| 52 |
if use_imp: |
| 53 |
|
| 54 |
|
| 55 |
return space.appexec([w_name, w_path], '''(name, path): |
| 56 |
import imp |
| 57 |
return imp.load_dynamic(name, path)''') |
| 58 |
else: |
| 59 |
w_spec = space.appexec([w_name, w_path], '''(modname, path): |
| 60 |
class FakeSpec: |
| 61 |
name = modname |
| 62 |
origin = path |
| 63 |
return FakeSpec |
| 64 |
''') |
| 65 |
w_mod = create_extension_module(space, w_spec) |
| 66 |
exec_extension_module(space, w_mod) |
| 67 |
return w_mod |
| 68 |
|
| 69 |
|
| 70 |
def get_cpyext_info(space): |
| 71 |
from pypy.module.imp.importing import get_so_extension |
| 72 |
state = space.fromcache(State) |
| 73 |
api_library = state.api_lib |
| 74 |
if sys.platform == 'win32': |
| 75 |
libraries = [api_library] |
| 76 |
|
| 77 |
compile_extra = ["/we4013"] |
| 78 |
|
| 79 |
w_maj, w_min = space.fixedview(space.sys.get('version_info'), 5)[:2] |
| 80 |
link_extra = ["/NODEFAULTLIB:Python%d%d.lib" % |
| 81 |
(space.int_w(w_maj), space.int_w(w_min))] |
| 82 |
else: |
| 83 |
libraries = [] |
| 84 |
if sys.platform.startswith('linux'): |
| 85 |
compile_extra = [ |
| 86 |
"-Werror", "-g", "-O0", "-Wp,-U_FORTIFY_SOURCE", "-fPIC"] |
| 87 |
link_extra = ["-g"] |
| 88 |
else: |
| 89 |
compile_extra = link_extra = None |
| 90 |
return SpaceCompiler(space, |
| 91 |
builddir_base=udir, |
| 92 |
include_extra=api.include_dirs, |
| 93 |
compile_extra=compile_extra, |
| 94 |
link_extra=link_extra, |
| 95 |
extra_libs=libraries, |
| 96 |
ext=get_so_extension(space)) |
| 97 |
|
| 98 |
|
| 99 |
def freeze_refcnts(self): |
| 100 |
rawrefcount._dont_free_any_more() |
| 101 |
|
| 102 |
def is_interned_string(space, w_obj): |
| 103 |
try: |
| 104 |
u = space.utf8_w(w_obj) |
| 105 |
except OperationError: |
| 106 |
return False |
| 107 |
return space.interned_strings.get(u) is not None |
| 108 |
|
| 109 |
def is_allowed_to_leak(space, obj): |
| 110 |
from pypy.module.cpyext.methodobject import W_PyCFunctionObject |
| 111 |
try: |
| 112 |
w_obj = from_ref(space, cts.cast('PyObject*', obj._as_ptr())) |
| 113 |
except: |
| 114 |
return False |
| 115 |
if isinstance(w_obj, W_PyCFunctionObject): |
| 116 |
return True |
| 117 |
|
| 118 |
|
| 119 |
return is_interned_string(space, w_obj) |
| 120 |
|
| 121 |
def _get_w_obj(space, c_obj): |
| 122 |
return from_ref(space, cts.cast('PyObject*', c_obj._as_ptr())) |
| 123 |
|
| 124 |
class CpyextLeak(leakfinder.MallocMismatch): |
| 125 |
def __str__(self): |
| 126 |
lines = [leakfinder.MallocMismatch.__str__(self), ''] |
| 127 |
lines.append( |
| 128 |
"These objects are attached to the following W_Root objects:") |
| 129 |
for c_obj in self.args[0]: |
| 130 |
try: |
| 131 |
lines.append(" %s" % (_get_w_obj(self.args[1], c_obj),)) |
| 132 |
except: |
| 133 |
pass |
| 134 |
return '\n'.join(lines) |
| 135 |
|
| 136 |
|
| 137 |
class LeakCheckingTest(object): |
| 138 |
"""Base class for all cpyext tests.""" |
| 139 |
spaceconfig = {"usemodules" : ['cpyext', 'thread', 'struct', 'array', |
| 140 |
'itertools', 'time', 'binascii', |
| 141 |
'mmap', 'signal', |
| 142 |
'_cffi_backend', |
| 143 |
], |
| 144 |
"objspace.disable_entrypoints_in_cffi": True} |
| 145 |
spaceconfig["objspace.std.withspecialisedtuple"] = True |
| 146 |
|
| 147 |
@classmethod |
| 148 |
def preload_builtins(cls, space): |
| 149 |
""" |
| 150 |
Eagerly create pyobjs for various builtins so they don't look like |
| 151 |
leaks. |
| 152 |
""" |
| 153 |
from pypy.module.cpyext.pyobject import make_ref |
| 154 |
w_to_preload = space.appexec([], """(): |
| 155 |
import sys |
| 156 |
import mmap |
| 157 |
# |
| 158 |
# copied&pasted to avoid importing the whole types.py, which is |
| 159 |
# expensive on py3k |
| 160 |
# <types.py> |
| 161 |
def _f(): pass |
| 162 |
FunctionType = type(_f) |
| 163 |
CodeType = type(_f.__code__) |
| 164 |
try: |
| 165 |
raise TypeError |
| 166 |
except TypeError: |
| 167 |
tb = sys.exc_info()[2] |
| 168 |
TracebackType = type(tb) |
| 169 |
FrameType = type(tb.tb_frame) |
| 170 |
del tb |
| 171 |
# </types.py> |
| 172 |
return [ |
| 173 |
#buffer, ## does not exist on py3k |
| 174 |
mmap.mmap, |
| 175 |
FunctionType, |
| 176 |
CodeType, |
| 177 |
TracebackType, |
| 178 |
FrameType, |
| 179 |
type(str.join), |
| 180 |
] |
| 181 |
""") |
| 182 |
for w_obj in space.unpackiterable(w_to_preload): |
| 183 |
make_ref(space, w_obj) |
| 184 |
|
| 185 |
def cleanup(self): |
| 186 |
self.space.getexecutioncontext().cleanup_cpyext_state() |
| 187 |
for _ in range(5): |
| 188 |
rawrefcount._collect() |
| 189 |
self.space.user_del_action._run_finalizers() |
| 190 |
try: |
| 191 |
|
| 192 |
leakfinder.stop_tracking_allocations(check=False) |
| 193 |
except leakfinder.MallocMismatch as e: |
| 194 |
result = e.args[0] |
| 195 |
filtered_result = {} |
| 196 |
for obj, value in result.iteritems(): |
| 197 |
if not is_allowed_to_leak(self.space, obj): |
| 198 |
filtered_result[obj] = value |
| 199 |
if filtered_result: |
| 200 |
raise CpyextLeak(filtered_result, self.space) |
| 201 |
assert not self.space.finalizer_queue.next_dead() |
| 202 |
|
| 203 |
|
| 204 |
class AppTestApi(LeakCheckingTest): |
| 205 |
def setup_class(cls): |
| 206 |
from rpython.rlib.clibffi import get_libc_name |
| 207 |
if cls.runappdirect: |
| 208 |
cls.libc = get_libc_name() |
| 209 |
else: |
| 210 |
cls.w_libc = cls.space.wrap(get_libc_name()) |
| 211 |
|
| 212 |
def setup_method(self, meth): |
| 213 |
if not self.runappdirect: |
| 214 |
freeze_refcnts(self) |
| 215 |
|
| 216 |
def teardown_method(self, meth): |
| 217 |
if self.runappdirect: |
| 218 |
return |
| 219 |
self.cleanup() |
| 220 |
|
| 221 |
@pytest.mark.skipif(only_pypy, reason='pypy only test') |
| 222 |
def test_only_import(self): |
| 223 |
import cpyext |
| 224 |
|
| 225 |
def test_dllhandle(self): |
| 226 |
import sys |
| 227 |
if sys.platform != "win32" or sys.version_info < (2, 6): |
| 228 |
skip("Windows Python >= 2.6 only") |
| 229 |
assert isinstance(sys.dllhandle, int) |
| 230 |
|
| 231 |
|
| 232 |
def _unwrap_include_dirs(space, w_include_dirs): |
| 233 |
if w_include_dirs is None: |
| 234 |
return None |
| 235 |
else: |
| 236 |
return [space.text_w(s) for s in space.listview(w_include_dirs)] |
| 237 |
|
| 238 |
def debug_collect(space): |
| 239 |
rawrefcount._collect() |
| 240 |
space.user_del_action._run_finalizers() |
| 241 |
rawrefcount._collect() |
| 242 |
|
| 243 |
|
| 244 |
class AppTestCpythonExtensionBase(LeakCheckingTest): |
| 245 |
def setup_class(cls): |
| 246 |
space = cls.space |
| 247 |
cls.w_here = space.wrap(str(HERE)) |
| 248 |
cls.w_udir = space.wrap(str(udir)) |
| 249 |
cls.w_runappdirect = space.wrap(cls.runappdirect) |
| 250 |
if not cls.runappdirect: |
| 251 |
cls.sys_info = get_cpyext_info(space) |
| 252 |
cls.w_debug_collect = space.wrap(interp2app(debug_collect)) |
| 253 |
cls.preload_builtins(space) |
| 254 |
|
| 255 |
|
| 256 |
space.call_method(space.sys.get("stdout"), "flush") |
| 257 |
|
| 258 |
|
| 259 |
cls.imported_module_names = [] |
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
cls._file_module_cache = {} |
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
cls._module_keepalive = [] |
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
freeze_refcnts(cls) |
| 274 |
else: |
| 275 |
def w_import_module(self, name, init=None, body='', filename=None, |
| 276 |
include_dirs=None, PY_SSIZE_T_CLEAN=False, use_imp=False): |
| 277 |
from extbuild import get_sys_info_app |
| 278 |
sys_info = get_sys_info_app(self.udir) |
| 279 |
return sys_info.import_module( |
| 280 |
name, init=init, body=body, filename=filename, |
| 281 |
include_dirs=include_dirs, |
| 282 |
PY_SSIZE_T_CLEAN=PY_SSIZE_T_CLEAN) |
| 283 |
cls.w_import_module = w_import_module |
| 284 |
|
| 285 |
def w_import_extension(self, modname, functions, prologue="", |
| 286 |
include_dirs=None, more_init="", PY_SSIZE_T_CLEAN=False): |
| 287 |
from extbuild import get_sys_info_app |
| 288 |
sys_info = get_sys_info_app(self.udir) |
| 289 |
return sys_info.import_extension( |
| 290 |
modname, functions, prologue=prologue, |
| 291 |
include_dirs=include_dirs, more_init=more_init, |
| 292 |
PY_SSIZE_T_CLEAN=PY_SSIZE_T_CLEAN) |
| 293 |
cls.w_import_extension = w_import_extension |
| 294 |
|
| 295 |
def w_compile_module(self, name, |
| 296 |
source_files=None, source_strings=None): |
| 297 |
from extbuild import get_sys_info_app |
| 298 |
sys_info = get_sys_info_app(self.udir) |
| 299 |
return sys_info.compile_extension_module(name, |
| 300 |
source_files=source_files, source_strings=source_strings) |
| 301 |
cls.w_compile_module = w_compile_module |
| 302 |
|
| 303 |
def w_load_module(self, mod, name): |
| 304 |
from extbuild import get_sys_info_app |
| 305 |
sys_info = get_sys_info_app(self.udir) |
| 306 |
return sys_info.load_module(mod, name) |
| 307 |
cls.w_load_module = w_load_module |
| 308 |
|
| 309 |
def w_debug_collect(self): |
| 310 |
import gc |
| 311 |
gc.collect() |
| 312 |
gc.collect() |
| 313 |
gc.collect() |
| 314 |
cls.w_debug_collect = w_debug_collect |
| 315 |
|
| 316 |
|
| 317 |
def record_imported_module(self, name): |
| 318 |
""" |
| 319 |
Record a module imported in a test so that it can be cleaned up in |
| 320 |
teardown before the check for leaks is done. |
| 321 |
|
| 322 |
name gives the name of the module in the space's sys.modules. |
| 323 |
""" |
| 324 |
self.imported_module_names.append(name) |
| 325 |
|
| 326 |
def setup_method(self, func): |
| 327 |
if self.runappdirect: |
| 328 |
return |
| 329 |
|
| 330 |
@unwrap_spec(name='text') |
| 331 |
def compile_module(space, name, |
| 332 |
w_source_files=None, |
| 333 |
w_source_strings=None): |
| 334 |
""" |
| 335 |
Build an extension module linked against the cpyext api library. |
| 336 |
""" |
| 337 |
if not space.is_none(w_source_files): |
| 338 |
source_files = space.unwrap(w_source_files) |
| 339 |
else: |
| 340 |
source_files = None |
| 341 |
if not space.is_none(w_source_strings): |
| 342 |
source_strings = space.listview_bytes(w_source_strings) |
| 343 |
else: |
| 344 |
source_strings = None |
| 345 |
pydname = self.sys_info.compile_extension_module( |
| 346 |
name, |
| 347 |
source_files=source_files, |
| 348 |
source_strings=source_strings) |
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
self.record_imported_module(name) |
| 353 |
|
| 354 |
return space.wrap(pydname) |
| 355 |
|
| 356 |
@unwrap_spec(name='text', init='text_or_none', body='text', |
| 357 |
filename='fsencode_or_none', PY_SSIZE_T_CLEAN=bool, |
| 358 |
use_imp=bool) |
| 359 |
def import_module(space, name, init=None, body='', |
| 360 |
filename=None, w_include_dirs=None, |
| 361 |
PY_SSIZE_T_CLEAN=False, use_imp=False): |
| 362 |
include_dirs = _unwrap_include_dirs(space, w_include_dirs) |
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
if init is None and not body: |
| 370 |
if name in self._file_module_cache: |
| 371 |
self.record_imported_module(name) |
| 372 |
return self._file_module_cache[name] |
| 373 |
|
| 374 |
|
| 375 |
|
| 376 |
w_modules = space.sys.get('modules') |
| 377 |
try: |
| 378 |
w_old = space.getitem(w_modules, space.newtext(name)) |
| 379 |
self._module_keepalive.append(w_old) |
| 380 |
except OperationError: |
| 381 |
pass |
| 382 |
w_result = self.sys_info.import_module( |
| 383 |
name, init, body, filename, include_dirs, PY_SSIZE_T_CLEAN, |
| 384 |
use_imp) |
| 385 |
if init is None and not body: |
| 386 |
self._file_module_cache[name] = w_result |
| 387 |
self.record_imported_module(name) |
| 388 |
return w_result |
| 389 |
|
| 390 |
|
| 391 |
@unwrap_spec(mod='text', name='text') |
| 392 |
def load_module(space, mod, name): |
| 393 |
return self.sys_info.load_module(mod, name) |
| 394 |
|
| 395 |
@unwrap_spec(modname='text', prologue='text', |
| 396 |
more_init='text', PY_SSIZE_T_CLEAN=bool) |
| 397 |
def import_extension(space, modname, w_functions, prologue="", |
| 398 |
w_include_dirs=None, more_init="", PY_SSIZE_T_CLEAN=False): |
| 399 |
functions = space.unwrap(w_functions) |
| 400 |
include_dirs = _unwrap_include_dirs(space, w_include_dirs) |
| 401 |
|
| 402 |
|
| 403 |
|
| 404 |
|
| 405 |
|
| 406 |
self._file_module_cache.pop(modname, None) |
| 407 |
w_modules = space.sys.get('modules') |
| 408 |
try: |
| 409 |
w_old = space.getitem(w_modules, space.newtext(modname)) |
| 410 |
self._module_keepalive.append(w_old) |
| 411 |
except OperationError: |
| 412 |
pass |
| 413 |
w_result = self.sys_info.import_extension( |
| 414 |
modname, functions, prologue, include_dirs, more_init, |
| 415 |
PY_SSIZE_T_CLEAN) |
| 416 |
self.record_imported_module(modname) |
| 417 |
return w_result |
| 418 |
|
| 419 |
wrap = self.space.wrap |
| 420 |
self.w_compile_module = wrap(interp2app(compile_module)) |
| 421 |
self.w_load_module = wrap(interp2app(load_module)) |
| 422 |
self.w_import_module = wrap(interp2app(import_module)) |
| 423 |
self.w_import_extension = wrap(interp2app(import_extension)) |
| 424 |
|
| 425 |
def unimport_module(self, name): |
| 426 |
""" |
| 427 |
Remove the named module from the space's sys.modules. |
| 428 |
""" |
| 429 |
w_cached = self._file_module_cache.pop(name, None) |
| 430 |
if w_cached is not None: |
| 431 |
self._module_keepalive.append(w_cached) |
| 432 |
w_modules = self.space.sys.get('modules') |
| 433 |
w_name = self.space.wrap(name) |
| 434 |
try: |
| 435 |
w_old = self.space.getitem(w_modules, w_name) |
| 436 |
self._module_keepalive.append(w_old) |
| 437 |
except OperationError: |
| 438 |
pass |
| 439 |
self.space.delitem(w_modules, w_name) |
| 440 |
|
| 441 |
def teardown_method(self, func): |
| 442 |
if self.runappdirect: |
| 443 |
self.w_debug_collect() |
| 444 |
return |
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
if leakfinder.TRACK_ALLOCATIONS: |
| 450 |
leakfinder.stop_tracking_allocations(check=False) |
| 451 |
|
| 452 |
|
| 453 |
|
| 454 |
|
| 455 |
|
| 456 |
|
| 457 |
|
| 458 |
|
| 459 |
fq = self.space.finalizer_queue |
| 460 |
for _ in range(5): |
| 461 |
before = len(rawrefcount._p_list) + len(rawrefcount._o_list) |
| 462 |
rawrefcount._collect() |
| 463 |
self.space.user_del_action._run_finalizers() |
| 464 |
after = len(rawrefcount._p_list) + len(rawrefcount._o_list) |
| 465 |
if before == after and not (hasattr(fq, '_queue') and fq._queue): |
| 466 |
break |
| 467 |
|
| 468 |
@classmethod |
| 469 |
def teardown_class(cls): |
| 470 |
if cls.runappdirect: |
| 471 |
return |
| 472 |
space = cls.space |
| 473 |
debug_collect(space) |
| 474 |
seen = set() |
| 475 |
for name in cls.imported_module_names: |
| 476 |
if name not in seen: |
| 477 |
seen.add(name) |
| 478 |
w_modules = space.sys.get('modules') |
| 479 |
w_name = space.wrap(name) |
| 480 |
try: |
| 481 |
space.delitem(w_modules, w_name) |
| 482 |
except OperationError: |
| 483 |
pass |
| 484 |
|
| 485 |
|
| 486 |
cls._module_keepalive = [] |
| 487 |
|
| 488 |
space.getexecutioncontext().cleanup_cpyext_state() |
| 489 |
fq = space.finalizer_queue |
| 490 |
for _ in range(5): |
| 491 |
rawrefcount._collect() |
| 492 |
if not (hasattr(fq, '_queue') and fq._queue): |
| 493 |
break |
| 494 |
space.user_del_action._run_finalizers() |
| 495 |
assert not space.finalizer_queue.next_dead() |
| 496 |
state = space.fromcache(State) |
| 497 |
assert 'operror' not in dir(state) |
| 498 |
|
| 499 |
|
| 500 |
class AppTestCpythonExtension(AppTestCpythonExtensionBase): |
| 501 |
def test_createmodule(self): |
| 502 |
import sys |
| 503 |
self.import_module(name='foo') |
| 504 |
assert 'foo' in sys.modules |
| 505 |
|
| 506 |
def test_export_function(self): |
| 507 |
import sys |
| 508 |
if '__pypy__' in sys.modules: |
| 509 |
from cpyext import is_cpyext_builtin_function as is_cpyext_function |
| 510 |
else: |
| 511 |
import inspect |
| 512 |
is_cpyext_function = inspect.isbuiltin |
| 513 |
body = """ |
| 514 |
PyObject* foo_pi(PyObject* self, PyObject *args) |
| 515 |
{ |
| 516 |
return PyFloat_FromDouble(3.14); |
| 517 |
} |
| 518 |
static PyMethodDef methods[] = { |
| 519 |
{ "return_pi", foo_pi, METH_NOARGS }, |
| 520 |
{ NULL } |
| 521 |
}; |
| 522 |
static struct PyModuleDef moduledef = { |
| 523 |
PyModuleDef_HEAD_INIT, |
| 524 |
"foo", /* m_name */ |
| 525 |
NULL, /* m_doc */ |
| 526 |
-1, /* m_size */ |
| 527 |
methods, /* m_methods */ |
| 528 |
}; |
| 529 |
""" |
| 530 |
module = self.import_module(name='foo', body=body) |
| 531 |
assert 'foo' in sys.modules |
| 532 |
assert 'return_pi' in dir(module) |
| 533 |
assert module.return_pi is not None |
| 534 |
assert is_cpyext_function(module.return_pi) |
| 535 |
assert module.return_pi() == 3.14 |
| 536 |
assert module.return_pi.__module__ == 'foo' |
| 537 |
|
| 538 |
|
| 539 |
def test_export_docstring(self): |
| 540 |
body = """ |
| 541 |
PyDoc_STRVAR(foo_pi_doc, "Return pi."); |
| 542 |
PyObject* foo_pi(PyObject* self, PyObject *args) |
| 543 |
{ |
| 544 |
return PyFloat_FromDouble(3.14); |
| 545 |
} |
| 546 |
static PyMethodDef methods[] = { |
| 547 |
{ "return_pi", foo_pi, METH_NOARGS, foo_pi_doc }, |
| 548 |
{ NULL } |
| 549 |
}; |
| 550 |
static struct PyModuleDef moduledef = { |
| 551 |
PyModuleDef_HEAD_INIT, |
| 552 |
"foo", /* m_name */ |
| 553 |
NULL, /* m_doc */ |
| 554 |
-1, /* m_size */ |
| 555 |
methods, /* m_methods */ |
| 556 |
}; |
| 557 |
""" |
| 558 |
module = self.import_module(name='foo', body=body) |
| 559 |
doc = module.return_pi.__doc__ |
| 560 |
assert doc == "Return pi." |
| 561 |
|
| 562 |
def test_load_dynamic(self): |
| 563 |
import sys |
| 564 |
body = """ |
| 565 |
static struct PyModuleDef moduledef = { |
| 566 |
PyModuleDef_HEAD_INIT, |
| 567 |
"%(modname)s", /* m_name */ |
| 568 |
NULL, /* m_doc */ |
| 569 |
-1, /* m_size */ |
| 570 |
NULL, /* m_methods */ |
| 571 |
}; |
| 572 |
""" |
| 573 |
foo = self.import_module(name='foo', body=body, use_imp=True) |
| 574 |
assert 'foo' in sys.modules |
| 575 |
del sys.modules['foo'] |
| 576 |
import imp |
| 577 |
foo2 = imp.load_dynamic('foo', foo.__file__) |
| 578 |
assert 'foo' in sys.modules |
| 579 |
assert foo.__dict__ == foo2.__dict__ |
| 580 |
|
| 581 |
def test_InitModule4_dotted(self): |
| 582 |
""" |
| 583 |
If the module name passed to Py_InitModule4 includes a package, only |
| 584 |
the module name (the part after the last dot) is considered when |
| 585 |
computing the name of the module initializer function. |
| 586 |
""" |
| 587 |
expected_name = "pypy.module.cpyext.test.dotted" |
| 588 |
module = self.import_module(name=expected_name, filename="dotted") |
| 589 |
assert module.__name__ == expected_name, module.__name__ |
| 590 |
|
| 591 |
|
| 592 |
def test_InitModule4_in_package(self): |
| 593 |
""" |
| 594 |
If `apple.banana` is an extension module which calls Py_InitModule4 with |
| 595 |
only "banana" as a name, the resulting module nevertheless is stored at |
| 596 |
`sys.modules["apple.banana"]`. |
| 597 |
""" |
| 598 |
module = self.import_module(name="apple.banana", filename="banana") |
| 599 |
assert module.__name__ == "apple.banana" |
| 600 |
|
| 601 |
|
| 602 |
def test_recursive_package_import(self): |
| 603 |
""" |
| 604 |
If `cherry.date` is an extension module which imports `apple.banana`, |
| 605 |
the latter is added to `sys.modules` for the `"apple.banana"` key. |
| 606 |
""" |
| 607 |
import sys, types, os |
| 608 |
|
| 609 |
banana = self.compile_module( |
| 610 |
"apple.banana", source_files=[os.path.join(self.here, 'banana.c')]) |
| 611 |
date = self.compile_module( |
| 612 |
"cherry.date", source_files=[os.path.join(self.here, 'date.c')]) |
| 613 |
|
| 614 |
|
| 615 |
|
| 616 |
cherry = sys.modules['cherry'] = types.ModuleType('cherry') |
| 617 |
cherry.__path__ = [os.path.dirname(date)] |
| 618 |
|
| 619 |
apple = sys.modules['apple'] = types.ModuleType('apple') |
| 620 |
apple.__path__ = [os.path.dirname(banana)] |
| 621 |
|
| 622 |
import cherry.date |
| 623 |
|
| 624 |
assert sys.modules['apple.banana'].__name__ == 'apple.banana' |
| 625 |
assert sys.modules['cherry.date'].__name__ == 'cherry.date' |
| 626 |
|
| 627 |
|
| 628 |
def test_modinit_func(self): |
| 629 |
""" |
| 630 |
A module can use the PyMODINIT_FUNC macro to declare or define its |
| 631 |
module initializer function. |
| 632 |
""" |
| 633 |
module = self.import_module(name='modinit') |
| 634 |
assert module.__name__ == 'modinit' |
| 635 |
|
| 636 |
|
| 637 |
def test_export_function2(self): |
| 638 |
body = """ |
| 639 |
static PyObject* my_objects[1]; |
| 640 |
static PyObject* foo_cached_pi(PyObject* self, PyObject *args) |
| 641 |
{ |
| 642 |
if (my_objects[0] == NULL) { |
| 643 |
my_objects[0] = PyFloat_FromDouble(3.14); |
| 644 |
} |
| 645 |
Py_INCREF(my_objects[0]); |
| 646 |
return my_objects[0]; |
| 647 |
} |
| 648 |
static PyObject* foo_drop_pi(PyObject* self, PyObject *args) |
| 649 |
{ |
| 650 |
if (my_objects[0] != NULL) { |
| 651 |
Py_DECREF(my_objects[0]); |
| 652 |
my_objects[0] = NULL; |
| 653 |
} |
| 654 |
Py_INCREF(Py_None); |
| 655 |
return Py_None; |
| 656 |
} |
| 657 |
static PyObject* foo_retinvalid(PyObject* self, PyObject *args) |
| 658 |
{ |
| 659 |
return (PyObject*)0xAFFEBABE; |
| 660 |
} |
| 661 |
static PyMethodDef methods[] = { |
| 662 |
{ "return_pi", foo_cached_pi, METH_NOARGS }, |
| 663 |
{ "drop_pi", foo_drop_pi, METH_NOARGS }, |
| 664 |
{ "return_invalid_pointer", foo_retinvalid, METH_NOARGS }, |
| 665 |
{ NULL } |
| 666 |
}; |
| 667 |
static struct PyModuleDef moduledef = { |
| 668 |
PyModuleDef_HEAD_INIT, |
| 669 |
"%(modname)s", /* m_name */ |
| 670 |
NULL, /* m_doc */ |
| 671 |
-1, /* m_size */ |
| 672 |
methods, /* m_methods */ |
| 673 |
}; |
| 674 |
""" |
| 675 |
module = self.import_module(name='foo', body=body) |
| 676 |
assert module.return_pi() == 3.14 |
| 677 |
module.drop_pi() |
| 678 |
module.drop_pi() |
| 679 |
assert module.return_pi() == 3.14 |
| 680 |
assert module.return_pi() == 3.14 |
| 681 |
module.drop_pi() |
| 682 |
skip("Hmm, how to check for the exception?") |
| 683 |
raises(api.InvalidPointerException, module.return_invalid_pointer) |
| 684 |
|
| 685 |
def test_argument(self): |
| 686 |
import sys |
| 687 |
body = """ |
| 688 |
PyObject* foo_test(PyObject* self, PyObject *args) |
| 689 |
{ |
| 690 |
PyObject *t = PyTuple_GetItem(args, 0); |
| 691 |
Py_INCREF(t); |
| 692 |
return t; |
| 693 |
} |
| 694 |
static PyMethodDef methods[] = { |
| 695 |
{ "test", foo_test, METH_VARARGS }, |
| 696 |
{ NULL } |
| 697 |
}; |
| 698 |
static struct PyModuleDef moduledef = { |
| 699 |
PyModuleDef_HEAD_INIT, |
| 700 |
"%(modname)s", /* m_name */ |
| 701 |
NULL, /* m_doc */ |
| 702 |
-1, /* m_size */ |
| 703 |
methods, /* m_methods */ |
| 704 |
}; |
| 705 |
""" |
| 706 |
module = self.import_module(name='foo', body=body) |
| 707 |
assert module.test(True, True) == True |
| 708 |
|
| 709 |
def test_exception(self): |
| 710 |
import sys |
| 711 |
body = """ |
| 712 |
static PyObject* foo_pi(PyObject* self, PyObject *args) |
| 713 |
{ |
| 714 |
PyErr_SetString(PyExc_Exception, "moo!"); |
| 715 |
return NULL; |
| 716 |
} |
| 717 |
static PyMethodDef methods[] = { |
| 718 |
{ "raise_exception", foo_pi, METH_NOARGS }, |
| 719 |
{ NULL } |
| 720 |
}; |
| 721 |
static struct PyModuleDef moduledef = { |
| 722 |
PyModuleDef_HEAD_INIT, |
| 723 |
"%(modname)s", /* m_name */ |
| 724 |
NULL, /* m_doc */ |
| 725 |
-1, /* m_size */ |
| 726 |
methods, /* m_methods */ |
| 727 |
}; |
| 728 |
""" |
| 729 |
module = self.import_module(name='foo', body=body) |
| 730 |
exc = raises(Exception, module.raise_exception) |
| 731 |
if type(exc.value) is not Exception: |
| 732 |
raise exc.value |
| 733 |
|
| 734 |
assert str(exc.value) == "moo!" |
| 735 |
|
| 736 |
def test_refcount(self): |
| 737 |
import sys |
| 738 |
body = """ |
| 739 |
static PyObject* foo_pi(PyObject* self, PyObject *args) |
| 740 |
{ |
| 741 |
PyObject *true_obj = Py_True; |
| 742 |
Py_ssize_t refcnt = true_obj->ob_refcnt; |
| 743 |
Py_ssize_t refcnt_after; |
| 744 |
Py_INCREF(true_obj); |
| 745 |
Py_INCREF(true_obj); |
| 746 |
if (!PyBool_Check(true_obj)) |
| 747 |
Py_RETURN_NONE; |
| 748 |
refcnt_after = true_obj->ob_refcnt; |
| 749 |
Py_DECREF(true_obj); |
| 750 |
Py_DECREF(true_obj); |
| 751 |
fprintf(stderr, "REFCNT %ld %ld\\n", refcnt, refcnt_after); |
| 752 |
return PyBool_FromLong(refcnt_after == refcnt + 2); |
| 753 |
} |
| 754 |
static PyObject* foo_bar(PyObject* self, PyObject *args) |
| 755 |
{ |
| 756 |
PyObject *true_obj = Py_True; |
| 757 |
PyObject *tup = NULL; |
| 758 |
Py_ssize_t refcnt = true_obj->ob_refcnt; |
| 759 |
Py_ssize_t refcnt_after; |
| 760 |
|
| 761 |
tup = PyTuple_New(1); |
| 762 |
Py_INCREF(true_obj); |
| 763 |
if (PyTuple_SetItem(tup, 0, true_obj) < 0) |
| 764 |
return NULL; |
| 765 |
refcnt_after = true_obj->ob_refcnt; |
| 766 |
Py_DECREF(tup); |
| 767 |
fprintf(stderr, "REFCNT2 %ld %ld %ld\\n", refcnt, refcnt_after, |
| 768 |
true_obj->ob_refcnt); |
| 769 |
return PyBool_FromLong(refcnt_after == refcnt + 1 && |
| 770 |
refcnt == true_obj->ob_refcnt); |
| 771 |
} |
| 772 |
|
| 773 |
static PyMethodDef methods[] = { |
| 774 |
{ "test_refcount", foo_pi, METH_NOARGS }, |
| 775 |
{ "test_refcount2", foo_bar, METH_NOARGS }, |
| 776 |
{ NULL } |
| 777 |
}; |
| 778 |
static struct PyModuleDef moduledef = { |
| 779 |
PyModuleDef_HEAD_INIT, |
| 780 |
"%(modname)s", /* m_name */ |
| 781 |
NULL, /* m_doc */ |
| 782 |
-1, /* m_size */ |
| 783 |
methods, /* m_methods */ |
| 784 |
}; |
| 785 |
""" |
| 786 |
module = self.import_module(name='foo', body=body) |
| 787 |
assert module.test_refcount() |
| 788 |
assert module.test_refcount2() |
| 789 |
|
| 790 |
|
| 791 |
def test_init_exception(self): |
| 792 |
import sys |
| 793 |
init = """ |
| 794 |
PyErr_SetString(PyExc_Exception, "moo!"); |
| 795 |
return NULL; |
| 796 |
""" |
| 797 |
exc = raises(Exception, self.import_module, name='foo', init=init) |
| 798 |
if type(exc.value) is not Exception: |
| 799 |
raise exc.value |
| 800 |
|
| 801 |
assert str(exc.value) == "moo!" |
| 802 |
|
| 803 |
|
| 804 |
def test_internal_exceptions(self): |
| 805 |
if self.runappdirect: |
| 806 |
skip('cannot import module with undefined functions') |
| 807 |
import sys |
| 808 |
body = """ |
| 809 |
PyAPI_FUNC(PyObject*) PyPy_Crash1(void); |
| 810 |
PyAPI_FUNC(Py_ssize_t) PyPy_Crash2(void); |
| 811 |
PyAPI_FUNC(PyObject*) PyPy_Noop(PyObject*); |
| 812 |
static PyObject* foo_crash1(PyObject* self, PyObject *args) |
| 813 |
{ |
| 814 |
return PyPy_Crash1(); |
| 815 |
} |
| 816 |
static PyObject* foo_crash2(PyObject* self, PyObject *args) |
| 817 |
{ |
| 818 |
Py_ssize_t a = PyPy_Crash2(); |
| 819 |
if (a == -1) |
| 820 |
return NULL; |
| 821 |
return PyFloat_FromDouble((double)a); |
| 822 |
} |
| 823 |
static PyObject* foo_crash3(PyObject* self, PyObject *args) |
| 824 |
{ |
| 825 |
Py_ssize_t a = PyPy_Crash2(); |
| 826 |
if (a == -1) |
| 827 |
PyErr_Clear(); |
| 828 |
return PyFloat_FromDouble((double)a); |
| 829 |
} |
| 830 |
static PyObject* foo_crash4(PyObject* self, PyObject *args) |
| 831 |
{ |
| 832 |
Py_ssize_t a = PyPy_Crash2(); |
| 833 |
return PyFloat_FromDouble((double)a); |
| 834 |
} |
| 835 |
static PyObject* foo_noop(PyObject* self, PyObject* args) |
| 836 |
{ |
| 837 |
Py_INCREF(args); |
| 838 |
return PyPy_Noop(args); |
| 839 |
} |
| 840 |
static PyObject* foo_set(PyObject* self, PyObject *args) |
| 841 |
{ |
| 842 |
PyErr_SetString(PyExc_TypeError, "clear called with no error"); |
| 843 |
if (PyLong_Check(args)) { |
| 844 |
Py_INCREF(args); |
| 845 |
return args; |
| 846 |
} |
| 847 |
return NULL; |
| 848 |
} |
| 849 |
static PyObject* foo_clear(PyObject* self, PyObject *args) |
| 850 |
{ |
| 851 |
PyErr_Clear(); |
| 852 |
if (PyLong_Check(args)) { |
| 853 |
Py_INCREF(args); |
| 854 |
return args; |
| 855 |
} |
| 856 |
return NULL; |
| 857 |
} |
| 858 |
static PyMethodDef methods[] = { |
| 859 |
{ "crash1", foo_crash1, METH_NOARGS }, |
| 860 |
{ "crash2", foo_crash2, METH_NOARGS }, |
| 861 |
{ "crash3", foo_crash3, METH_NOARGS }, |
| 862 |
{ "crash4", foo_crash4, METH_NOARGS }, |
| 863 |
{ "clear", foo_clear, METH_O }, |
| 864 |
{ "set", foo_set, METH_O }, |
| 865 |
{ "noop", foo_noop, METH_O }, |
| 866 |
{ NULL } |
| 867 |
}; |
| 868 |
static struct PyModuleDef moduledef = { |
| 869 |
PyModuleDef_HEAD_INIT, |
| 870 |
"%(modname)s", /* m_name */ |
| 871 |
NULL, /* m_doc */ |
| 872 |
-1, /* m_size */ |
| 873 |
methods, /* m_methods */ |
| 874 |
}; |
| 875 |
""" |
| 876 |
module = self.import_module(name='foo', body=body) |
| 877 |
|
| 878 |
|
| 879 |
expected = "ZeroDivisionError('integer division" |
| 880 |
exc = raises(SystemError, module.crash1) |
| 881 |
|
| 882 |
assert exc.value.args[0].startswith(expected) |
| 883 |
|
| 884 |
exc = raises(SystemError, module.crash2) |
| 885 |
assert exc.value.args[0].startswith(expected) |
| 886 |
|
| 887 |
|
| 888 |
assert module.crash3() == -1 |
| 889 |
|
| 890 |
expected = 'c function call returned a result with an exception set' |
| 891 |
|
| 892 |
exc = raises(SystemError, module.crash4) |
| 893 |
assert exc.value.args[0] == expected |
| 894 |
|
| 895 |
|
| 896 |
|
| 897 |
assert module.noop(1) == 1 |
| 898 |
|
| 899 |
|
| 900 |
expected = 'c function call returned NULL without setting an exception' |
| 901 |
exc = raises(SystemError, module.clear, None) |
| 902 |
assert exc.value.args[0] == expected |
| 903 |
|
| 904 |
|
| 905 |
raises(TypeError, module.set, None) |
| 906 |
|
| 907 |
|
| 908 |
assert module.clear(1) == 1 |
| 909 |
|
| 910 |
|
| 911 |
expected = 'c function call returned a result with an exception set' |
| 912 |
exc = raises(SystemError, module.set, 1) |
| 913 |
assert exc.value.args[0] == expected |
| 914 |
|
| 915 |
|
| 916 |
|
| 917 |
assert module.clear(1) == 1 |
| 918 |
|
| 919 |
def test_new_exception(self): |
| 920 |
mod = self.import_extension('foo', [ |
| 921 |
('newexc', 'METH_VARARGS', |
| 922 |
''' |
| 923 |
char *name = _PyUnicode_AsString(PyTuple_GetItem(args, 0)); |
| 924 |
return PyErr_NewException(name, PyTuple_GetItem(args, 1), |
| 925 |
PyTuple_GetItem(args, 2)); |
| 926 |
''' |
| 927 |
), |
| 928 |
]) |
| 929 |
raises(SystemError, mod.newexc, "name", Exception, {}) |
| 930 |
|
| 931 |
@pytest.mark.skipif(only_pypy, reason='pypy specific test') |
| 932 |
def test_hash_pointer(self): |
| 933 |
mod = self.import_extension('foo', [ |
| 934 |
('get_hash', 'METH_NOARGS', |
| 935 |
''' |
| 936 |
return PyLong_FromLong(_Py_HashPointer(Py_None)); |
| 937 |
''' |
| 938 |
), |
| 939 |
]) |
| 940 |
h = mod.get_hash() |
| 941 |
assert h != 0 |
| 942 |
assert h % 4 == 0 |
| 943 |
|
| 944 |
def test_types(self): |
| 945 |
"""test the presence of random types""" |
| 946 |
|
| 947 |
mod = self.import_extension('foo', [ |
| 948 |
('get_names', 'METH_NOARGS', |
| 949 |
''' |
| 950 |
/* XXX in tests, the C type is not correct */ |
| 951 |
#define NAME(type) ((PyTypeObject*)&type)->tp_name |
| 952 |
return Py_BuildValue("ssssss", |
| 953 |
NAME(PyCell_Type), |
| 954 |
NAME(PyModule_Type), |
| 955 |
NAME(PyProperty_Type), |
| 956 |
NAME(PyStaticMethod_Type), |
| 957 |
NAME(PyClassMethod_Type), |
| 958 |
NAME(PyCFunction_Type) |
| 959 |
); |
| 960 |
''' |
| 961 |
), |
| 962 |
]) |
| 963 |
assert mod.get_names() == ('cell', 'module', 'property', |
| 964 |
'staticmethod', 'classmethod', |
| 965 |
'builtin_function_or_method') |
| 966 |
|
| 967 |
def test_get_programname(self): |
| 968 |
mod = self.import_extension('foo', [ |
| 969 |
('get_programname', 'METH_NOARGS', |
| 970 |
''' |
| 971 |
wchar_t* name1 = Py_GetProgramName(); |
| 972 |
wchar_t* name2 = Py_GetProgramName(); |
| 973 |
if (name1 != name2) |
| 974 |
Py_RETURN_FALSE; |
| 975 |
return PyUnicode_FromWideChar(name1, wcslen(name1)); |
| 976 |
''' |
| 977 |
)], |
| 978 |
prologue='#include <wchar.h>') |
| 979 |
p = mod.get_programname() |
| 980 |
print(p) |
| 981 |
assert 'py' in p |
| 982 |
|
| 983 |
@pytest.mark.skipif(only_pypy, reason='pypy only test') |
| 984 |
def test_get_version(self): |
| 985 |
mod = self.import_extension('foo', [ |
| 986 |
('get_version', 'METH_NOARGS', |
| 987 |
''' |
| 988 |
char* name1 = Py_GetVersion(); |
| 989 |
char* name2 = Py_GetVersion(); |
| 990 |
if (name1 != name2) |
| 991 |
Py_RETURN_FALSE; |
| 992 |
return PyUnicode_FromString(name1); |
| 993 |
''' |
| 994 |
), |
| 995 |
]) |
| 996 |
p = mod.get_version() |
| 997 |
print(p) |
| 998 |
assert 'PyPy' in p |
| 999 |
|
| 1000 |
def test_no_double_imports(self): |
| 1001 |
import sys, os |
| 1002 |
try: |
| 1003 |
body = """ |
| 1004 |
static struct PyModuleDef moduledef = { |
| 1005 |
PyModuleDef_HEAD_INIT, |
| 1006 |
"%(modname)s", /* m_name */ |
| 1007 |
NULL, /* m_doc */ |
| 1008 |
-1, /* m_size */ |
| 1009 |
NULL /* m_methods */ |
| 1010 |
}; |
| 1011 |
""" |
| 1012 |
init = """ |
| 1013 |
static int _imported_already = 0; |
| 1014 |
FILE *f = fopen("_imported_already", "w"); |
| 1015 |
fprintf(f, "imported_already: %d\\n", _imported_already); |
| 1016 |
fclose(f); |
| 1017 |
_imported_already = 1; |
| 1018 |
return PyModule_Create(&moduledef); |
| 1019 |
""" |
| 1020 |
self.import_module(name='foo', init=init, body=body) |
| 1021 |
assert 'foo' in sys.modules |
| 1022 |
|
| 1023 |
f = open('_imported_already') |
| 1024 |
data = f.read() |
| 1025 |
f.close() |
| 1026 |
assert data == 'imported_already: 0\n' |
| 1027 |
|
| 1028 |
f = open('_imported_already', 'w') |
| 1029 |
f.write('not again!\n') |
| 1030 |
f.close() |
| 1031 |
m1 = sys.modules['foo'] |
| 1032 |
m2 = self.load_module(m1.__file__, name='foo') |
| 1033 |
assert m1 is m2 |
| 1034 |
assert m1 is sys.modules['foo'] |
| 1035 |
|
| 1036 |
f = open('_imported_already') |
| 1037 |
data = f.read() |
| 1038 |
f.close() |
| 1039 |
assert data == 'not again!\n' |
| 1040 |
|
| 1041 |
finally: |
| 1042 |
try: |
| 1043 |
os.unlink('_imported_already') |
| 1044 |
except OSError: |
| 1045 |
pass |
| 1046 |
|
| 1047 |
def test_no_structmember(self): |
| 1048 |
"""structmember.h should not be included by default.""" |
| 1049 |
mod = self.import_extension('foo', [ |
| 1050 |
('bar', 'METH_NOARGS', |
| 1051 |
''' |
| 1052 |
/* reuse a name that is #defined in structmember.h */ |
| 1053 |
int RO = 0; (void)RO; |
| 1054 |
Py_RETURN_NONE; |
| 1055 |
''' |
| 1056 |
), |
| 1057 |
]) |
| 1058 |
|
| 1059 |
def test_consistent_flags(self): |
| 1060 |
import sys |
| 1061 |
mod = self.import_extension('foo', [ |
| 1062 |
('test_optimize', 'METH_NOARGS', |
| 1063 |
''' |
| 1064 |
return PyLong_FromLong(Py_OptimizeFlag); |
| 1065 |
'''), |
| 1066 |
]) |
| 1067 |
|
| 1068 |
|
| 1069 |
assert mod.test_optimize() == sys.flags.optimize |
| 1070 |
|
| 1071 |
def test_generic_type(self): |
| 1072 |
mod = self.import_extension('foo', [ |
| 1073 |
('is_genericalias_type', 'METH_O', |
| 1074 |
""" |
| 1075 |
long test = (Py_TYPE(args) == &Py_GenericAliasType); |
| 1076 |
return PyLong_FromLong(test); |
| 1077 |
""")]) |
| 1078 |
assert mod.is_genericalias_type(tuple[int]) |