61 lines
2.2 KiB
Python
61 lines
2.2 KiB
Python
import onnx
|
|
import onnx.helper
|
|
import pytest
|
|
|
|
from models.export import inspect_onnx_metadata
|
|
|
|
|
|
def _tiny_onnx_bytes() -> bytes:
|
|
node = onnx.helper.make_node("Identity", ["x"], ["y"])
|
|
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
|
|
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
|
|
graph = onnx.helper.make_graph([node], "tiny", [x], [y])
|
|
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
|
|
return model.SerializeToString()
|
|
|
|
|
|
def test_inspect_onnx_metadata_reads_producer_and_io(tmp_path):
|
|
path = tmp_path / "model.onnx"
|
|
path.write_bytes(_tiny_onnx_bytes())
|
|
|
|
metadata = inspect_onnx_metadata(path)
|
|
|
|
assert metadata["available"] is True
|
|
assert metadata["producer_name"] == "pytest-fixture"
|
|
assert metadata["graph_inputs"] == ["x"]
|
|
assert metadata["graph_outputs"] == ["y"]
|
|
|
|
|
|
def test_inspect_onnx_metadata_rejects_structurally_invalid_model(tmp_path):
|
|
"""A protobuf-valid but structurally broken graph (a node reading an
|
|
input the graph never declares) must be rejected: `onnx.load` alone
|
|
only parses the protobuf and would let this through."""
|
|
node = onnx.helper.make_node("Identity", ["undeclared_input"], ["y"])
|
|
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
|
|
graph = onnx.helper.make_graph([node], "broken", [], [y])
|
|
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
|
|
path = tmp_path / "model.onnx"
|
|
path.write_bytes(model.SerializeToString())
|
|
|
|
with pytest.raises(ValueError, match="no es un modelo ONNX válido"):
|
|
inspect_onnx_metadata(path)
|
|
|
|
|
|
def test_inspect_onnx_metadata_without_onnx_available(monkeypatch, tmp_path):
|
|
import builtins
|
|
|
|
real_import = builtins.__import__
|
|
|
|
def fake_import(name, *args, **kwargs):
|
|
if name == "onnx":
|
|
raise ImportError("onnx not installed")
|
|
return real_import(name, *args, **kwargs)
|
|
|
|
monkeypatch.setattr(builtins, "__import__", fake_import)
|
|
path = tmp_path / "model.onnx"
|
|
path.write_bytes(b"irrelevant")
|
|
assert inspect_onnx_metadata(path) == {
|
|
"available": False,
|
|
"reason": "el paquete 'onnx' no está instalado (extra 'export')",
|
|
}
|