Skip to content

Commit 099dbe3

Browse files
committed
Add extra benchmark for find_shortest_chains exposing slow O(N^2) algorithm
1 parent 8a9a960 commit 099dbe3

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

tests/benchmarking/test_benchmarking.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,40 @@ def test_no_chains(self, large_graph, benchmark):
464464
)
465465
assert result == set()
466466

467+
def test_chains_found_sparse_imports(self, benchmark):
468+
"""
469+
A test case where the number of import chains is significantly less
470+
than the number of module combinations. In this case package `a` has
471+
100 modules and package `c` has 100 modules, however the number of import
472+
chains between them is only 10.
473+
474+
This case of "sparse" imports is typical of realistic scenarios, where there are
475+
large packages and only a small handful of contract violations.
476+
477+
This test case is designed to expose weaknesses of naive O(N^2) algorithms
478+
which compute chains by pathfinding between every pair of modules.
479+
"""
480+
graph = ImportGraph()
481+
graph.add_module("a")
482+
graph.add_module("b")
483+
graph.add_module("c")
484+
for i in range(100):
485+
graph.add_module(f"a.m{i}")
486+
graph.add_module(f"b.m{i}")
487+
graph.add_module(f"c.m{i}")
488+
if i % 10 == 0:
489+
graph.add_import(importer=f"a.m{i}", imported=f"b.m{i}")
490+
graph.add_import(importer=f"b.m{i}", imported=f"c.m{i}")
491+
492+
result = _run_benchmark(
493+
benchmark,
494+
graph.find_shortest_chains,
495+
"a",
496+
"c",
497+
as_packages=True,
498+
)
499+
assert len(result) == 10
500+
467501

468502
def test_copy_graph(large_graph, benchmark):
469503
_run_benchmark(benchmark, lambda: deepcopy(large_graph))

0 commit comments

Comments
 (0)