Skip to content

Commit 3570bc6

Browse files
authored
Merge pull request #477 from mrcrnkovich/425_458_SL_mock
adding fake data to the common_api
2 parents 3a06ef8 + 916b735 commit 3570bc6

File tree

4 files changed

+178
-18
lines changed

4 files changed

+178
-18
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,4 @@ start_env.sh
2222
/src/server/local_files/
2323
.mypy_cache/
2424
*secrets*
25-
*kustomization*
25+
*kustomization*

src/server/api/common_api.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,22 @@
66
import time
77
from datetime import datetime
88

9+
from api.fake_data import sl_mock_data
10+
911
try:
1012
from secrets_dict import SHELTERLUV_SECRET_TOKEN
1113
except ImportError:
1214
# Not running locally
1315
print("Couldn't get SHELTERLUV_SECRET_TOKEN from file, trying environment **********")
14-
from os import environ
15-
16-
try:
17-
SHELTERLUV_SECRET_TOKEN = environ['SHELTERLUV_SECRET_TOKEN']
18-
except KeyError:
19-
# Nor in environment
20-
# You're SOL for now
21-
print("Couldn't get secrets from file or environment")
22-
16+
from os import getenv
2317

18+
SHELTERLUV_SECRET_TOKEN = getenv('SHELTERLUV_SECRET_TOKEN')
19+
if not SHELTERLUV_SECRET_TOKEN:
20+
print("Couldn't get secrets from file or environment",
21+
"Defaulting to Fake Data")
2422

2523
from api import jwt_ops
2624

27-
2825
@common_api.route('/api/timeout_test/<duration>', methods=['GET'])
2926
def get_timeout(duration):
3027
start = datetime.now().strftime("%H:%M:%S");
@@ -178,7 +175,6 @@ def get_360(matching_id):
178175

179176
return jsonify({'result': result})
180177

181-
182178
@common_api.route('/api/person/<matching_id>/animals', methods=['GET'])
183179
@jwt_ops.jwt_required()
184180
def get_animals(matching_id):
@@ -187,6 +183,9 @@ def get_animals(matching_id):
187183
"animal_details": {}
188184
}
189185

186+
if not SHELTERLUV_SECRET_TOKEN:
187+
return jsonify(sl_mock_data('animals'))
188+
190189
with engine.connect() as connection:
191190
query = text("select * from pdp_contacts where matching_id = :matching_id and source_type = 'shelterluvpeople' and archived_date is null")
192191
query_result = connection.execute(query, matching_id=matching_id)
@@ -212,6 +211,10 @@ def get_animals(matching_id):
212211
def get_person_animal_events(matching_id, animal_id):
213212
result = {}
214213
events = []
214+
215+
if not SHELTERLUV_SECRET_TOKEN:
216+
return jsonify(sl_mock_data('events'))
217+
215218
with engine.connect() as connection:
216219
query = text("select * from pdp_contacts where matching_id = :matching_id and source_type = 'shelterluvpeople' and archived_date is null")
217220
query_result = connection.execute(query, matching_id=matching_id)

src/server/api/fake_data.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
""" Fake data that can be returned when an API token is missing for local
2+
development, or for running pytest
3+
4+
Shelterluv Data contains:
5+
Matched: Animal & Event End point
6+
"""
7+
8+
shelterluv_data = {
9+
'animals': {
10+
"animal_details": {
11+
'12345': {
12+
"Age": 24,
13+
"DOBUnixTime": 1568480456,
14+
"Name": "Lola aka Fake Cat",
15+
"Type": "Cat",
16+
"Photos":
17+
["https://images.unsplash.com/photo-1456926631375-92c8ce872def?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8OHx8YW5pbWFsfGVufDB8fDB8fA%3D%3D&w=1000&q=80"],
18+
"Status": "Healthy In Home",
19+
},
20+
},
21+
"person_details": {
22+
"shelterluv_short_id": 2,
23+
},
24+
},
25+
'events': {
26+
'12345':[
27+
{
28+
'AssociatedRecords': [
29+
{'Id': 12345, 'Type': 'Animal' },
30+
{'Id': 12345, 'Type': 'Person'},
31+
],
32+
'Subtype': 'Foster Home',
33+
'Time': '1602694822',
34+
'Type': 'Outcome.Adoption',
35+
'User': 'Fake User',
36+
},
37+
]
38+
},
39+
}
40+
41+
42+
def sl_mock_data(end_point: str)-> dict:
43+
""" Shelterluv mock data.
44+
Takes the end_point as a str of `animals` or `events` and returns
45+
a dict representing a test data for that end_point.
46+
"""
47+
48+
return shelterluv_data.get(end_point)

src/server/test_api.py

Lines changed: 115 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,15 @@
3131
SERVER_URL = "http://server:5000"
3232
IS_LOCAL = False
3333

