Skip to content

Commit 926e594

Browse files
committed
Update error handling, and tests for geographic distance script.
1 parent 809ef68 commit 926e594

2 files changed

Lines changed: 62 additions & 22 deletions

File tree

Geographic Distance/geographic_distance.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,33 +9,41 @@ def calculate_distance_and_time(coord1, coord2, avg_speed):
99
:param avg_speed: Average speed in km/h for estimating travel time
1010
:return: Distance in kilometers and estimated travel time in hours
1111
"""
12-
if not (isinstance(coord1, tuple) and isinstance(coord2, tuple)):
13-
raise ValueError("Coordinates must be in the format 'lat, lon'")
1412

1513
# Calculate geodesic distance
1614
distance = geodesic(coord1, coord2).kilometers
1715
# Estimate travel time (distance / speed)
18-
if avg_speed > 0:
19-
travel_time = distance / avg_speed
20-
else:
21-
raise ValueError("Average speed must be greater than 0.")
16+
travel_time = distance / avg_speed
17+
2218
return distance, travel_time
2319

2420

2521
def main():
2622
# Coordinates (latitude, longitude)
27-
coord1 = input("Enter the latitude and longitude of the first location (lat1, lon1) Example: 40.7128, -74.006: ")
28-
coord2 = input("Enter the latitude and longitude of the second location (lat2, lon2) Example: 37.7749, -122.4194: ")
23+
try:
24+
coord1 = tuple(map(float, input('Enter the latitude and longitude of the first location (lat1, lon1) Example: 40.7128, -74.006: ').split(',')))
25+
coord2 = tuple(map(float, input('Enter the latitude and longitude of the second location (lat2, lon2) Example: 37.7749, -122.4194: ').split(',')))
26+
except ValueError as e:
27+
raise ValueError("Coordinates must be in the format 'lat, lon'") from e
28+
29+
if not all(-90 <= x <= 90 for x in (coord1[0], coord2[0])) or not all(-180 <= x <= 180 for x in (coord1[1], coord2[1])):
30+
raise ValueError('Invalid coordinates')
2931

3032
# Speed in km/h (e.g., driving speed)
31-
avg_speed = float(input("Enter the average speed in km/h Example: 60: "))
33+
try:
34+
avg_speed = float(input('Enter the average speed in km/h Example: 60: '))
35+
except ValueError as e:
36+
raise ValueError('Average speed must be a number') from e
37+
38+
if avg_speed <= 0:
39+
raise ValueError('Average speed must be greater than 0.')
3240

3341
# Calculate the distance and travel time
3442
distance, travel_time = calculate_distance_and_time(coord1, coord2, avg_speed)
3543

36-
print(f"Distance between the two coordinates: {distance:.2f} km")
37-
print(f"Estimated travel time: {travel_time:.2f} hours")
44+
print(f'Distance between the two coordinates: {distance:.2f} kilometers')
45+
print(f'Estimated travel time: {travel_time:.2f} hours')
3846

3947

40-
if __name__ == "__main__":
48+
if __name__ == '__main__':
4149
main()

Geographic Distance/test_geographic_distance.py

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
from unittest.mock import patch
2+
13
import pytest
2-
from geographic_distance import calculate_distance_and_time
4+
from geographic_distance import calculate_distance_and_time, main
35

46

57
def test_calculate_distance_and_time():
@@ -21,15 +23,6 @@ def test_calculate_distance_and_time_invalid_speed():
2123
calculate_distance_and_time(coord1, coord2, avg_speed)
2224

2325

24-
def test_calculate_distance_and_time_invalid_coordinates():
25-
# Test with invalid coordinates (not tuples)
26-
coord1 = "40.7128, -74.006"
27-
coord2 = "37.7749, -122.4194"
28-
avg_speed = 60
29-
with pytest.raises(ValueError):
30-
calculate_distance_and_time(coord1, coord2, avg_speed)
31-
32-
3326
def test_calculate_distance_and_time_same_coordinates():
3427
# Test with same coordinates
3528
coord1 = (40.7128, -74.006)
@@ -38,3 +31,42 @@ def test_calculate_distance_and_time_same_coordinates():
3831
distance, travel_time = calculate_distance_and_time(coord1, coord2, avg_speed)
3932
assert distance == 0
4033
assert travel_time == 0
34+
35+
36+
@pytest.fixture
37+
def mock_input():
38+
with patch('builtins.input', side_effect=['40.7128, -74.006', '37.7749, -122.4194', '60']):
39+
yield
40+
41+
42+
def test_main(mock_input, capsys):
43+
main()
44+
captured = capsys.readouterr()
45+
assert 'Distance between the two coordinates:' in captured.out
46+
assert 'Estimated travel time:' in captured.out
47+
48+
49+
def test_main_invalid_coordinates(mock_input, capsys):
50+
with patch('builtins.input', side_effect=['abc, def', '37.7749, -122.4194', '60']):
51+
with pytest.raises(ValueError):
52+
main()
53+
54+
55+
def test_main_invalid_speed(mock_input, capsys):
56+
with patch('builtins.input', side_effect=['40.7128, -74.006', '37.7749, -122.4194', 'abc']):
57+
with pytest.raises(ValueError):
58+
main()
59+
60+
61+
def test_main_zero_speed(mock_input, capsys):
62+
with patch('builtins.input', side_effect=['40.7128, -74.006', '37.7749, -122.4194', '0']):
63+
with pytest.raises(ValueError):
64+
main()
65+
66+
67+
def test_main_same_coordinates(mock_input, capsys):
68+
with patch('builtins.input', side_effect=['40.7128, -74.006', '40.7128, -74.006', '60']):
69+
main()
70+
captured = capsys.readouterr()
71+
assert 'Distance between the two coordinates: 0.00 kilometers' in captured.out
72+
assert 'Estimated travel time: 0.00 hours' in captured.out

0 commit comments

Comments
 (0)