homepage/tests/test_weather.py

60 lines
2.6 KiB
Python

import pytest
from main import app, get_weather, weather_cache
import main as main_mod
import time
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def test_get_weather_success(monkeypatch):
# Мокаем requests.get
class MockResp:
def raise_for_status(self):
pass
def json(self):
return {'current': {'temp_c': 10, 'cloud': 50}}
monkeypatch.setattr(main_mod, 'requests', type('R', (), {'get': lambda *a, **k: MockResp()}))
# Мокаем config
monkeypatch.setattr(main_mod, 'load_config', lambda: {'weather': {'api_key': 'x', 'lat': 1, 'lon': 2, 'cache_ttl': 1}})
main_mod.weather_cache = {'data': None, 'ts': 0}
res = get_weather()
assert res == {'temp': 10, 'cloud': 50}
def test_get_weather_cache(monkeypatch):
# Проверяем что кэш работает
monkeypatch.setattr(main_mod, 'load_config', lambda: {'weather': {'api_key': 'x', 'lat': 1, 'lon': 2, 'cache_ttl': 10}})
main_mod.weather_cache = {'data': {'temp': 5, 'cloud': 20}, 'ts': time.time()}
res = get_weather()
assert res == {'temp': 5, 'cloud': 20}
def test_get_weather_ttl(monkeypatch):
# Проверяем что TTL работает
monkeypatch.setattr(main_mod, 'load_config', lambda: {'weather': {'api_key': 'x', 'lat': 1, 'lon': 2, 'cache_ttl': 0}})
main_mod.weather_cache = {'data': {'temp': 5, 'cloud': 20}, 'ts': time.time() - 100}
called = {}
class MockResp:
def raise_for_status(self): pass
def json(self): return {'current': {'temp_c': 7, 'cloud': 33}}
monkeypatch.setattr(main_mod, 'requests', type('R', (), {'get': lambda *a, **k: MockResp()}))
res = get_weather()
assert res == {'temp': 7, 'cloud': 33}
def test_get_weather_error(monkeypatch):
# Проверяем обработку ошибки
def bad_get(*a, **k): raise Exception('fail')
monkeypatch.setattr(main_mod, 'requests', type('R', (), {'get': bad_get}))
monkeypatch.setattr(main_mod, 'load_config', lambda: {'weather': {'api_key': 'x', 'lat': 1, 'lon': 2, 'cache_ttl': 1}})
main_mod.weather_cache = {'data': None, 'ts': 0}
res = get_weather()
assert res is None
def test_index_weather(client, monkeypatch):
# Проверяем что погода отображается на главной
monkeypatch.setattr(main_mod, 'get_weather', lambda: {'temp': 15, 'cloud': 80})
resp = client.get('/')
assert resp.status_code == 200
assert b'15' in resp.data
assert b'80%'.replace(b'%', b'%') in resp.data