Skip to content

Commit c3aef62

Browse files
authored
IN-318 caching tests on routes
IN-318 caching tests on routes
2 parents d813dd3 + e795b8b commit c3aef62

28 files changed

+398
-122
lines changed

integration_tests/integration_tests.md

+5-2
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,10 @@ To set up for the integration tests you should check a few things first:
3333

3434
### Gotchas
3535

36-
Make sure you are able to assume digideps dev role with your credentials or tests will not work.
37-
You may need to update some Sirius data. This is temporary, we're going to get them to create some stable
36+
* Make sure you are able to assume digideps dev role with your credentials or tests will not work.
37+
38+
* You may need to update some Sirius data. This is temporary, we're going to get them to create some stable
3839
test data for us, but for now, you need to log into Cloud9 and run:
3940
`UPDATE cases SET onlinelpaid = 'A33718377316' WHERE uid = 700000000013;`
41+
42+
* If that doesn't work, check there are some cases to update using `SELECT uid as case_number, onlinelpaid, casetype, casesubtype, donor_id FROM cases WHERE casetype = 'LPA';`

integration_tests/v1/test_healthcheck.py

+11-6
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,15 @@
77
@pytest.mark.parametrize("test_config", configs_to_test)
88
def test_healthcheck_route(test_config):
99

10-
status, response = send_a_request(
11-
test_config=test_config,
12-
url=f"{test_config['healthcheck_endpoint']['url']}",
13-
method=test_config["healthcheck_endpoint"]["method"],
14-
)
10+
if test_config["name"] == "original collections api on aws dev":
11+
print("Healthcheck does not exist on original collections api on aws dev")
12+
pass
13+
else:
1514

16-
assert status == 200
15+
status, response = send_a_request(
16+
test_config=test_config,
17+
url=f"{test_config['healthcheck_endpoint']['url']}",
18+
method=test_config["healthcheck_endpoint"]["method"],
19+
)
20+
21+
assert status == 200

integration_tests/v1/test_use_an_lpa.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ def test_use_an_lpa_route(test_config):
1717
assert status == 200
1818
response_dict = json.loads(response)
1919
# TODO we are getting a list from sirius?
20-
assert is_valid_schema(response_dict[0], "use_an_lpa_schema.json")
21-
assert response_dict[0]["uId"].replace("-", "") == valid_id
20+
assert is_valid_schema(response_dict, "use_an_lpa_schema.json")
21+
assert response_dict["uId"].replace("-", "") == valid_id
2222

2323

2424
@pytest.mark.smoke_test

lambda_functions/v1/functions/lpa/app/__init__.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44

55
from .api.resources import api as api_blueprint
6-
from .api.sirius_service import SiriusService
6+
from .sirius_service.sirius_handler import SiriusService
77
from .config import Config
88

99

@@ -15,8 +15,9 @@ def create_app(flask=Flask, config=Config):
1515
app.register_blueprint(api_blueprint)
1616

1717
if config.REQUEST_CACHING == "enabled":
18+
1819
app.redis = redis.StrictRedis.from_url(
19-
url=config.REDIS_URL, charset="utf-8", decode_responses=True
20+
url=f"redis://{config.REDIS_URL}", charset="utf-8", decode_responses=True
2021
)
2122

2223
redis_cache = app.redis

lambda_functions/v1/functions/lpa/app/api/handlers.py

+8-10
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,3 @@
1-
import json
2-
import os
3-
4-
import urllib3
5-
61
# from flask import current_app
72
from flask import current_app
83
from werkzeug.exceptions import abort
@@ -11,7 +6,6 @@
116

127
# from .sirius import build_sirius_url, send_request_to_sirius
138
# from . import sirius
14-
from .sirius_service import SiriusService
159

1610
logger = custom_logger()
1711

@@ -27,7 +21,7 @@ def get_by_online_tool_id(lpa_online_tool_id):
2721
if sirius_status_code in [200]:
2822
if len(sirius_response) > 0:
2923
try:
30-
return format_response(sirius_response=sirius_response), 200
24+
return format_online_tool_response(sirius_response=sirius_response), 200
3125
except Exception as e:
3226
logger.error(f"Error formatting sirius response: {e}")
3327
abort(404)
@@ -43,12 +37,12 @@ def get_by_sirius_uid(sirius_uid):
4337
sirius_url = generate_sirius_url(sirius_uid=sirius_uid)
4438

