|
| 1 | +"""Run against an installed wheel/sdist, outside the source package directory.""" |
| 2 | + |
| 3 | +import ast |
| 4 | +import builtins |
| 5 | +import contextlib |
| 6 | +import importlib.metadata |
| 7 | +import importlib.util |
| 8 | +import io |
| 9 | +import json |
| 10 | +from pathlib import Path |
| 11 | +import subprocess |
| 12 | +import sys |
| 13 | +import tempfile |
| 14 | +from types import SimpleNamespace |
| 15 | +import unittest |
| 16 | +from unittest.mock import patch |
| 17 | + |
| 18 | +if importlib.util.find_spec('funasr_onnx') is None: |
| 19 | + raise unittest.SkipTest('Install the standalone funasr-onnx distribution first.') |
| 20 | + |
| 21 | +import funasr_onnx |
| 22 | +from funasr_onnx.paraformer_online_bin import Paraformer as ParaformerOnline |
| 23 | + |
| 24 | + |
| 25 | +ENTRYPOINTS = ( |
| 26 | + funasr_onnx.Paraformer, |
| 27 | + funasr_onnx.ContextualParaformer, |
| 28 | + funasr_onnx.SeacoParaformer, |
| 29 | + ParaformerOnline, |
| 30 | + funasr_onnx.Fsmn_vad, |
| 31 | + funasr_onnx.Fsmn_vad_online, |
| 32 | + funasr_onnx.CT_Transformer, |
| 33 | + funasr_onnx.CT_Transformer_VadRealtime, |
| 34 | + funasr_onnx.SenseVoiceSmall, |
| 35 | +) |
| 36 | + |
| 37 | + |
| 38 | +class InstalledOnnxPackageTest(unittest.TestCase): |
| 39 | + def test_installed_distribution_version_and_origin(self): |
| 40 | + distribution = importlib.metadata.distribution('funasr-onnx') |
| 41 | + self.assertEqual(distribution.version, '0.4.3') |
| 42 | + self.assertEqual( |
| 43 | + Path(funasr_onnx.__file__).resolve().parent, |
| 44 | + Path(distribution.locate_file('funasr_onnx')).resolve(), |
| 45 | + ) |
| 46 | + |
| 47 | + def test_installed_modules_have_no_string_exceptions(self): |
| 48 | + offenders = [] |
| 49 | + for source in Path(funasr_onnx.__file__).parent.rglob('*.py'): |
| 50 | + for node in ast.walk(ast.parse(source.read_text(encoding='utf-8'))): |
| 51 | + if not isinstance(node, ast.Raise): |
| 52 | + continue |
| 53 | + literal = node.exc |
| 54 | + if ( |
| 55 | + isinstance(literal, ast.Call) |
| 56 | + and isinstance(literal.func, ast.Attribute) |
| 57 | + and literal.func.attr == 'format' |
| 58 | + ): |
| 59 | + literal = literal.func.value |
| 60 | + if isinstance(literal, ast.Constant) and isinstance(literal.value, str): |
| 61 | + offenders.append(f'{source.name}:{node.lineno}') |
| 62 | + self.assertEqual(offenders, []) |
| 63 | + |
| 64 | + def check_export_import_error(self, error, expected_type, preserves_cause): |
| 65 | + original_import = builtins.__import__ |
| 66 | + |
| 67 | + def broken_export_import(name, *args, **kwargs): |
| 68 | + if name == 'funasr': |
| 69 | + raise error |
| 70 | + return original_import(name, *args, **kwargs) |
| 71 | + |
| 72 | + # Only the optional exporter import is replaced; constructors are installed code. |
| 73 | + with tempfile.TemporaryDirectory() as model_dir: |
| 74 | + for entrypoint in ENTRYPOINTS: |
| 75 | + with self.subTest(entrypoint=entrypoint.__name__): |
| 76 | + error.__traceback__ = None |
| 77 | + with patch('builtins.__import__', side_effect=broken_export_import): |
| 78 | + with contextlib.redirect_stdout(io.StringIO()): |
| 79 | + with self.assertRaises(expected_type) as raised: |
| 80 | + entrypoint(model_dir) |
| 81 | + if preserves_cause: |
| 82 | + self.assertIs(raised.exception.__cause__, error) |
| 83 | + else: |
| 84 | + self.assertIs(raised.exception, error) |
| 85 | + |
| 86 | + def test_missing_transitive_export_dependency_remains_visible(self): |
| 87 | + error = ModuleNotFoundError("No module named 'torchaudio'", name='torchaudio') |
| 88 | + self.check_export_import_error(error, ImportError, preserves_cause=True) |
| 89 | + |
| 90 | + def test_unrelated_export_import_failure_is_not_misreported(self): |
| 91 | + error = RuntimeError('exporter initialization failed') |
| 92 | + self.check_export_import_error(error, RuntimeError, preserves_cause=False) |
| 93 | + |
| 94 | + def test_failed_model_download_preserves_cause(self): |
| 95 | + original_import = builtins.__import__ |
| 96 | + error = OSError('model download failed') |
| 97 | + |
| 98 | + def failed_download(*args, **kwargs): |
| 99 | + raise error |
| 100 | + |
| 101 | + def controlled_download_import(name, *args, **kwargs): |
| 102 | + if name == 'modelscope.hub.snapshot_download': |
| 103 | + return SimpleNamespace(snapshot_download=failed_download) |
| 104 | + return original_import(name, *args, **kwargs) |
| 105 | + |
| 106 | + with tempfile.TemporaryDirectory() as directory: |
| 107 | + missing_model = str(Path(directory) / 'not-downloaded') |
| 108 | + for entrypoint in ENTRYPOINTS: |
| 109 | + with self.subTest(entrypoint=entrypoint.__name__): |
| 110 | + error.__traceback__ = None |
| 111 | + with patch('builtins.__import__', side_effect=controlled_download_import): |
| 112 | + with self.assertRaises(RuntimeError) as raised: |
| 113 | + entrypoint(missing_model) |
| 114 | + self.assertIs(raised.exception.__cause__, error) |
| 115 | + |
| 116 | + def test_missing_onnxruntime_import_preserves_cause(self): |
| 117 | + script = ''' |
| 118 | +import builtins |
| 119 | +import json |
| 120 | +original_import = builtins.__import__ |
| 121 | +def broken_import(name, *args, **kwargs): |
| 122 | + if name == 'onnxruntime': |
| 123 | + raise ModuleNotFoundError("No module named 'onnxruntime'", name='onnxruntime') |
| 124 | + return original_import(name, *args, **kwargs) |
| 125 | +builtins.__import__ = broken_import |
| 126 | +try: |
| 127 | + import funasr_onnx |
| 128 | +except Exception as error: |
| 129 | + print(json.dumps({ |
| 130 | + 'type': type(error).__name__, |
| 131 | + 'cause': type(error.__cause__).__name__, |
| 132 | + 'missing': getattr(error.__cause__, 'name', None), |
| 133 | + })) |
| 134 | +else: |
| 135 | + print(json.dumps({'type': None})) |
| 136 | +''' |
| 137 | + result = subprocess.run( |
| 138 | + [sys.executable, '-c', script], capture_output=True, text=True, timeout=60, |
| 139 | + check=True, |
| 140 | + ) |
| 141 | + self.assertEqual(json.loads(result.stdout.splitlines()[-1]), { |
| 142 | + 'type': 'ImportError', 'cause': 'ModuleNotFoundError', 'missing': 'onnxruntime', |
| 143 | + }) |
| 144 | + |
| 145 | + |
| 146 | +if __name__ == '__main__': |
| 147 | + unittest.main() |
0 commit comments