|
| 1 | +import dotenv |
| 2 | + |
| 3 | +dotenv.load_dotenv('tests/sample.env') |
| 4 | + |
| 5 | + |
| 6 | +def make_client(tmp_path): |
| 7 | + from budgetkey_api.flask_app import create_flask_app |
| 8 | + |
| 9 | + app = create_flask_app(session_file_dir=str(tmp_path / 'sessions'), cache_dir=str(tmp_path / 'cache'), |
| 10 | + services='none') |
| 11 | + app.config.update({'TESTING': True}) |
| 12 | + app.testing = True |
| 13 | + return app.test_client() |
| 14 | + |
| 15 | + |
| 16 | +def test_datarecords_bad_key(tmp_path): |
| 17 | + client = make_client(tmp_path) |
| 18 | + resp = client.get('/api/datarecords/no_such_key') |
| 19 | + assert resp.status_code == 404 |
| 20 | + |
| 21 | + |
| 22 | +def test_datarecords_fetches_and_caches(tmp_path, monkeypatch): |
| 23 | + from budgetkey_api.modules import datarecords |
| 24 | + |
| 25 | + calls = [] |
| 26 | + |
| 27 | + class FakeResponse: |
| 28 | + def raise_for_status(self): |
| 29 | + pass |
| 30 | + |
| 31 | + def json(self): |
| 32 | + return {'result': [{'key': 'subject::foo'}]} |
| 33 | + |
| 34 | + def fake_get(url, **kwargs): |
| 35 | + calls.append(url) |
| 36 | + return FakeResponse() |
| 37 | + |
| 38 | + monkeypatch.setattr(datarecords.requests, 'get', fake_get) |
| 39 | + |
| 40 | + client = make_client(tmp_path) |
| 41 | + for _ in range(2): |
| 42 | + resp = client.get('/api/datarecords/subject') |
| 43 | + assert resp.status_code == 200 |
| 44 | + assert resp.json == {'result': [{'key': 'subject::foo'}]} |
| 45 | + assert resp.headers['Cache-Control'] == f'max-age={datarecords.TIMEOUT}' |
| 46 | + |
| 47 | + # Second call is served from the cache |
| 48 | + assert calls == [f'{datarecords.DATARECORDS_URL}/subject'] |
| 49 | + |
| 50 | + |
| 51 | +def test_datarecords_upstream_failure(tmp_path, monkeypatch): |
| 52 | + from budgetkey_api.modules import datarecords |
| 53 | + |
| 54 | + def fake_get(url, **kwargs): |
| 55 | + raise ConnectionError('boom') |
| 56 | + |
| 57 | + monkeypatch.setattr(datarecords.requests, 'get', fake_get) |
| 58 | + |
| 59 | + client = make_client(tmp_path) |
| 60 | + resp = client.get('/api/datarecords/intervention') |
| 61 | + assert resp.status_code == 502 |
0 commit comments