4539
sirius_status_code, sirius_response = current_app.sirius.send_request_to_sirius(
46-
key=sirius_url, url=sirius_url, method="GET"
40+
key=sirius_uid, url=sirius_url, method="GET"
4741
)
4842
if sirius_status_code in [200]:
4943
if len(sirius_response) > 0:
5044
try:
51-
return sirius_response, 200
45+
return format_uid_response(sirius_response=sirius_response), 200
5246
except Exception as e:
5347
logger.error(f"Error formatting sirius response: {e}")
5448
abort(404)
@@ -77,7 +71,11 @@ def generate_sirius_url(lpa_online_tool_id=None, sirius_uid=None):
7771
return url
7872

7973

80-
def format_response(sirius_response):
74+
def format_uid_response(sirius_response):
75+
return sirius_response[0]
76+
77+
78+
def format_online_tool_response(sirius_response):
8179

8280
logger.info(f"type(sirius_response): {type(sirius_response)}")
8381
lpa_data = sirius_response[0]

lambda_functions/v1/functions/lpa/app/api/resources.py

-7
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,6 @@ def handle504(error=None):
6262
def handle_healthcheck_route():
6363
response_message = "OK"
6464

65-
from flask import current_app
66-
67-
logger.info(f"current_app: {current_app}")
68-
logger.info(f"current_app.config: {current_app.config}")
69-
7065
return jsonify(response_message), 200
7166

7267

@@ -75,8 +70,6 @@ def handle_lpa_online_tool(lpa_online_tool_id):
7570
logger.info(f"lpa_online_tool_id: {lpa_online_tool_id}")
7671

7772
response, status = get_by_online_tool_id(lpa_online_tool_id=lpa_online_tool_id)
78-
print(f"response: {response}")
79-
print(f"status: {status}")
8073

8174
return jsonify(response), status
8275

lambda_functions/v1/functions/lpa/app/config.py

-4
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,6 @@ class Config(object):
2121
REQUEST_CACHING = os.environ.get("REQUEST_CACHING", default="disabled")
2222

2323

24-
class ProductionConfig(Config):
25-
pass
26-
27-
2824
class LocalMockConfig(Config):
2925
# override prod values
3026
DEBUG = True
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from .flask_lambda import FlaskLambda
22
from . import create_app
3-
from .config import ProductionConfig
3+
from .config import Config
44

5-
lambda_handler = create_app(flask=FlaskLambda, config=ProductionConfig)
5+
lambda_handler = create_app(flask=FlaskLambda, config=Config)

lambda_functions/v1/functions/lpa/app/sirius_service/__init__.py

Whitespace-only changes.

lambda_functions/v1/functions/lpa/app/api/sirius_service.py lambda_functions/v1/functions/lpa/app/sirius_service/sirius_handler.py

+8-15
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import requests
99
from botocore.exceptions import ClientError
1010

11-
from .helpers import custom_logger
11+
from ..api.helpers import custom_logger
1212

1313
logger = custom_logger("sirius_service")
1414

@@ -159,8 +159,6 @@ def send_request_to_sirius(self, key, url, method, content_type=None, data=None)
159159

160160
cache_enabled = True if self.request_caching == "enabled" else False
161161

162-
redis_service = self.cache
163-
164162
if self._check_sirius_available():
165163
sirius_status_code, sirius_data = self._get_data_from_sirius(
166164
url, method, content_type, data
@@ -170,16 +168,14 @@ def send_request_to_sirius(self, key, url, method, content_type=None, data=None)
170168
logger.info(f"method: {method}")
171169
if cache_enabled and method == "GET" and sirius_status_code == 200:
172170
logger.info(f"Putting data in cache with key: {key}")
173-
self._put_sirius_data_in_cache(
174-
redis_conn=redis_service, key=key, data=sirius_data
175-
)
171+
self._put_sirius_data_in_cache(key=key, data=sirius_data)
176172

177173
return sirius_status_code, sirius_data
178174
else:
179175
if cache_enabled and method == "GET":
180176
logger.info(f"Getting data from cache with key: {key}")
181177
sirius_status_code, sirius_data = self._get_sirius_data_from_cache(
182-
redis_conn=redis_service, key=key
178+
key=key
183179
)
184180

185181
return sirius_status_code, sirius_data
@@ -216,30 +212,27 @@ def _get_data_from_sirius(self, url, method, content_type=None, data=None):
216212
error_message=f"Unable to send request to Sirius", error_details=e
217213
)
218214

