|
| 1 | +import pytest |
| 2 | + |
| 3 | +from grimp.adaptors.graph import ImportGraph |
| 4 | + |
| 5 | + |
| 6 | +class TestFindShortestCycle: |
| 7 | + @pytest.mark.parametrize( |
| 8 | + "expected_cycle", |
| 9 | + [ |
| 10 | + ("foo", "bar", "foo"), |
| 11 | + ("foo", "bar", "baz", "foo"), |
| 12 | + ], |
| 13 | + ) |
| 14 | + def test_finds_shortest_cycle_when_exists(self, expected_cycle): |
| 15 | + graph = ImportGraph() |
| 16 | + # Shortest cycle |
| 17 | + for importer, imported in zip(expected_cycle[:-1], expected_cycle[1:]): |
| 18 | + graph.add_import(importer=importer, imported=imported) |
| 19 | + # Longer cycle |
| 20 | + graph.add_import(importer="foo", imported="x") |
| 21 | + graph.add_import(importer="x", imported="y") |
| 22 | + graph.add_import(importer="y", imported="z") |
| 23 | + graph.add_import(importer="z", imported="foo") |
| 24 | + |
| 25 | + assert graph.find_shortest_cycle("foo") == expected_cycle |
| 26 | + |
| 27 | + graph.remove_import(importer=expected_cycle[-2], imported=expected_cycle[-1]) |
| 28 | + |
| 29 | + assert graph.find_shortest_cycle("foo") == ("foo", "x", "y", "z", "foo") |
| 30 | + |
| 31 | + def test_returns_none_if_no_cycle_exists(self): |
| 32 | + graph = ImportGraph() |
| 33 | + graph.add_import(importer="foo", imported="bar") |
| 34 | + graph.add_import(importer="bar", imported="baz") |
| 35 | + # graph.add_import(importer="baz", imported="foo") # This import is missing -> No cycle. |
| 36 | + |
| 37 | + assert graph.find_shortest_cycle("foo") is None |
| 38 | + |
| 39 | + def test_ignores_internal_imports_when_as_package_is_true(self): |
| 40 | + graph = ImportGraph() |
| 41 | + graph.add_module("colors") |
| 42 | + graph.add_import(importer="colors.red", imported="colors.blue") |
| 43 | + graph.add_import(importer="colors.blue", imported="colors.red") |
| 44 | + graph.add_import(importer="colors.red", imported="x") |
| 45 | + graph.add_import(importer="x", imported="y") |
| 46 | + graph.add_import(importer="y", imported="z") |
| 47 | + graph.add_import(importer="z", imported="colors.blue") |
| 48 | + |
| 49 | + assert graph.find_shortest_cycle("colors", as_package=True) == ( |
| 50 | + "colors.red", |
| 51 | + "x", |
| 52 | + "y", |
| 53 | + "z", |
| 54 | + "colors.blue", |
| 55 | + ) |
0 commit comments