|
| 1 | +import io |
| 2 | +import json |
| 3 | +from unittest.mock import MagicMock |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from eligibility_signposting_api.repos.campaign_repo import CampaignRepo, BucketName |
| 8 | +from tests.fixtures.builders.model.rule import CampaignConfigFactory |
| 9 | + |
| 10 | + |
| 11 | +def make_s3_body(payload: dict): |
| 12 | + return {"Body": io.BytesIO(json.dumps(payload).encode("utf-8"))} |
| 13 | + |
| 14 | + |
| 15 | +class TestCampaignRepo: |
| 16 | + @pytest.fixture |
| 17 | + def mock_s3_client(self): |
| 18 | + return MagicMock() |
| 19 | + |
| 20 | + @pytest.fixture |
| 21 | + def repo(self, mock_s3_client): |
| 22 | + return CampaignRepo( |
| 23 | + s3_client=mock_s3_client, |
| 24 | + bucket_name=BucketName("test-bucket"), |
| 25 | + ) |
| 26 | + |
| 27 | + @pytest.fixture |
| 28 | + def rules_payload(self): |
| 29 | + campaign_config = CampaignConfigFactory.build() |
| 30 | + return { |
| 31 | + "campaign_config": campaign_config.model_dump(mode="json") |
| 32 | + } |
| 33 | + |
| 34 | + def test_get_campaign_configs_loads_from_s3(self, repo, mock_s3_client, rules_payload): |
| 35 | + mock_s3_client.list_objects.return_value = { |
| 36 | + "Contents": [{"Key": "rsv.json"}] |
| 37 | + } |
| 38 | + mock_s3_client.get_object.return_value = make_s3_body(rules_payload) |
| 39 | + |
| 40 | + result = list(repo.get_campaign_configs()) |
| 41 | + |
| 42 | + assert len(result) == 1 |
| 43 | + assert result[0].id == rules_payload["campaign_config"]["id"] |
| 44 | + |
| 45 | + mock_s3_client.list_objects.assert_called_once_with(Bucket="test-bucket") |
| 46 | + mock_s3_client.get_object.assert_called_once_with( |
| 47 | + Bucket="test-bucket", |
| 48 | + Key="rsv.json", |
| 49 | + ) |
| 50 | + |
| 51 | + def test_get_campaign_configs_uses_cache_within_ttl( |
| 52 | + self, |
| 53 | + repo, |
| 54 | + mock_s3_client, |
| 55 | + monkeypatch, |
| 56 | + ): |
| 57 | + repo._cache_ttl_seconds = 60 |
| 58 | + |
| 59 | + first_config = CampaignConfigFactory.build(version=1) |
| 60 | + |
| 61 | + mock_s3_client.list_objects.return_value = { |
| 62 | + "Contents": [{"Key": "rsv.json"}] |
| 63 | + } |
| 64 | + mock_s3_client.get_object.return_value = make_s3_body( |
| 65 | + {"campaign_config": first_config.model_dump(mode="json")} |
| 66 | + ) |
| 67 | + |
| 68 | + monkeypatch.setattr("time.time", lambda: 1000.0) |
| 69 | + |
| 70 | + first = list(repo.get_campaign_configs()) |
| 71 | + second = list(repo.get_campaign_configs()) |
| 72 | + |
| 73 | + assert first[0].version == 1 |
| 74 | + assert second[0].version == 1 |
| 75 | + assert mock_s3_client.list_objects.call_count == 1 |
| 76 | + assert mock_s3_client.get_object.call_count == 1 |
0 commit comments