|
| 1 | +import networkx |
| 2 | +import pytest |
| 3 | + |
| 4 | +from algorithm.graph.test.graph_data_utils import create_weighted_city_graph |
| 5 | + |
| 6 | +city_graph = create_weighted_city_graph() |
| 7 | + |
| 8 | + |
| 9 | +@pytest.mark.benchmark(group='graph_dijkstra') |
| 10 | +@pytest.mark.parametrize( |
| 11 | + argnames='graph, source, target, expected_path', |
| 12 | + argvalues=[ |
| 13 | + (city_graph, 'Los Angeles', 'Boston', ['Los Angeles', 'Riverside', 'Chicago', 'Detroit', 'Boston']), |
| 14 | + ], |
| 15 | + ids=['los_angeles_to_boston']) |
| 16 | +def test_graph_dijkstra_path(benchmark, graph, source, target, expected_path): |
| 17 | + """ |
| 18 | + Find the shortest path between two nodes in a graph using Dijkstra's algorithm. |
| 19 | + :param benchmark: benchmark fixture |
| 20 | + :param graph: city graph of the United States |
| 21 | + :param source: source city node |
| 22 | + :param target: target city node |
| 23 | + :param expected_path: expected shortest path |
| 24 | + """ |
| 25 | + shortest_path = benchmark(networkx.dijkstra_path, graph, source, target) |
| 26 | + assert shortest_path == expected_path |
| 27 | + |
| 28 | + |
| 29 | +@pytest.mark.benchmark(group='graph_dijkstra') |
| 30 | +@pytest.mark.parametrize( |
| 31 | + argnames='graph, source, target, expected_distance', |
| 32 | + argvalues=[ |
| 33 | + (city_graph, 'Los Angeles', 'Boston', 2605), |
| 34 | + ], |
| 35 | + ids=['los_angeles_to_boston']) |
| 36 | +def test_graph_dijkstra_distance(benchmark, graph, source, target, expected_distance): |
| 37 | + """ |
| 38 | + Find the shortest distance between two nodes in a graph using Dijkstra's algorithm. |
| 39 | + :param benchmark: benchmark fixture |
| 40 | + :param graph: city graph of the United States |
| 41 | + :param source: source city node |
| 42 | + :param target: target city node |
| 43 | + :param expected_distance: expected shortest distance (weight) |
| 44 | + """ |
| 45 | + total_weight = benchmark(networkx.dijkstra_path_length, graph, source, target) |
| 46 | + assert total_weight == expected_distance |
0 commit comments