test_public_api.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. import sys
  2. import sysconfig
  3. import subprocess
  4. import pkgutil
  5. import types
  6. import importlib
  7. import warnings
  8. import numpy as np
  9. import numpy
  10. import pytest
  11. from numpy.testing import IS_WASM
  12. try:
  13. import ctypes
  14. except ImportError:
  15. ctypes = None
  16. def check_dir(module, module_name=None):
  17. """Returns a mapping of all objects with the wrong __module__ attribute."""
  18. if module_name is None:
  19. module_name = module.__name__
  20. results = {}
  21. for name in dir(module):
  22. item = getattr(module, name)
  23. if (hasattr(item, '__module__') and hasattr(item, '__name__')
  24. and item.__module__ != module_name):
  25. results[name] = item.__module__ + '.' + item.__name__
  26. return results
  27. def test_numpy_namespace():
  28. # None of these objects are publicly documented to be part of the main
  29. # NumPy namespace (some are useful though, others need to be cleaned up)
  30. undocumented = {
  31. 'Tester': 'numpy.testing._private.nosetester.NoseTester',
  32. '_add_newdoc_ufunc': 'numpy.core._multiarray_umath._add_newdoc_ufunc',
  33. 'add_docstring': 'numpy.core._multiarray_umath.add_docstring',
  34. 'add_newdoc': 'numpy.core.function_base.add_newdoc',
  35. 'add_newdoc_ufunc': 'numpy.core._multiarray_umath._add_newdoc_ufunc',
  36. 'byte_bounds': 'numpy.lib.utils.byte_bounds',
  37. 'compare_chararrays': 'numpy.core._multiarray_umath.compare_chararrays',
  38. 'deprecate': 'numpy.lib.utils.deprecate',
  39. 'deprecate_with_doc': 'numpy.lib.utils.deprecate_with_doc',
  40. 'disp': 'numpy.lib.function_base.disp',
  41. 'fastCopyAndTranspose': 'numpy.core._multiarray_umath.fastCopyAndTranspose',
  42. 'get_array_wrap': 'numpy.lib.shape_base.get_array_wrap',
  43. 'get_include': 'numpy.lib.utils.get_include',
  44. 'recfromcsv': 'numpy.lib.npyio.recfromcsv',
  45. 'recfromtxt': 'numpy.lib.npyio.recfromtxt',
  46. 'safe_eval': 'numpy.lib.utils.safe_eval',
  47. 'set_string_function': 'numpy.core.arrayprint.set_string_function',
  48. 'show_config': 'numpy.__config__.show',
  49. 'show_runtime': 'numpy.lib.utils.show_runtime',
  50. 'who': 'numpy.lib.utils.who',
  51. }
  52. # We override dir to not show these members
  53. allowlist = undocumented
  54. bad_results = check_dir(np)
  55. # pytest gives better error messages with the builtin assert than with
  56. # assert_equal
  57. assert bad_results == allowlist
  58. @pytest.mark.skipif(IS_WASM, reason="can't start subprocess")
  59. @pytest.mark.parametrize('name', ['testing', 'Tester'])
  60. def test_import_lazy_import(name):
  61. """Make sure we can actually use the modules we lazy load.
  62. While not exported as part of the public API, it was accessible. With the
  63. use of __getattr__ and __dir__, this isn't always true It can happen that
  64. an infinite recursion may happen.
  65. This is the only way I found that would force the failure to appear on the
  66. badly implemented code.
  67. We also test for the presence of the lazily imported modules in dir
  68. """
  69. exe = (sys.executable, '-c', "import numpy; numpy." + name)
  70. result = subprocess.check_output(exe)
  71. assert not result
  72. # Make sure they are still in the __dir__
  73. assert name in dir(np)
  74. def test_dir_testing():
  75. """Assert that output of dir has only one "testing/tester"
  76. attribute without duplicate"""
  77. assert len(dir(np)) == len(set(dir(np)))
  78. def test_numpy_linalg():
  79. bad_results = check_dir(np.linalg)
  80. assert bad_results == {}
  81. def test_numpy_fft():
  82. bad_results = check_dir(np.fft)
  83. assert bad_results == {}
  84. @pytest.mark.skipif(ctypes is None,
  85. reason="ctypes not available in this python")
  86. def test_NPY_NO_EXPORT():
  87. cdll = ctypes.CDLL(np.core._multiarray_tests.__file__)
  88. # Make sure an arbitrary NPY_NO_EXPORT function is actually hidden
  89. f = getattr(cdll, 'test_not_exported', None)
  90. assert f is None, ("'test_not_exported' is mistakenly exported, "
  91. "NPY_NO_EXPORT does not work")
  92. # Historically NumPy has not used leading underscores for private submodules
  93. # much. This has resulted in lots of things that look like public modules
  94. # (i.e. things that can be imported as `import numpy.somesubmodule.somefile`),
  95. # but were never intended to be public. The PUBLIC_MODULES list contains
  96. # modules that are either public because they were meant to be, or because they
  97. # contain public functions/objects that aren't present in any other namespace
  98. # for whatever reason and therefore should be treated as public.
  99. #
  100. # The PRIVATE_BUT_PRESENT_MODULES list contains modules that look public (lack
  101. # of underscores) but should not be used. For many of those modules the
  102. # current status is fine. For others it may make sense to work on making them
  103. # private, to clean up our public API and avoid confusion.
  104. PUBLIC_MODULES = ['numpy.' + s for s in [
  105. "array_api",
  106. "array_api.linalg",
  107. "ctypeslib",
  108. "distutils",
  109. "distutils.cpuinfo",
  110. "distutils.exec_command",
  111. "distutils.misc_util",
  112. "distutils.log",
  113. "distutils.system_info",
  114. "doc",
  115. "doc.constants",
  116. "doc.ufuncs",
  117. "f2py",
  118. "fft",
  119. "lib",
  120. "lib.format", # was this meant to be public?
  121. "lib.mixins",
  122. "lib.recfunctions",
  123. "lib.scimath",
  124. "lib.stride_tricks",
  125. "linalg",
  126. "ma",
  127. "ma.extras",
  128. "ma.mrecords",
  129. "matlib",
  130. "polynomial",
  131. "polynomial.chebyshev",
  132. "polynomial.hermite",
  133. "polynomial.hermite_e",
  134. "polynomial.laguerre",
  135. "polynomial.legendre",
  136. "polynomial.polynomial",
  137. "random",
  138. "testing",
  139. "typing",
  140. "typing.mypy_plugin",
  141. "version",
  142. ]]
  143. PUBLIC_ALIASED_MODULES = [
  144. "numpy.char",
  145. "numpy.emath",
  146. "numpy.rec",
  147. ]
  148. PRIVATE_BUT_PRESENT_MODULES = ['numpy.' + s for s in [
  149. "compat",
  150. "compat.py3k",
  151. "conftest",
  152. "core",
  153. "core.arrayprint",
  154. "core.defchararray",
  155. "core.einsumfunc",
  156. "core.fromnumeric",
  157. "core.function_base",
  158. "core.getlimits",
  159. "core.memmap",
  160. "core.multiarray",
  161. "core.numeric",
  162. "core.numerictypes",
  163. "core.overrides",
  164. "core.records",
  165. "core.shape_base",
  166. "core.umath",
  167. "core.umath_tests",
  168. "distutils.armccompiler",
  169. "distutils.ccompiler",
  170. 'distutils.ccompiler_opt',
  171. "distutils.command",
  172. "distutils.command.autodist",
  173. "distutils.command.bdist_rpm",
  174. "distutils.command.build",
  175. "distutils.command.build_clib",
  176. "distutils.command.build_ext",
  177. "distutils.command.build_py",
  178. "distutils.command.build_scripts",
  179. "distutils.command.build_src",
  180. "distutils.command.config",
  181. "distutils.command.config_compiler",
  182. "distutils.command.develop",
  183. "distutils.command.egg_info",
  184. "distutils.command.install",
  185. "distutils.command.install_clib",
  186. "distutils.command.install_data",
  187. "distutils.command.install_headers",
  188. "distutils.command.sdist",
  189. "distutils.conv_template",
  190. "distutils.core",
  191. "distutils.extension",
  192. "distutils.fcompiler",
  193. "distutils.fcompiler.absoft",
  194. "distutils.fcompiler.arm",
  195. "distutils.fcompiler.compaq",
  196. "distutils.fcompiler.environment",
  197. "distutils.fcompiler.g95",
  198. "distutils.fcompiler.gnu",
  199. "distutils.fcompiler.hpux",
  200. "distutils.fcompiler.ibm",
  201. "distutils.fcompiler.intel",
  202. "distutils.fcompiler.lahey",
  203. "distutils.fcompiler.mips",
  204. "distutils.fcompiler.nag",
  205. "distutils.fcompiler.none",
  206. "distutils.fcompiler.pathf95",
  207. "distutils.fcompiler.pg",
  208. "distutils.fcompiler.nv",
  209. "distutils.fcompiler.sun",
  210. "distutils.fcompiler.vast",
  211. "distutils.fcompiler.fujitsu",
  212. "distutils.from_template",
  213. "distutils.intelccompiler",
  214. "distutils.lib2def",
  215. "distutils.line_endings",
  216. "distutils.mingw32ccompiler",
  217. "distutils.msvccompiler",
  218. "distutils.npy_pkg_config",
  219. "distutils.numpy_distribution",
  220. "distutils.pathccompiler",
  221. "distutils.unixccompiler",
  222. "dual",
  223. "f2py.auxfuncs",
  224. "f2py.capi_maps",
  225. "f2py.cb_rules",
  226. "f2py.cfuncs",
  227. "f2py.common_rules",
  228. "f2py.crackfortran",
  229. "f2py.diagnose",
  230. "f2py.f2py2e",
  231. "f2py.f90mod_rules",
  232. "f2py.func2subr",
  233. "f2py.rules",
  234. "f2py.symbolic",
  235. "f2py.use_rules",
  236. "fft.helper",
  237. "lib.arraypad",
  238. "lib.arraysetops",
  239. "lib.arrayterator",
  240. "lib.function_base",
  241. "lib.histograms",
  242. "lib.index_tricks",
  243. "lib.nanfunctions",
  244. "lib.npyio",
  245. "lib.polynomial",
  246. "lib.shape_base",
  247. "lib.twodim_base",
  248. "lib.type_check",
  249. "lib.ufunclike",
  250. "lib.user_array", # note: not in np.lib, but probably should just be deleted
  251. "lib.utils",
  252. "linalg.lapack_lite",
  253. "linalg.linalg",
  254. "ma.bench",
  255. "ma.core",
  256. "ma.testutils",
  257. "ma.timer_comparison",
  258. "matrixlib",
  259. "matrixlib.defmatrix",
  260. "polynomial.polyutils",
  261. "random.mtrand",
  262. "random.bit_generator",
  263. "testing.print_coercion_tables",
  264. "testing.utils",
  265. ]]
  266. def is_unexpected(name):
  267. """Check if this needs to be considered."""
  268. if '._' in name or '.tests' in name or '.setup' in name:
  269. return False
  270. if name in PUBLIC_MODULES:
  271. return False
  272. if name in PUBLIC_ALIASED_MODULES:
  273. return False
  274. if name in PRIVATE_BUT_PRESENT_MODULES:
  275. return False
  276. return True
  277. # These are present in a directory with an __init__.py but cannot be imported
  278. # code_generators/ isn't installed, but present for an inplace build
  279. SKIP_LIST = [
  280. "numpy.core.code_generators",
  281. "numpy.core.code_generators.genapi",
  282. "numpy.core.code_generators.generate_umath",
  283. "numpy.core.code_generators.ufunc_docstrings",
  284. "numpy.core.code_generators.generate_numpy_api",
  285. "numpy.core.code_generators.generate_ufunc_api",
  286. "numpy.core.code_generators.numpy_api",
  287. "numpy.core.code_generators.generate_umath_doc",
  288. "numpy.core.cversions",
  289. "numpy.core.generate_numpy_api",
  290. "numpy.distutils.msvc9compiler",
  291. ]
  292. def test_all_modules_are_expected():
  293. """
  294. Test that we don't add anything that looks like a new public module by
  295. accident. Check is based on filenames.
  296. """
  297. modnames = []
  298. for _, modname, ispkg in pkgutil.walk_packages(path=np.__path__,
  299. prefix=np.__name__ + '.',
  300. onerror=None):
  301. if is_unexpected(modname) and modname not in SKIP_LIST:
  302. # We have a name that is new. If that's on purpose, add it to
  303. # PUBLIC_MODULES. We don't expect to have to add anything to
  304. # PRIVATE_BUT_PRESENT_MODULES. Use an underscore in the name!
  305. modnames.append(modname)
  306. if modnames:
  307. raise AssertionError(f'Found unexpected modules: {modnames}')
  308. # Stuff that clearly shouldn't be in the API and is detected by the next test
  309. # below
  310. SKIP_LIST_2 = [
  311. 'numpy.math',
  312. 'numpy.distutils.log.sys',
  313. 'numpy.distutils.log.logging',
  314. 'numpy.distutils.log.warnings',
  315. 'numpy.doc.constants.re',
  316. 'numpy.doc.constants.textwrap',
  317. 'numpy.lib.emath',
  318. 'numpy.lib.math',
  319. 'numpy.matlib.char',
  320. 'numpy.matlib.rec',
  321. 'numpy.matlib.emath',
  322. 'numpy.matlib.math',
  323. 'numpy.matlib.linalg',
  324. 'numpy.matlib.fft',
  325. 'numpy.matlib.random',
  326. 'numpy.matlib.ctypeslib',
  327. 'numpy.matlib.ma',
  328. ]
  329. def test_all_modules_are_expected_2():
  330. """
  331. Method checking all objects. The pkgutil-based method in
  332. `test_all_modules_are_expected` does not catch imports into a namespace,
  333. only filenames. So this test is more thorough, and checks this like:
  334. import .lib.scimath as emath
  335. To check if something in a module is (effectively) public, one can check if
  336. there's anything in that namespace that's a public function/object but is
  337. not exposed in a higher-level namespace. For example for a `numpy.lib`
  338. submodule::
  339. mod = np.lib.mixins
  340. for obj in mod.__all__:
  341. if obj in np.__all__:
  342. continue
  343. elif obj in np.lib.__all__:
  344. continue
  345. else:
  346. print(obj)
  347. """
  348. def find_unexpected_members(mod_name):
  349. members = []
  350. module = importlib.import_module(mod_name)
  351. if hasattr(module, '__all__'):
  352. objnames = module.__all__
  353. else:
  354. objnames = dir(module)
  355. for objname in objnames:
  356. if not objname.startswith('_'):
  357. fullobjname = mod_name + '.' + objname
  358. if isinstance(getattr(module, objname), types.ModuleType):
  359. if is_unexpected(fullobjname):
  360. if fullobjname not in SKIP_LIST_2:
  361. members.append(fullobjname)
  362. return members
  363. unexpected_members = find_unexpected_members("numpy")
  364. for modname in PUBLIC_MODULES:
  365. unexpected_members.extend(find_unexpected_members(modname))
  366. if unexpected_members:
  367. raise AssertionError("Found unexpected object(s) that look like "
  368. "modules: {}".format(unexpected_members))
  369. def test_api_importable():
  370. """
  371. Check that all submodules listed higher up in this file can be imported
  372. Note that if a PRIVATE_BUT_PRESENT_MODULES entry goes missing, it may
  373. simply need to be removed from the list (deprecation may or may not be
  374. needed - apply common sense).
  375. """
  376. def check_importable(module_name):
  377. try:
  378. importlib.import_module(module_name)
  379. except (ImportError, AttributeError):
  380. return False
  381. return True
  382. module_names = []
  383. for module_name in PUBLIC_MODULES:
  384. if not check_importable(module_name):
  385. module_names.append(module_name)
  386. if module_names:
  387. raise AssertionError("Modules in the public API that cannot be "
  388. "imported: {}".format(module_names))
  389. for module_name in PUBLIC_ALIASED_MODULES:
  390. try:
  391. eval(module_name)
  392. except AttributeError:
  393. module_names.append(module_name)
  394. if module_names:
  395. raise AssertionError("Modules in the public API that were not "
  396. "found: {}".format(module_names))
  397. with warnings.catch_warnings(record=True) as w:
  398. warnings.filterwarnings('always', category=DeprecationWarning)
  399. warnings.filterwarnings('always', category=ImportWarning)
  400. for module_name in PRIVATE_BUT_PRESENT_MODULES:
  401. if not check_importable(module_name):
  402. module_names.append(module_name)
  403. if module_names:
  404. raise AssertionError("Modules that are not really public but looked "
  405. "public and can not be imported: "
  406. "{}".format(module_names))
  407. @pytest.mark.xfail(
  408. sysconfig.get_config_var("Py_DEBUG") is not None,
  409. reason=(
  410. "NumPy possibly built with `USE_DEBUG=True ./tools/travis-test.sh`, "
  411. "which does not expose the `array_api` entry point. "
  412. "See https://github.com/numpy/numpy/pull/19800"
  413. ),
  414. )
  415. def test_array_api_entry_point():
  416. """
  417. Entry point for Array API implementation can be found with importlib and
  418. returns the numpy.array_api namespace.
  419. """
  420. eps = importlib.metadata.entry_points()
  421. try:
  422. xp_eps = eps.select(group="array_api")
  423. except AttributeError:
  424. # The select interface for entry_points was introduced in py3.10,
  425. # deprecating its dict interface. We fallback to dict keys for finding
  426. # Array API entry points so that running this test in <=3.9 will
  427. # still work - see https://github.com/numpy/numpy/pull/19800.
  428. xp_eps = eps.get("array_api", [])
  429. assert len(xp_eps) > 0, "No entry points for 'array_api' found"
  430. try:
  431. ep = next(ep for ep in xp_eps if ep.name == "numpy")
  432. except StopIteration:
  433. raise AssertionError("'numpy' not in array_api entry points") from None
  434. xp = ep.load()
  435. msg = (
  436. f"numpy entry point value '{ep.value}' "
  437. "does not point to our Array API implementation"
  438. )
  439. assert xp is numpy.array_api, msg