34+
35+
try:
36+
from secrets_dict import SHELTERLUV_SECRET_TOKEN
37+
except ImportError:
38+
SHELTERLUV_SECRET_TOKEN = os.getenv("SHELTERLUV_SECRET_TOKEN")
39+
finally:
40+
SL_Token = True if SHELTERLUV_SECRET_TOKEN else False
41+
42+
3443
### DNS lookup tests ##############################
3544

3645
def test_bad_dns():
@@ -138,11 +147,6 @@ def test_inact_userblocked(state: State):
138147
response = requests.post(SERVER_URL + "/api/user/login", json=data)
139148
assert response.status_code == 401
140149

141-
142-
143-
144-
145-
146150
### Admin-level tests ######################################
147151

148152
def test_adminlogin(state: State):
@@ -261,4 +265,109 @@ def test_statistics(state: State):
261265
auth_hdr = {'Authorization' : b_string}
262266

263267
response = requests.get(SERVER_URL + "/api/statistics", headers=auth_hdr)
264-
assert response.status_code == 200
268+
assert response.status_code == 200
269+
270+
271+
### Shelterluv API tests ######################################
272+
273+
@pytest.mark.skipif(SL_Token, reason="Not run when SL_Token Present")
274+
def test_user_get_person_animal_events(state: State):
275+
""" Test that the api returns mock data if the Shelterluv Token
276+
is missing from secrets
277+
"""
278+
279+
# Build auth string value including token from state
280+
b_string = 'Bearer ' + state.state['base_user']
281+
282+
assert len(b_string) > 24
283+
284+
auth_hdr = {'Authorization' : b_string}
285+
url = SERVER_URL + "/api/person/12345/animal/12345/events"
286+
287+
try:
288+
response = requests.get(url, headers = auth_hdr)
289+
except Exception as err:
290+
print(err)
291+
else:
292+
assert response.status_code == 200
293+
from api.fake_data import sl_mock_data
294+
assert response.json() == sl_mock_data("events")
295+
296+
297+
@pytest.mark.skipif(SL_Token, reason="Not run when SL_Token Present")
298+
def test_user_get_animals(state: State):
299+
""" Test that the api returns mock data if the Shelterluv Token
300+
is missing from secrets
301+
"""
302+
303+
# Build auth string value including token from state
304+
b_string = 'Bearer ' + state.state['base_user']
305+
306+
assert len(b_string) > 24
307+
308+
auth_hdr = {'Authorization' : b_string}
309+
url = SERVER_URL + "/api/person/12345/animals"
310+
311+
try:
312+
response = requests.get(url, headers = auth_hdr)
313+
except Exception as err:
314+
print(err)
315+
else:
316+
assert response.status_code == 200
317+
from api.fake_data import sl_mock_data
318+
assert response.json() == sl_mock_data("animals")
319+
320+
321+
@pytest.mark.skipif(not SL_Token, reason="Run when SL_Token Present")
322+
def test_user_get_animals_sl_token(state: State):
323+
""" Test to confirm api does not return mock values if the Shelterluv Token
324+
is present in the secrets_dict file.
325+
Note this works on the assumption the SL token is not valid, and returns
326+
a default empty value
327+
328+
>> This is tricky - if SL token is correct and person_id is valid, could get animal records returned.
329+
330+
"""
331+
332+
# Build auth string value including token from state
333+
b_string = 'Bearer ' + state.state['base_user']
334+
335+
assert len(b_string) > 24
336+
337+
auth_hdr = {'Authorization' : b_string}
338+
url = SERVER_URL + "/api/person/12345/animals"
339+
340+
try:
341+
response = requests.get(url, headers = auth_hdr)
342+
except Exception as err:
343+
print(err)
344+
pytest.fail('test_user_get_animals_sl_token - Request failed', pytrace=False)
345+
else:
346+
assert response.status_code == 200
347+
assert response.json() == {'person_details': {}, 'animal_details': {}}
348+
349+
350+
@pytest.mark.skipif(not SL_Token, reason="Run when SL_Token Present")
351+
def test_user_get_person_animal_events_sl_token(state: State):
352+
""" Test to confirm api does not return mock values if the Shelterluv Token
353+
is present in the secrets_dict file.
354+
Note this works on the assumption the SL token is not valid, and returns
355+
a default empty value
356+
"""
357+
358+
# Build auth string value including token from state
359+
b_string = 'Bearer ' + state.state['base_user']
360+
361+
assert len(b_string) > 24
362+
363+
auth_hdr = {'Authorization' : b_string}
364+
url = SERVER_URL + "/api/person/12345/animal/12345/events"
365+
366+
try:
367+
response = requests.get(url, headers = auth_hdr)
368+
except Exception as err:
369+
print(err)
370+
pytest.fail('test_user_get_person_animal_events_sl_token - Request failed', pytrace=False)
371+
else:
372+
assert response.status_code == 200
373+
assert response.json() == {}

0 commit comments

Comments
 (0)