219-
def _put_sirius_data_in_cache(self, redis_conn, key, data):
215+
def _put_sirius_data_in_cache(self, key, data):
220216
logger.info(f"_put_sirius_data_in_cache")
221217
cache_name = self.request_caching_name
222218

223219
cache_ttl_in_seconds = self.request_caching_ttl * 60 * 60
224220

225221
data = json.dumps(data)
226222

227-
redis_conn.set(name=f"{cache_name}-{key}", value=data, ex=cache_ttl_in_seconds)
223+
self.cache.set(name=f"{cache_name}-{key}", value=data, ex=cache_ttl_in_seconds)
228224

229225
logger.info(f"setting redis: {cache_name}-{key}")
230226

231-
def _get_sirius_data_from_cache(self, redis_conn, key):
227+
def _get_sirius_data_from_cache(self, key):
232228

233229
cache_name = self.request_caching_name
234230

235231
logger.info(f"getting redis: {cache_name}-{key}")
236-
logger.info(
237-
f'redis_conn.exists(f"{cache_name}-{key}"): {redis_conn.exists(f"{cache_name}-{key}")}'
238-
)
239232

240-
if redis_conn.exists(f"{cache_name}-{key}"):
233+
if self.cache.exists(f"{cache_name}-{key}"):
241234
status_code = 200
242-
result = redis_conn.get(f"{cache_name}-{key}")
235+
result = self.cache.get(f"{cache_name}-{key}")
243236
result = json.loads(result)
244237
else:
245238
status_code = 500

lambda_functions/v1/tests/conftest.py

-5
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,3 @@ def aws_credentials(monkeypatch):
99
monkeypatch.setenv("AWS_SESSION_TOKEN", "testing")
1010
monkeypatch.setenv("AWS_DEFAULT_REGION", "eu-west-1")
1111
monkeypatch.setenv("AWS_XRAY_CONTEXT_MISSING", "LOG_ERROR")
12-
monkeypatch.setenv("SIRIUS_BASE_URL", "http://not-really-sirius.com")
13-
monkeypatch.setenv("SIRIUS_API_VERSION", "v1")
14-
monkeypatch.setenv("SESSION_DATA", "publicapi@opgtest.com")
15-
monkeypatch.setenv("ENVIRONMENT", "not-a-real-environment")
16-
monkeypatch.setenv("JWT_SECRET", "THIS_IS_MY_SECRET_KEY")

lambda_functions/v1/tests/routes/conftest.py

+54-5
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,34 @@
11
from textwrap import wrap
22

3+
import fakeredis
34
import pytest
45
from flask import Flask
56

6-
from lambda_functions.v1.functions.lpa.app import api
77
from lambda_functions.v1.functions.lpa.app import create_app
88
from lambda_functions.v1.functions.lpa.app.config import LocalTestingConfig
9+
10+
from lambda_functions.v1.functions.lpa.app.sirius_service import sirius_handler
911
from lambda_functions.v1.tests.helpers import load_data
1012

13+
mock_redis_server = fakeredis.FakeServer()
14+
15+
16+
class NoCache(LocalTestingConfig):
17+
REQUEST_CACHING = "disabled"
18+
1119

1220
@pytest.fixture(scope="session")
1321
def app(*args, **kwargs):
14-
app = create_app(config=LocalTestingConfig)
22+
23+
app = create_app(Flask, config=LocalTestingConfig)
1524

1625
routes = [str(p) for p in app.url_map.iter_rules()]
1726
print(f"routes: {routes}")
1827

