|
| 1 | +import nx_parallel as nxp |
| 2 | +from nx_parallel.interface import ALGORITHMS |
| 3 | +import networkx as nx |
| 4 | +import inspect |
| 5 | +import pytest |
| 6 | +import os |
| 7 | +import joblib |
| 8 | + |
| 9 | + |
| 10 | +def get_functions_with_should_run(): |
| 11 | + for name, obj in inspect.getmembers(nxp.algorithms, inspect.isfunction): |
| 12 | + if callable(obj.should_run): |
| 13 | + yield name |
| 14 | + |
| 15 | + |
| 16 | +def test_get_functions_with_should_run(): |
| 17 | + assert set(get_functions_with_should_run()) == set(ALGORITHMS) |
| 18 | + |
| 19 | + |
| 20 | +def test_default_should_run(): |
| 21 | + @nxp._configure_if_nx_active() |
| 22 | + def dummy_default(): |
| 23 | + pass |
| 24 | + |
| 25 | + with pytest.MonkeyPatch().context() as mp: |
| 26 | + mp.delitem(os.environ, "PYTEST_CURRENT_TEST", raising=False) |
| 27 | + assert ( |
| 28 | + dummy_default.should_run() |
| 29 | + == "Parallel backend requires `n_jobs` > 1 to run" |
| 30 | + ) |
| 31 | + |
| 32 | + with joblib.parallel_config(n_jobs=4): |
| 33 | + assert dummy_default.should_run() |
| 34 | + |
| 35 | + |
| 36 | +def test_skip_parallel_backend(): |
| 37 | + @nxp._configure_if_nx_active(should_run=nxp.should_skip_parallel) |
| 38 | + def dummy_skip_parallel(): |
| 39 | + pass |
| 40 | + |
| 41 | + assert dummy_skip_parallel.should_run() == "Fast algorithm; skip parallel execution" |
| 42 | + |
| 43 | + |
| 44 | +def test_should_run_if_large(): |
| 45 | + @nxp._configure_if_nx_active(should_run=nxp.should_run_if_large) |
| 46 | + def dummy_if_large(G): |
| 47 | + pass |
| 48 | + |
| 49 | + smallG = nx.fast_gnp_random_graph(20, 0.6, seed=42) |
| 50 | + largeG = nx.fast_gnp_random_graph(250, 0.6, seed=42) |
| 51 | + |
| 52 | + assert dummy_if_large.should_run(smallG) == "Graph too small for parallel execution" |
| 53 | + assert dummy_if_large.should_run(largeG) |
| 54 | + |
| 55 | + |
| 56 | +@pytest.mark.parametrize("func_name", get_functions_with_should_run()) |
| 57 | +def test_should_run(func_name): |
| 58 | + tournament_funcs = [ |
| 59 | + "tournament_is_strongly_connected", |
| 60 | + ] |
| 61 | + |
| 62 | + if func_name in tournament_funcs: |
| 63 | + G = nx.tournament.random_tournament(15, seed=42) |
| 64 | + else: |
| 65 | + G = nx.fast_gnp_random_graph(40, 0.6, seed=42) |
| 66 | + H = nxp.ParallelGraph(G) |
| 67 | + func = getattr(nxp, func_name) |
| 68 | + |
| 69 | + result = func.should_run(H) |
| 70 | + if not isinstance(result, (bool, str)): |
| 71 | + raise AssertionError( |
| 72 | + f"{func.__name__}.should_run has an invalid return type; {type(result)}" |
| 73 | + ) |
0 commit comments