Skip to content

Commit b1c2f73

Browse files
A couple more tests
1 parent 51397c2 commit b1c2f73

File tree

2 files changed

+116
-47
lines changed

2 files changed

+116
-47
lines changed

mips_api/__init__.py

Lines changed: 32 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -616,7 +616,7 @@ def process_balance(bal_dict, coa_dict):
616616
# check for success
617617
if "executionResult" not in bal_dict:
618618
LOG.error(f"No execution result found: '{bal_dict}'")
619-
raise KeyError("No 'executionResult' found")
619+
raise KeyError("No 'executionResult' key found")
620620

621621
result = bal_dict["executionResult"]
622622
if result != "SUCCESS":
@@ -629,7 +629,8 @@ def process_balance(bal_dict, coa_dict):
629629
_detail = []
630630
for k, v in bal_dict["extraInformation"].items():
631631
if k != "Level1":
632-
LOG.info(f"Unexpected key (not 'Level1'): {k}")
632+
LOG.error(f"Unexpected key (not 'Level1'): {k}")
633+
raise KeyError("No 'Level1' key found")
633634
else:
634635
_detail = v
635636

@@ -669,6 +670,7 @@ def process_balance(bal_dict, coa_dict):
669670
name = None
670671
if k not in coa_dict:
671672
LOG.error(f"Key {k} not found in chart of accounts")
673+
LOG.debug(f"List of keys: {coa_dict.keys()}")
672674
name = k
673675
else:
674676
name = coa_dict[k]
@@ -755,39 +757,46 @@ def lambda_handler(event, context):
755757
show_no_program = _param_show_no_program_bool(params)
756758
show_other = _param_show_other_bool(params)
757759

758-
# Process the chart of accounts from MIP, it's used in all cases
759-
raw_chart = chart_cache(
760-
mip_org,
761-
ssm_secrets,
762-
s3_bucket,
763-
s3_chart_path,
764-
hide_inactive,
765-
)
766-
LOG.debug(f"Raw chart data: {raw_chart}")
767-
coa_chart = process_chart(
768-
raw_chart,
769-
omit_codes_list,
770-
priority_codes,
771-
hide_inactive,
772-
code_other,
773-
show_other,
774-
code_no_program,
775-
show_no_program,
776-
)
777-
778760
# parse the path and return appropriate data
779761
if "path" in event:
780762
event_path = event["path"]
781763

782764
if event_path == api_routes["ApiTrialBalances"]:
765+
raw_chart = chart_cache(
766+
mip_org,
767+
ssm_secrets,
768+
s3_bucket,
769+
s3_chart_path,
770+
False,
771+
)
772+
LOG.debug(f"Raw chart data: {raw_chart}")
773+
783774
# Process current balances
784775
raw_bal = balance_cache(
785776
mip_org, ssm_secrets, s3_bucket, s3_balance_path
786777
)
787-
bal_csv = format_balance(raw_bal, coa_chart)
778+
bal_csv = format_balance(raw_bal, raw_chart)
788779

789780
return _build_return_text(200, bal_csv)
790781
else:
782+
raw_chart = chart_cache(
783+
mip_org,
784+
ssm_secrets,
785+
s3_bucket,
786+
s3_chart_path,
787+
hide_inactive,
788+
)
789+
LOG.debug(f"Raw chart data: {raw_chart}")
790+
coa_chart = process_chart(
791+
raw_chart,
792+
omit_codes_list,
793+
priority_codes,
794+
hide_inactive,
795+
code_other,
796+
show_other,
797+
code_no_program,
798+
show_no_program,
799+
)
791800

792801
if event_path == api_routes["ApiChartOfAccounts"]:
793802
# conditionally filter the output

tests/unit/test_handler.py

Lines changed: 84 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,17 @@
149149
]
150150
}
151151

