增加环绕侦察场景适配

This commit is contained in:
2026-01-08 15:44:38 +08:00
parent 3eba1f962b
commit 10c5bb5a8a
5441 changed files with 40219 additions and 379695 deletions

View File

@@ -1,4 +1,3 @@
import importlib
import importlib.metadata
import os
import pathlib
@@ -15,8 +14,10 @@ INCLUDE_DIR = NUMPY_ROOT / '_core' / 'include'
PKG_CONFIG_DIR = NUMPY_ROOT / '_core' / 'lib' / 'pkgconfig'
@pytest.mark.skipif(not IS_INSTALLED, reason="`numpy-config` not expected to be installed")
@pytest.mark.skipif(IS_WASM, reason="wasm interpreter cannot start subprocess")
@pytest.mark.skipif(not IS_INSTALLED,
reason="`numpy-config` not expected to be installed")
@pytest.mark.skipif(IS_WASM,
reason="wasm interpreter cannot start subprocess")
class TestNumpyConfig:
def check_numpyconfig(self, arg):
p = subprocess.run(['numpy-config', arg], capture_output=True, text=True)
@@ -36,13 +37,15 @@ class TestNumpyConfig:
assert pathlib.Path(stdout) == PKG_CONFIG_DIR.resolve()
@pytest.mark.skipif(not IS_INSTALLED, reason="numpy must be installed to check its entrypoints")
@pytest.mark.skipif(not IS_INSTALLED,
reason="numpy must be installed to check its entrypoints")
def test_pkg_config_entrypoint():
(entrypoint,) = importlib.metadata.entry_points(group='pkg_config', name='numpy')
assert entrypoint.value == numpy._core.lib.pkgconfig.__name__
@pytest.mark.skipif(not IS_INSTALLED, reason="numpy.pc is only available when numpy is installed")
@pytest.mark.skipif(not IS_INSTALLED,
reason="numpy.pc is only available when numpy is installed")
@pytest.mark.skipif(IS_EDITABLE, reason="editable installs don't have a numpy.pc")
def test_pkg_config_config_exists():
assert PKG_CONFIG_DIR.joinpath('numpy.pc').is_file()

View File

