|
| 1 | +from unittest.mock import patch |
| 2 | + |
| 3 | +import pytest |
| 4 | +from geographic_distance import calculate_distance_and_time, main |
| 5 | + |
| 6 | + |
| 7 | +def test_calculate_distance_and_time(): |
| 8 | + # Test with valid coordinates and speed |
| 9 | + coord1 = (40.7128, -74.006) |
| 10 | + coord2 = (37.7749, -122.4194) |
| 11 | + avg_speed = 60 |
| 12 | + distance, travel_time = calculate_distance_and_time(coord1, coord2, avg_speed) |
| 13 | + assert distance > 0 |
| 14 | + assert travel_time > 0 |
| 15 | + |
| 16 | + |
| 17 | +def test_calculate_distance_and_time_invalid_speed(): |
| 18 | + # Test with invalid speed (zero) |
| 19 | + coord1 = (40.7128, -74.006) |
| 20 | + coord2 = (37.7749, -122.4194) |
| 21 | + avg_speed = 0 |
| 22 | + with pytest.raises(ValueError): |
| 23 | + calculate_distance_and_time(coord1, coord2, avg_speed) |
| 24 | + |
| 25 | + |
| 26 | +def test_calculate_distance_and_time_same_coordinates(): |
| 27 | + # Test with same coordinates |
| 28 | + coord1 = (40.7128, -74.006) |
| 29 | + coord2 = (40.7128, -74.006) |
| 30 | + avg_speed = 60 |
| 31 | + distance, travel_time = calculate_distance_and_time(coord1, coord2, avg_speed) |
| 32 | + assert distance == 0 |
| 33 | + 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