28+
app.sirius.cache = fakeredis.FakeStrictRedis(
29+
charset="utf-8", decode_responses=True, server=mock_redis_server
30+
)
31+
1932
yield app
2033

2134

@@ -25,21 +38,45 @@ def test_server(app):
2538
return app.test_client()
2639

2740

41+
@pytest.fixture(scope="session")
42+
def app_no_cache(*args, **kwargs):
43+
app = create_app(Flask, config=NoCache)
44+
45+
routes = [str(p) for p in app.url_map.iter_rules()]
46+
print(f"routes: {routes}")
47+
48+
app.sirius.cache = fakeredis.FakeStrictRedis(
49+
charset="utf-8", decode_responses=True, server=mock_redis_server
50+
)
51+
52+
yield app
53+
54+
55+
@pytest.fixture(scope="function")
56+
def test_server_no_cache(app_no_cache):
57+
return app_no_cache.test_client()
58+
59+
2860
@pytest.fixture(autouse=True)
2961
def patched_get_secret(monkeypatch):
3062
def mock_secret(*args, **kwargs):
3163
print("patched_get_secret returning mock_secret")
3264
return "this_is_a_secret_string"
3365

34-
monkeypatch.setattr(api.sirius_service.SiriusService, "_get_secret", mock_secret)
66+
monkeypatch.setattr(sirius_handler.SiriusService, "_get_secret", mock_secret)
3567

3668

3769
@pytest.fixture()
3870
def patched_send_request_to_sirius(monkeypatch):
3971
def mock_get(*args, **kwargs):
4072
print("Using fake_send_request_to_sirius ")
73+
print(f"args: {args}")
74+
print(f"kwargs: {kwargs}")
75+
76+
url = args[1]
4177

42-
test_id = kwargs["url"].split("=")[1]
78+
# test_id = kwargs["url"].split("=")[1]
79+
test_id = url.split("=")[1]
4380
print(f"test_id: {test_id}")
4481

4582
if test_id[0] == "7":
@@ -75,6 +112,18 @@ def mock_get(*args, **kwargs):
75112
print("test_id is not a valid sirius_uid or lpa-online-tool id")
76113
return 404, ""
77114

115+
monkeypatch.setattr(sirius_handler.SiriusService, "_get_data_from_sirius", mock_get)
116+
117+
118+
@pytest.fixture
119+
def patched_send_request_to_sirius_available(monkeypatch):
120+
monkeypatch.setattr(
121+
sirius_handler.SiriusService, "_check_sirius_available", lambda x: True
122+
)
123+
124+
125+
@pytest.fixture
126+
def patched_send_request_to_sirius_unavailable(monkeypatch):
78127
monkeypatch.setattr(
79-
api.sirius_service.SiriusService, "send_request_to_sirius", mock_get
128+
sirius_handler.SiriusService, "_check_sirius_available", lambda x: False
80129
)
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,34 @@
1-
def test_healthcheck_route(test_server):
1+
from lambda_functions.v1.functions.lpa.app.sirius_service import sirius_handler
2+
import pytest
3+
4+
5+
@pytest.mark.parametrize("sirius_available", [(True), (False)])
6+
def test_healthcheck_route_with_cache(test_server, monkeypatch, sirius_available):
7+
8+
monkeypatch.setattr(
9+
sirius_handler.SiriusService,
10+
"_check_sirius_available",
11+
lambda x: sirius_available,
12+
)
213

314
response = test_server.get(f"/v1/healthcheck")
415

516
assert response.status_code == 200
617
assert response.get_json() == "OK"
18+
19+
20+
@pytest.mark.parametrize("sirius_available", [(True), (False)])
21+
def test_healthcheck_route_no_cache(
22+
test_server_no_cache, monkeypatch, sirius_available
23+
):
24+
25+
monkeypatch.setattr(
26+
sirius_handler.SiriusService,
27+
"_check_sirius_available",
28+
lambda x: sirius_available,
29+
)
30+
31+
response = test_server_no_cache.get(f"/v1/healthcheck")
32+
33+
assert response.status_code == 200
34+
assert response.get_json() == "OK"

0 commit comments

Comments
 (0)