152+
mock_balance_empty = {}
153+
154+
mock_balance_invalid1 = {
155+
"executionResult": "INVALID",
156+
}
157+
158+
mock_balance_invalid2 = {
159+
"executionResult": "SUCCESS",
160+
"extraInformation": {"foo": "bar"},
161+
}
162+
152163
mock_balance_success = {
153164
"executionResult": "SUCCESS",
154165
"extraInformation": {
@@ -163,7 +174,7 @@
163174
"DBDETAIL_SUM_POSTEDAMT": mock_balance_start,
164175
"DBDETAIL_SUM_SEGMENT_N0": "",
165176
"DBDETAIL_SUM_SEGMENT_N1": "",
166-
"DBDETAIL_SUM_SEGMENT_N2": "123456",
177+
"DBDETAIL_SUM_SEGMENT_N2": "12345600",
167178
"DBDETAIL_SUM_SEGMENT_N3": "",
168179
"DBDETAIL_SUM_SEGMENT_N4": "",
169180
"DBDETAIL_SUM_SEGMENT_N5": "",
@@ -180,7 +191,7 @@
180191
"DBDETAIL_SUM_POSTEDAMT": mock_balance_activity,
181192
"DBDETAIL_SUM_SEGMENT_N0": "",
182193
"DBDETAIL_SUM_SEGMENT_N1": "",
183-
"DBDETAIL_SUM_SEGMENT_N2": "123456",
194+
"DBDETAIL_SUM_SEGMENT_N2": "12345600",
184195
"DBDETAIL_SUM_SEGMENT_N3": "",
185196
"DBDETAIL_SUM_SEGMENT_N4": "",
186197
"DBDETAIL_SUM_SEGMENT_N5": "",
@@ -197,7 +208,7 @@
197208
"DBDETAIL_SUM_POSTEDAMT": mock_balance_end,
198209
"DBDETAIL_SUM_SEGMENT_N0": "",
199210
"DBDETAIL_SUM_SEGMENT_N1": "",
200-
"DBDETAIL_SUM_SEGMENT_N2": "123456",
211+
"DBDETAIL_SUM_SEGMENT_N2": "12345600",
201212
"DBDETAIL_SUM_SEGMENT_N3": "",
202213
"DBDETAIL_SUM_SEGMENT_N4": "",
203214
"DBDETAIL_SUM_SEGMENT_N5": "",
@@ -345,7 +356,7 @@
345356
"EndBalance",
346357
],
347358
[
348-
"123456",
359+
"12345600",
349360
"Program Part A",
350361
expected_start_date,
351362
expected_end_date,
@@ -356,7 +367,7 @@
356367
]
357368

358369
expected_balance_csv = f"""AccountNumber,AccountName,PeriodStart,PeriodEnd,StartBalance,Activity,EndBalance\r
359-
123456,Program Part A,{expected_start_date},{expected_end_date},{mock_balance_start},{mock_balance_activity},{mock_balance_end}\r
370+
12345600,Program Part A,{expected_start_date},{expected_end_date},{mock_balance_start},{mock_balance_activity},{mock_balance_end}\r
360371
"""
361372

362373
# mock query-string parameters
@@ -509,21 +520,18 @@ def test_bad_secrets(mocker):
509520

510521
def test_requests(mocker, requests_mock):
511522
"""
512-
Test getting chart of accounts from upstream API
523+
Test _chart_requests and _balance_requests
513524
514525
Relies on `requests-mock.Mocker` fixture to inject mock `requests` responses.
515526
Because requests-mock creates a requests transport adapter, responses are
516-
global and not thread-safe. Run tests sequentially to maintain control of
517-
response order.
527+
global (across all tests). Run all related assertions sequentially to maintain
528+
control of the response order.
518529
"""
519530

520531
# inject mock responses into `requests`
521532
login_mock = requests_mock.post(mips_api._mip_url_login, json=mock_token)
522533
segment_mock = requests_mock.get(mips_api._mip_url_coa_segments, json=mock_segments)
523534
account_mock = requests_mock.get(mips_api._mip_url_coa_accounts, json=mock_accounts)
524-
balance_mock = requests_mock.post(
525-
mips_api._mip_url_current_balance, json=mock_balance_success
526-
)
527535
logout_mock = requests_mock.post(mips_api._mip_url_logout)
528536

529537
# also mock today's date
@@ -547,13 +555,14 @@ def test_requests(mocker, requests_mock):
547555
assert logout_mock.call_count == 1
548556

549557
# get current balance from mip
558+
balance_mock = requests_mock.post(
559+
mips_api._mip_url_current_balance, json=mock_balance_success
560+
)
550561
balance_dict = mips_api._balance_requests(mock_org_name, mock_secrets)
551562
assert balance_mock.call_count == 1
552563
assert balance_dict == mock_balance_success
553564

554-
# begin a second test with an alternate requests response
555-
556-
# inject new mock response with an Exception
565+
# inject new mock response with an Exception for coa segments
557566
requests_mock.get(mips_api._mip_url_coa_segments, exc=Exception)
558567

559568
# assert logout is called when an exception is raised
@@ -587,6 +596,40 @@ def test_cache_write(mocker):
587596
mips_api._s3_cache_write(expected_coa_dict_raw, mock_s3_bucket, mock_s3_chart)
588597

589598

599+
@pytest.mark.parametrize(
600+
"api_response,cache_response",
601+
[
602+
(mock_balance_success, None),
603+
(None, mock_balance_success),
604+
(mock_balance_success, mock_balance_success),
605+
],
606+
)
607+
def test_balance_cache(mocker, api_response, cache_response):
608+
"""Test balance_cache() with no upstream response"""
609+
mocker.patch(
610+
"mips_api._balance_requests",
611+
autospec=True,
612+
return_value=api_response,
613+
)
614+
mocker.patch(
615+
"mips_api._s3_cache_read",
616+
autospec=True,
617+
return_value=cache_response,
618+
)
619+
mocker.patch(
620+
"mips_api._s3_cache_write",
621+
autospec=True,
622+
)
623+
624+
found_dict = mips_api.balance_cache(
625+
mock_org_name,
626+
mock_secrets,
627+
mock_s3_bucket,
628+
mock_s3_chart,
629+
)
630+
assert found_dict == mock_balance_success
631+
632+
590633
@pytest.mark.parametrize(
591634
"chart_response,cache_response",
592635
[
@@ -724,6 +767,24 @@ def test_process_chart(
724767
assert processed_chart == expected_dict
725768

726769

770+
@pytest.mark.parametrize(
771+
"bal_dict, coa_dict, fail",
772+
[
773+
(mock_balance_empty, expected_coa_dict_full, True),
774+
(mock_balance_invalid1, expected_coa_dict_full, True),
775+
(mock_balance_invalid2, expected_coa_dict_full, True),
776+
(mock_balance_success, expected_coa_dict_full, False),
777+
],
778+
)
779+
def test_process_balance(bal_dict, coa_dict, fail):
780+
if fail:
781+
with pytest.raises(Exception):
782+
mips_api.process_balance(bal_dict, coa_dict)
783+
else:
784+
found_rows = mips_api.process_balance(bal_dict, coa_dict)
785+
assert found_rows == expected_balance_rows
786+
787+
727788
@pytest.mark.parametrize(
728789
"params,expected_bool",
729790
[
@@ -820,7 +881,7 @@ def test_lambda_handler_no_env(invalid_event):
820881
assert ret["statusCode"] == 500
821882

822883

823-
def _test_with_env(mocker, event, code, body=None, error=None, use_json=True):
884+
def _test_with_env(mocker, event, code, body=None, error=None, text=None):
824885
"""Keep lambda_handler tests DRY"""
825886

826887
# mock environment variables
@@ -860,17 +921,18 @@ def _test_with_env(mocker, event, code, body=None, error=None, use_json=True):
860921
ret = mips_api.lambda_handler(event, None)
861922
assert ret["statusCode"] == code
862923

863-
if use_json:
924+
if text is not None:
925+
assert ret["body"] == text
926+
927+
else:
864928
json_body = json.loads(ret["body"])
865929

930+
if body is not None:
931+
assert json_body == body
932+
866933
if error is not None:
867934
assert json_body["error"] == error
868935

869-
elif body is not None:
870-
assert json_body == body
871-
else:
872-
assert ret["body"] == body
873-
874936

875937
def test_lambda_handler_invalid_path(invalid_event, mocker):
876938
"""Test event with no path"""
@@ -904,9 +966,7 @@ def test_lambda_handler_accounts_priority(accounts_priority_event, mocker):
904966
def test_lambda_handler_balance(balances_event, mocker):
905967
"""Test tag-list event"""
906968

907-
_test_with_env(
908-
mocker, balances_event, 200, body=expected_balance_csv, use_json=False
909-
)
969+
_test_with_env(mocker, balances_event, 200, text=expected_balance_csv)
910970

911971

912972
def test_lambda_handler_tags(tags_event, mocker):

0 commit comments

Comments
 (0)