|
| 1 | +# tests/test_weather.py |
| 2 | + |
| 3 | +import sys |
| 4 | + |
| 5 | +import pytest |
| 6 | +from weather import WeatherService |
| 7 | + |
| 8 | +# from hypothesis import given |
| 9 | +# from hypothesis.strategies import floats |
| 10 | + |
| 11 | + |
| 12 | +# ✅ Parametrization |
| 13 | +@pytest.mark.parametrize( |
| 14 | + "city,expected_temp", [("London", 15), ("Berlin", 20), ("Paris", 17)] |
| 15 | +) |
| 16 | +def test_get_temperature_multiple_cities(monkeypatch, city, expected_temp): |
| 17 | + def fake_get(url, params): |
| 18 | + class FakeResponse: |
| 19 | + def raise_for_status(self): |
| 20 | + pass |
| 21 | + |
| 22 | + def json(self): |
| 23 | + return {"current": {"temp_c": expected_temp}} |
| 24 | + |
| 25 | + return FakeResponse() |
| 26 | + |
| 27 | + monkeypatch.setattr("weather.httpx.get", fake_get) |
| 28 | + |
| 29 | + service = WeatherService(api_key="fake-key") |
| 30 | + temp = service.get_temperature(city) |
| 31 | + |
| 32 | + assert temp == expected_temp |
| 33 | + |
| 34 | + |
| 35 | +# ✅ pytest.raises |
| 36 | +def test_get_temperature_raises_http_error(monkeypatch): |
| 37 | + def fake_get(url, params): |
| 38 | + class FakeResponse: |
| 39 | + def raise_for_status(self): |
| 40 | + raise Exception("API error") |
| 41 | + |
| 42 | + return FakeResponse() |
| 43 | + |
| 44 | + monkeypatch.setattr("weather.httpx.get", fake_get) |
| 45 | + |
| 46 | + service = WeatherService(api_key="fake-key") |
| 47 | + |
| 48 | + with pytest.raises(Exception): |
| 49 | + service.get_temperature("Tokyo") |
| 50 | + |
| 51 | + |
| 52 | +# ✅ pytest.mark.skip |
| 53 | +@pytest.mark.skip(reason="Skipping this test for demonstration purposes.") |
| 54 | +def test_skipped_example(): |
| 55 | + assert False |
| 56 | + |
| 57 | + |
| 58 | +# ✅ pytest.mark.skipif |
| 59 | +@pytest.mark.skipif(sys.platform == "win32", reason="Does not run on Windows") |
| 60 | +def test_only_runs_on_non_windows(): |
| 61 | + assert True |
| 62 | + |
| 63 | + |
| 64 | +# ✅ pytest.mark.xfail |
| 65 | +@pytest.mark.xfail(reason="Known bug: API sometimes returns wrong temperature") |
| 66 | +def test_expected_failure_example(): |
| 67 | + assert 2 + 2 == 5 |
| 68 | + |
| 69 | + |
| 70 | +# ✅ Hypothesis property-based test |
| 71 | +# @given(floats(min_value=-50, max_value=50)) |
| 72 | +# def test_temperature_range_property(temp): |
| 73 | +# assert -50 <= temp <= 50 |
0 commit comments