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