@@ -124,6 +124,7 @@ class TestNdpointer:
assert_(p.from_param(x))
assert_raises(TypeError, p.from_param, np.array([[1, 2], [3, 4]]))
@pytest.mark.thread_unsafe(reason="checks that global ndpointer cache is updating")
def test_cache(self):
assert_(ndpointer(dtype=np.float64) is ndpointer(dtype=np.float64))
@@ -178,6 +179,7 @@ class TestNdpointerCFunc:
arr.__array_interface__['data']
)
@pytest.mark.thread_unsafe(reason="mutates global test vars")
def test_vague_return_value(self):
""" Test that vague ndpointer return values do not promote to arrays """
arr = np.zeros((2, 3))
@@ -252,6 +254,7 @@ class TestAsArray:
check(as_array(pointer(c_array[0]), shape=(2,)))
check(as_array(pointer(c_array[0][0]), shape=(2, 3)))
@pytest.mark.thread_unsafe(reason="garbage collector is global state")
def test_reference_cycles(self):
# related to gh-6511
import ctypes
@@ -302,6 +305,7 @@ class TestAsCtypesType:
ct = np.ctypeslib.as_ctypes_type(dt)
assert_equal(ct, ctypes.c_uint16)
@pytest.mark.thread_unsafe(reason="some sort of data race? (gh-29943)")
def test_subarray(self):
dt = np.dtype((np.int32, (2, 3)))
ct = np.ctypeslib.as_ctypes_type(dt)
@@ -321,6 +325,7 @@ class TestAsCtypesType:
('b', ctypes.c_uint32),
])
@pytest.mark.thread_unsafe(reason="some sort of data race? (gh-29943)")
def test_structure_aligned(self):
dt = np.dtype([
('a', np.uint16),
@@ -351,6 +356,7 @@ class TestAsCtypesType:
('b', ctypes.c_uint32),
])
@pytest.mark.thread_unsafe(reason="some sort of data race? (gh-29943)")
def test_padded_union(self):
dt = np.dtype({
'names': ['a', 'b'],

View File

@@ -1,23 +1,23 @@
import subprocess
import sys
from importlib.util import LazyLoader, find_spec, module_from_spec
import textwrap
import pytest
from numpy.testing import IS_WASM
# Warning raised by _reload_guard() in numpy/__init__.py
@pytest.mark.filterwarnings("ignore:The NumPy module was reloaded")
@pytest.mark.skipif(IS_WASM, reason="can't start subprocess")
def test_lazy_load():
# gh-22045. lazyload doesn't import submodule names into the namespace
# muck with sys.modules to test the importing system
old_numpy = sys.modules.pop("numpy")
numpy_modules = {}
for mod_name, mod in list(sys.modules.items()):
if mod_name[:6] == "numpy.":
numpy_modules[mod_name] = mod
sys.modules.pop(mod_name)
# Test within a new process, to ensure that we do not mess with the
# global state during the test run (could lead to cryptic test failures).
# This is generally unsafe, especially, since we also reload the C-modules.
code = textwrap.dedent(r"""
import sys
from importlib.util import LazyLoader, find_spec, module_from_spec
try:
# create lazy load of numpy as np
spec = find_spec("numpy")
module = module_from_spec(spec)
@@ -31,8 +31,12 @@ def test_lazy_load():
# test triggering the import of the package
np.ndarray
finally:
if old_numpy:
sys.modules["numpy"] = old_numpy
sys.modules.update(numpy_modules)
""")
p = subprocess.run(
(sys.executable, '-c', code),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf-8',
check=False,
)
assert p.returncode == 0, p.stdout

View File

@@ -21,6 +21,7 @@ class TestNumPyConfigs:
]
@patch("numpy.__config__._check_pyyaml")
@pytest.mark.thread_unsafe(reason="unittest.mock.patch updates global state")
def test_pyyaml_not_found(self, mock_yaml_importer):
mock_yaml_importer.side_effect = ModuleNotFoundError()
with pytest.warns(UserWarning):

View File

@@ -190,10 +190,8 @@ PRIVATE_BUT_PRESENT_MODULES = ['numpy.' + s for s in [
"f2py.rules",
"f2py.symbolic",
"f2py.use_rules",
"fft.helper",
"lib.user_array", # note: not in np.lib, but probably should just be deleted
"linalg.lapack_lite",
"linalg.linalg",
"ma.core",
"ma.testutils",
"matlib",
@@ -780,7 +778,7 @@ def test___qualname___and___module___attribute():
inspect.ismodule(member) and # it's a module
"numpy" in member.__name__ and # inside NumPy
not member_name.startswith("_") and # not private
member_name not in {"tests", "typing"} and # 2024-12: type names don't match
member_name not in {"tests", "typing"} and # type names don't match
"numpy._core" not in member.__name__ and # outside _core
member not in visited_modules # not visited yet
):

View File

@@ -7,15 +7,10 @@ from importlib import reload
import pytest
import numpy.exceptions as ex
from numpy.testing import (
IS_WASM,
assert_,
assert_equal,
assert_raises,
assert_warns,
)
from numpy.testing import IS_WASM, assert_, assert_equal, assert_raises
@pytest.mark.thread_unsafe(reason="reloads global module")
def test_numpy_reloading():
# gh-7844. Also check that relevant globals retain their identity.
import numpy as np
@@ -25,14 +20,14 @@ def test_numpy_reloading():
VisibleDeprecationWarning = ex.VisibleDeprecationWarning
ModuleDeprecationWarning = ex.ModuleDeprecationWarning
with assert_warns(UserWarning):
with pytest.warns(UserWarning):
reload(np)
assert_(_NoValue is np._NoValue)
assert_(ModuleDeprecationWarning is ex.ModuleDeprecationWarning)
assert_(VisibleDeprecationWarning is ex.VisibleDeprecationWarning)
assert_raises(RuntimeError, reload, numpy._globals)
with assert_warns(UserWarning):
with pytest.warns(UserWarning):
reload(np)
assert_(_NoValue is np._NoValue)
assert_(ModuleDeprecationWarning is ex.ModuleDeprecationWarning)
@@ -48,27 +43,34 @@ def test_novalue():
@pytest.mark.skipif(IS_WASM, reason="can't start subprocess")
def test_full_reimport():
"""At the time of writing this, it is *not* truly supported, but
apparently enough users rely on it, for it to be an annoying change
when it started failing previously.
"""
# Reimporting numpy like this is not safe due to use of global C state,
# and has unexpected side effects. Test that an ImportError is raised.
# When all extension modules are isolated, this should test that clearing
# sys.modules and reimporting numpy works without error.
# Test within a new process, to ensure that we do not mess with the
# global state during the test run (could lead to cryptic test failures).
# This is generally unsafe, especially, since we also reload the C-modules.
code = textwrap.dedent(r"""
import sys
from pytest import warns
import numpy as np
for k in list(sys.modules.keys()):
if "numpy" in k:
del sys.modules[k]
for k in [k for k in sys.modules if k.startswith('numpy')]:
del sys.modules[k]
with warns(UserWarning):
try:
import numpy as np
except ImportError as err:
if str(err) != "cannot load module more than once per process":
raise SystemExit(f"Unexpected ImportError: {err}")
else:
raise SystemExit("DID NOT RAISE ImportError")
""")
p = subprocess.run([sys.executable, '-c', code], capture_output=True)
if p.returncode:
raise AssertionError(
f"Non-zero return code: {p.returncode!r}\n\n{p.stderr.decode()}"
)
p = subprocess.run(
(sys.executable, '-c', code),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf-8',
check=False,
)
assert p.returncode == 0, p.stdout

View File

@@ -5,8 +5,7 @@ Test that we can run executable scripts that have been installed with numpy.
import os
import subprocess
import sys
from os.path import dirname, isfile
from os.path import join as pathjoin
from os.path import dirname, isfile, join as pathjoin
import pytest

View File

@@ -34,10 +34,11 @@ class FindFuncs(ast.NodeVisitor):
ast.NodeVisitor.generic_visit(self, node)
if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings':
if node.args[0].value == "ignore":
raise AssertionError(
"warnings should have an appropriate stacklevel; "
f"found in {self.__filename} on line {node.lineno}")
if getattr(node.args[0], "value", None) == "ignore":
if not self.__filename.name.startswith("test_"):
raise AssertionError(
"ignore filters should only be used in tests; "
f"found in {self.__filename} on line {node.lineno}")
if p.ls[-1] == 'warn' and (
len(p.ls) == 1 or p.ls[-2] == 'warnings'):