|
| 1 | +"""Regression tests for building node trees when networkx is unavailable. |
| 2 | +
|
| 3 | +When nodebpy is vendored into a Blender extension, the optional ``networkx`` |
| 4 | +dependency is frequently absent. The Sugiyama layout should then fall back to |
| 5 | +the simple arrangement instead of crashing. |
| 6 | +
|
| 7 | +The subtle failure mode this guards against is order-dependent: the *first* |
| 8 | +arrange attempt raises a clean ``ImportError`` (which is caught and falls back), |
| 9 | +but a *second* attempt used to surface a raw ``KeyError`` from the namespace |
| 10 | +package machinery, escaping the ``except ImportError`` guard. So we must build |
| 11 | +more than one tree in the same process to exercise the real bug. |
| 12 | +""" |
| 13 | + |
| 14 | +import sys |
| 15 | + |
| 16 | +import pytest |
| 17 | + |
| 18 | +from nodebpy import TreeBuilder |
| 19 | +from nodebpy import geometry as g |
| 20 | + |
| 21 | + |
| 22 | +@pytest.fixture |
| 23 | +def no_networkx(): |
| 24 | + """Simulate a vendored install where networkx cannot be imported. |
| 25 | +
|
| 26 | + Setting ``sys.modules['networkx'] = None`` makes ``import networkx`` raise |
| 27 | + ``ImportError``. We also evict the cached ``nodebpy.lib.nodearrange`` |
| 28 | + modules so the import is genuinely re-attempted (rebuilding the namespace |
| 29 | + package path), matching the user's fresh-process scenario. |
| 30 | + """ |
| 31 | + blocked = "networkx" |
| 32 | + saved = { |
| 33 | + k: v |
| 34 | + for k, v in sys.modules.items() |
| 35 | + if k == blocked |
| 36 | + or k.startswith(blocked + ".") |
| 37 | + or k.startswith("nodebpy.lib.nodearrange") |
| 38 | + } |
| 39 | + for key in saved: |
| 40 | + del sys.modules[key] |
| 41 | + sys.modules[blocked] = None # force ImportError on `import networkx` |
| 42 | + try: |
| 43 | + yield |
| 44 | + finally: |
| 45 | + del sys.modules[blocked] |
| 46 | + sys.modules.update(saved) |
| 47 | + |
| 48 | + |
| 49 | +def _build(name: str) -> TreeBuilder: |
| 50 | + with TreeBuilder.geometry(name) as tree: # default arrange="sugiyama" |
| 51 | + geo = tree.inputs.geometry() |
| 52 | + out = tree.outputs.geometry() |
| 53 | + _ = geo >> g.SetPosition() >> g.RealizeInstances() >> out |
| 54 | + return tree |
| 55 | + |
| 56 | + |
| 57 | +def test_fallback_without_networkx(no_networkx): |
| 58 | + """Two sequential sugiyama builds must degrade gracefully without networkx.""" |
| 59 | + # First tree: clean ImportError -> warns + falls back. This works today. |
| 60 | + with pytest.warns(UserWarning, match="networkx"): |
| 61 | + _build("FirstNoNX") |
| 62 | + |
| 63 | + # Second tree: this is where the stale namespace path used to raise |
| 64 | + # KeyError: 'nodebpy.lib.nodearrange', escaping `except ImportError`. |
| 65 | + second = _build("SecondNoNX") |
| 66 | + |
| 67 | + # The tree should still have been built and arranged (simple fallback). |
| 68 | + assert len(second.tree.nodes) > 0 |
0 commit comments