-
Notifications
You must be signed in to change notification settings - Fork 54
/
test_update_prevalence.py
1251 lines (1076 loc) · 47 KB
/
test_update_prevalence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from unittest.mock import Mock, patch, call
import pydantic
import json
import logging
import pytest
import requests
from typing import Dict, List, Tuple, Optional
import typing
from datetime import timedelta, date, datetime, tzinfo
from sentry_sdk.integrations.logging import LoggingIntegration
from update_prevalence import (
calc_last_two_weeks_evaluation_range,
calc_last_month_evaluation_range,
calc_cumulative_cases_evaluation_ranges,
parse_jhu_vaccines_us,
parse_can_region_summary_by_county,
AllData,
DataCache,
DateSpan,
County,
LogAggregator,
log_aggregator,
Place,
PopulationFilteredLogging,
AppLocation,
parse_romania_prevalence_data,
parse_canada_prevalence_data,
parse_json,
main,
Vaccination,
)
from logging import Logger
import update_prevalence
@pytest.fixture
def effective_date() -> date:
return date(2020, 12, 15)
@pytest.fixture(autouse=True)
def set_effective_date(effective_date: date) -> None:
update_prevalence.effective_date = effective_date
update_prevalence.last_two_weeks_evaluation_range = calc_last_two_weeks_evaluation_range()
update_prevalence.last_month_evaluation_range = calc_last_month_evaluation_range()
update_prevalence.cumulative_cases_evaluation_ranges = calc_cumulative_cases_evaluation_ranges()
class MyPlace(PopulationFilteredLogging):
pop: int
def __init__(self, pop: int):
self.pop = pop
@property
def population_as_int(self) -> int:
return self.pop
@pytest.fixture
def small_place() -> PopulationFilteredLogging:
return MyPlace(5000)
@pytest.fixture
def medium_place() -> PopulationFilteredLogging:
return MyPlace(10000)
@pytest.fixture
def large_place() -> PopulationFilteredLogging:
return MyPlace(100000)
def add_cumulative_cases(
place: Place, effective_date: date, last_month_cases: int, last_two_weeks_cases: List[int]
) -> None:
one_month_ago = effective_date - timedelta(days=30)
place.cumulative_cases[one_month_ago] = last_month_cases
assert len(last_two_weeks_cases) == 15, "Please simulate real data length for last two weeks range"
for i in range(0, len(last_two_weeks_cases)):
days_since_effective_date = len(last_two_weeks_cases) - i - 1
place.cumulative_cases[
effective_date - timedelta(days=days_since_effective_date)
] = last_two_weeks_cases[i]
if place.cases_last_week is not None and place.tests_in_past_week is not None:
place.test_positivity_rate = place.cases_last_week / place.tests_in_past_week
def add_increasing_cumulative_cases(place: Place, effective_date: date) -> None:
last_month_cases = 1
cases_over_time = [5, 5, 5, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 10, 10]
add_cumulative_cases(place, effective_date, last_month_cases, cases_over_time)
def add_stable_cumulative_cases(place: Place, effective_date: date) -> None:
last_month_cases = 5
cases_over_time = [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
add_cumulative_cases(place, effective_date, last_month_cases, cases_over_time)
@pytest.fixture
def my_county(effective_date: date) -> County:
my_county = County(
fullname="My County, My State",
name="My County",
country="My Country",
state="My State",
population=123,
tests_in_past_week=50,
)
add_stable_cumulative_cases(my_county, effective_date)
return my_county
@pytest.fixture
def my_app_location(effective_date: date, my_county: County) -> AppLocation:
increase = 0.3
app_location = AppLocation(
label=my_county.name,
population=f"{my_county.population:,}",
casesPastWeek=my_county.cases_last_week,
casesIncreasingPercentage=increase * 100,
averageFullyVaccinatedMultiplier=my_county.average_fully_vaccinated_multiplier(),
updatedAt=effective_date.strftime("%B %d, %Y"),
)
return app_location
@pytest.fixture
def data() -> AllData:
data = AllData()
# creates entry
data.get_country("US")
return data
# Don't save the cache from tests to actual disk
class NonSavingDataCache(DataCache):
def save(self) -> None:
pass
@pytest.fixture
def cache(effective_date: date) -> DataCache:
cache = NonSavingDataCache(effective_date=effective_date, data={})
cache.save
return cache
@pytest.fixture
def mock_canada_regions_response() -> Mock:
mock_canada_regions_response = Mock()
mock_canada_regions_response.status_code = 200
mock_canada_regions_response.text = """"region","pruid","hruid","name_canonical","name_canonical_fr","name_short","name_ccodwg","name_other_1","name_other_2","name_other_3","pop","pop_2019_07","pop_2020_07","pop_2021_07"
"AB",48,4831,"South Zone","South Zone","South","South","South zone",,,308346,305937,307967,308346"""
return mock_canada_regions_response
@pytest.fixture
def mock_canada_regions_response_with_duplicate_region() -> Mock:
mock_canada_regions_response_with_duplicate_region = Mock()
mock_canada_regions_response_with_duplicate_region.status_code = 200
mock_canada_regions_response_with_duplicate_region.text = """"region","pruid","hruid","name_canonical","name_canonical_fr","name_short","name_ccodwg","name_other_1","name_other_2","name_other_3","pop","pop_2019_07","pop_2020_07","pop_2021_07"
"AB",48,4831,"South Zone","South Zone","South","South","South zone",,,308346,305937,307967,308346
"AB",48,4831,"South Zone","South Zone","South","South","South zone",,,308346,305937,307967,308346"""
return mock_canada_regions_response_with_duplicate_region
@pytest.fixture
def mock_canada_provinces_response() -> Mock:
mock_canada_provinces_response = Mock()
mock_canada_provinces_response.status_code = 200
mock_canada_provinces_response.text = """"region","pruid","name_canonical","name_canonical_fr","name_ccodwg","pop","pop_2020_01","pop_2020_04","pop_2020_07","pop_2020_10","pop_2021_01","pop_2021_04","pop_2021_07","pop_2021_10","pop_2022_01","pop_2022_04","pop_2022_07"
"AB",48,"Alberta","Alberta","Alberta",4543111,4401362,4414332,4416682,4421857,4429077,4436944,4443773,4466124,4482385,4502858,4543111
"""
return mock_canada_provinces_response
@pytest.fixture
def mock_canada_regional_vaccination_reports_response() -> Mock:
mock_canada_regional_vaccination_reports_response = Mock()
mock_canada_regional_vaccination_reports_response.status_code = 200
mock_canada_regional_vaccination_reports_response.text = json.dumps(
{
"hr_uid": 4831,
"last_updated": "2022-12-30 23:55:06",
"data": [
{
"date": "2022-12-21",
"change_cases": 152,
"change_fatalities": 14,
"change_tests": None,
"change_hospitalizations": -3,
"change_criticals": 1,
"change_recoveries": None,
"change_vaccinations": 532,
"change_vaccinated": 95,
"change_boosters_1": 352,
"change_boosters_2": None,
"total_cases": 40637,
"total_fatalities": 493,
"total_tests": None,
"total_hospitalizations": 70,
"total_criticals": 3,
"total_recoveries": 33617,
"total_vaccinations": 494473,
"total_vaccinated": 194952,
"total_boosters_1": 94748,
"total_boosters_2": None,
}
],
}
)
return mock_canada_regional_vaccination_reports_response
@pytest.fixture
def mock_canada_empty_regional_vaccination_reports_response() -> Mock:
mock_canada_regional_vaccination_reports_response = Mock()
mock_canada_regional_vaccination_reports_response.status_code = 200
mock_canada_regional_vaccination_reports_response.text = json.dumps(
{
"hr_uid": 4831,
"last_updated": "2022-12-30 23:55:06",
"data": [],
}
)
return mock_canada_regional_vaccination_reports_response
@pytest.fixture
def mock_canada_regional_case_reports_response_last_two_weeks() -> Mock:
mock_canada_regional_case_reports_response = Mock()
mock_canada_regional_case_reports_response.status_code = 200
mock_canada_regional_case_reports_response.text = json.dumps(
{
"data": {
"cases": [
{
"name": "cases",
"region": "AB",
"sub_region_1": "4831",
"date": "2022-12-16",
"value": 40610,
"value_daily": 8,
},
{
"name": "cases",
"region": "AB",
"sub_region_1": "4831",
"date": "2022-12-17",
"value": 40623,
"value_daily": 13,
},
],
},
}
)
return mock_canada_regional_case_reports_response
@pytest.fixture
def mock_canada_regional_case_reports_response_a_month_ago() -> Mock:
mock_canada_regional_case_reports_response = Mock()
mock_canada_regional_case_reports_response.status_code = 200
mock_canada_regional_case_reports_response.text = json.dumps(
{
"data": {
"cases": [],
},
}
)
return mock_canada_regional_case_reports_response
@pytest.fixture
def mock_canada_vaccine_distribution_response() -> Mock:
mock_canada_vaccine_distribution_response = Mock()
mock_canada_vaccine_distribution_response.status_code = 200
mock_canada_vaccine_distribution_response.text = json.dumps(
{
"data": [
{
"province": "AB",
"date": "2022-02-03",
"pfizer_biontech": 7056075,
"pfizer_biontech_administered": None,
"moderna": 2687654,
"moderna_administered": None,
"astrazeneca": 318700,
"astrazeneca_administered": None,
"johnson": 10000,
"johnson_administered": None,
"pfizer_biontech_paediatric": 394000,
"pfizer_biontech_paediatric_administered": None,
},
]
}
)
return mock_canada_vaccine_distribution_response
@pytest.fixture
def mock_canada_provincial_reports_response() -> Mock:
mock_canada_provincial_reports_response = Mock()
mock_canada_provincial_reports_response.status_code = 200
mock_canada_provincial_reports_response.text = json.dumps(
{
"data": [
{
"region": "AB",
"date": "2020-12-05",
"cases": 68113,
"cases_daily": 1828,
"deaths": 615,
"deaths_daily": 19,
"hospitalizations": 563,
"hospitalizations_daily": 30,
"icu": 101,
"icu_daily": 2,
"tests_completed": 2371900,
"tests_completed_daily": 23544,
"vaccine_coverage_dose_1": 0,
"vaccine_coverage_dose_1_daily": 0,
"vaccine_coverage_dose_2": 0,
"vaccine_coverage_dose_2_daily": 0,
"vaccine_coverage_dose_3": 0,
"vaccine_coverage_dose_3_daily": 0,
"vaccine_coverage_dose_4": 0,
"vaccine_coverage_dose_4_daily": 0,
"vaccine_administration_total_doses": 0,
"vaccine_administration_total_doses_daily": 0,
"vaccine_administration_dose_1": 0,
"vaccine_administration_dose_1_daily": 0,
"vaccine_administration_dose_2": 0,
"vaccine_administration_dose_2_daily": 0,
"vaccine_administration_dose_3": 0,
"vaccine_administration_dose_3_daily": 0,
"vaccine_administration_dose_4": 0,
"vaccine_administration_dose_4_daily": 0,
},
{
"region": "AB",
"date": "2020-12-08",
"cases": 73126,
"cases_daily": 1494,
"deaths": 653,
"deaths_daily": 13,
"hospitalizations": 654,
"hospitalizations_daily": 45,
"icu": 112,
"icu_daily": 4,
"tests_completed": 2428461,
"tests_completed_daily": 16894,
"vaccine_coverage_dose_1": 0,
"vaccine_coverage_dose_1_daily": 0,
"vaccine_coverage_dose_2": 0,
"vaccine_coverage_dose_2_daily": 0,
"vaccine_coverage_dose_3": 0,
"vaccine_coverage_dose_3_daily": 0,
"vaccine_coverage_dose_4": 0,
"vaccine_coverage_dose_4_daily": 0,
"vaccine_administration_total_doses": 0,
"vaccine_administration_total_doses_daily": 0,
"vaccine_administration_dose_1": 0,
"vaccine_administration_dose_1_daily": 0,
"vaccine_administration_dose_2": 0,
"vaccine_administration_dose_2_daily": 0,
"vaccine_administration_dose_3": 0,
"vaccine_administration_dose_3_daily": 0,
"vaccine_administration_dose_4": 0,
"vaccine_administration_dose_4_daily": 0,
},
{
"region": "AB",
"date": "2020-12-14",
"cases": 622102,
"cases_daily": 114,
"deaths": 5308,
"deaths_daily": 0,
"hospitalizations": 1042,
"hospitalizations_daily": 0,
"icu": 38,
"icu_daily": 0,
"tests_completed": 7363742,
"tests_completed_daily": 933,
"vaccine_coverage_dose_1": 79.5,
"vaccine_coverage_dose_1_daily": 0,
"vaccine_coverage_dose_2": 75.6,
"vaccine_coverage_dose_2_daily": 0,
"vaccine_coverage_dose_3": 39.5,
"vaccine_coverage_dose_3_daily": 0,
"vaccine_coverage_dose_4": 16.4,
"vaccine_coverage_dose_4_daily": 0,
"vaccine_administration_total_doses": 9586987,
"vaccine_administration_total_doses_daily": 0,
"vaccine_administration_dose_1": 3609940,
"vaccine_administration_dose_1_daily": 0,
"vaccine_administration_dose_2": 3435139,
"vaccine_administration_dose_2_daily": 0,
"vaccine_administration_dose_3": 1795849,
"vaccine_administration_dose_3_daily": 0,
"vaccine_administration_dose_4": 746059,
"vaccine_administration_dose_4_daily": 0,
},
],
}
)
return mock_canada_provincial_reports_response
@patch("update_prevalence.requests.get", spec=requests.get)
def test_parse_jhu_vaccines_us(
mock_get: Mock,
data: AllData,
cache: DataCache,
) -> None:
mock_response = Mock()
mock_response.status_code = 200
mock_response.text = """Date,UID,Province_State,Country_Region,Doses_admin,People_at_least_one_dose,People_fully_vaccinated,Total_additional_doses
2022-12-02,84000056,Wyoming,US,835616,350112,305397,142731"""
mock_get.return_value = mock_response
# ditto
wyoming = data.get_state("Wyoming", country="US")
parse_jhu_vaccines_us(cache, data)
assert wyoming.vaccines_total.completed_vaccinations == 305397
@patch("update_prevalence.logger", spec=Logger)
@patch("update_prevalence.requests.get", spec=requests.get)
def test_parse_jhu_vaccines_us_known_unknown_state(
mock_get: Mock,
mock_logger: Mock,
data: AllData,
cache: DataCache,
) -> None:
mock_response = Mock()
mock_response.status_code = 200
mock_response.text = """Date,UID,Province_State,Country_Region,Doses_admin,People_at_least_one_dose,People_fully_vaccinated,Total_additional_doses
2022-12-02,84000056,Wyoming,US,835616,350112,305397,142731
2022-12-02,84070022,Long Term Care (LTC) Program,US,7897367,4317892,3930082,2335790"""
mock_get.return_value = mock_response
# ditto
data.get_state("Wyoming", country="US")
parse_jhu_vaccines_us(cache, data)
mock_logger.warning.assert_not_called()
@patch("update_prevalence.logger", spec=Logger)
@patch("update_prevalence.requests.get", spec=requests.get)
def test_parse_jhu_vaccines_us_unknown_unknown_state(
mock_get: Mock,
mock_logger: Mock,
data: AllData,
cache: DataCache,
) -> None:
mock_response = Mock()
mock_response.status_code = 200
mock_response.text = """Date,UID,Province_State,Country_Region,Doses_admin,People_at_least_one_dose,People_fully_vaccinated,Total_additional_doses
2022-12-02,84000056,Wyoming,US,835616,350112,305397,142731
2022-12-02,8675309,Some Unknown Entry,US,7897367,4317892,3930082,2335790"""
mock_get.return_value = mock_response
# ditto
data.get_state("Wyoming", country="US")
parse_jhu_vaccines_us(cache, data)
mock_logger.warning.assert_called()
@patch("update_prevalence.requests.get", spec=requests.get)
@patch("update_prevalence.sleep", autospec=True)
@patch("update_prevalence.logger", spec=Logger)
def test_parse_json_retry(
mock_logger: Mock,
mock_sleep: Mock,
mock_get: Mock,
cache: DataCache,
) -> None:
mock_response_failure = Mock()
mock_response_failure.status_code = 429
url = "http://fake"
e = requests.exceptions.HTTPError(response=mock_response_failure)
mock_response_failure.raise_for_status.side_effect = e
mock_response_success = Mock()
mock_response_success.status_code = 200
mock_response_success.text = """{"field1": 123}"""
mock_get.side_effect = [mock_response_failure, mock_response_success]
class FakeModel(pydantic.BaseModel):
field1: str
parse_json(cache, FakeModel, url)
mock_logger.info.assert_has_calls(
[
call("Fetching http://fake..."),
call("Fetching http://fake (try 2/4)..."),
]
)
@patch("update_prevalence.logger", spec=Logger)
@patch("update_prevalence.requests.get", spec=requests.get)
def test_parse_can_region_summary_by_county(
mock_get: Mock,
mock_logger: Mock,
data: AllData,
cache: DataCache,
) -> None:
mock_response = Mock()
mock_response.status_code = 200
mock_response.text = json.dumps(
[
{
"fips": "02013",
"country": "US",
"state": "AK",
"population": 3337,
"metrics": {
"testPositivityRatio": None,
},
"actuals": {
"vaccinationsInitiated": 2899,
"vaccinationsCompleted": 2498,
},
},
]
)
_state = data.get_state("Alaska", country="US")
county = data.get_county("Aleutians East", state="Alaska", country="US")
county.fips = "02013"
data.populate_fips_cache()
mock_get.return_value = mock_response
parse_can_region_summary_by_county(cache, data)
mock_logger.warning.assert_not_called()
assert county.test_positivity_rate is None
assert county.vaccines_total.partial_vaccinations == 401
assert county.vaccines_total.completed_vaccinations == 2498
@patch("update_prevalence.logger", spec=Logger)
@patch("update_prevalence.requests.get", spec=requests.get)
def test_parse_can_region_summary_by_county_unknown_unknown_county(
mock_get: Mock,
mock_logger: Mock,
data: AllData,
cache: DataCache,
) -> None:
mock_response = Mock()
mock_response.status_code = 200
mock_response.text = json.dumps(
[
{
"fips": "8675309",
"country": "US",
"state": "MP",
"county": "aslkdjfa",
"population": 48000,
},
]
)
mock_get.return_value = mock_response
parse_can_region_summary_by_county(cache, data)
mock_logger.warning.assert_called()
@patch("update_prevalence.logger", spec=Logger)
@patch("update_prevalence.requests.get", spec=requests.get)
def test_parse_can_region_summary_by_county_known_unknown_county(
mock_get: Mock,
mock_logger: Mock,
data: AllData,
cache: DataCache,
) -> None:
mock_response = Mock()
mock_response.status_code = 200
mock_response.text = json.dumps(
[
{
"fips": "69100",
"country": "US",
"state": "MP",
"county": "Rota Municipality",
"population": 48000,
},
]
)
mock_get.return_value = mock_response
parse_can_region_summary_by_county(cache, data)
mock_logger.warning.assert_not_called()
@patch("update_prevalence.logger", spec=Logger)
def test_Log_Aggregator_logs_small_impacts_as_debug(
mock_logger: Mock, small_place: PopulationFilteredLogging
) -> None:
aggregator = LogAggregator()
aggregator.add_issue("issue type one", small_place)
aggregator.log()
mock_logger.log.assert_called_with(logging.DEBUG, "5,000 people affected by issue type one")
@patch("update_prevalence.logger", spec=Logger)
def test_Log_Aggregator_logs_small_impacts_as_info(
mock_logger: Mock, medium_place: PopulationFilteredLogging
) -> None:
aggregator = LogAggregator()
aggregator.add_issue("issue type two", medium_place)
aggregator.log()
mock_logger.log.assert_called_with(logging.INFO, "10,000 people affected by issue type two")
@patch("update_prevalence.logger", spec=Logger)
def test_Log_Aggregator_logs_large_impacts_as_warning(
mock_logger: Mock, large_place: PopulationFilteredLogging
) -> None:
aggregator = LogAggregator()
aggregator.add_issue("issue type three", large_place)
aggregator.log()
mock_logger.log.assert_called_with(logging.WARNING, "100,000 people affected by issue type three")
@patch("update_prevalence.logger", spec=Logger)
def test_Log_Aggregator_combines_small_impacts_as_info(
mock_logger: Mock, small_place: PopulationFilteredLogging
) -> None:
aggregator = LogAggregator()
aggregator.add_issue("issue type four", small_place)
aggregator.add_issue("issue type four", small_place)
aggregator.log()
mock_logger.log.assert_called_with(logging.INFO, "10,000 people affected by issue type four")
@patch("update_prevalence.logger", spec=Logger)
def test_PopulationFilteredLogging_issue_delegates_to_log_aggregator(
mock_logger: Mock, small_place: PopulationFilteredLogging
) -> None:
small_place.issue("issue type five", "detail")
log_aggregator.log()
mock_logger.log.assert_called_with(logging.DEBUG, "5,000 people affected by issue type five")
def test_County_as_app_data_positiveCasePercentage(effective_date: date, my_county: County) -> None:
my_county.test_positivity_rate = 0.5
app_location = my_county.as_app_data()
assert app_location.positiveCasePercentage == 50
def test_County_as_app_data_updatedAt(effective_date: date, my_county: County) -> None:
add_increasing_cumulative_cases(my_county, effective_date)
app_location = my_county.as_app_data()
assert app_location.updatedAt == (effective_date - timedelta(days=6)).strftime("%B %d, %Y")
@patch("update_prevalence.logger", spec=Logger)
def test_County_as_app_data_validates_positivity_rate(
mock_logger: Mock, effective_date: date, my_county: County
) -> None:
my_county.test_positivity_rate = 1.5
app_location = my_county.as_app_data()
assert app_location.positiveCasePercentage is None
mock_logger.info.assert_has_calls(
[call("Invalid test positivity rate (123 people): test rate for My County is 1.5")]
)
@patch("update_prevalence.logger", spec=Logger)
def test_County_as_app_data_logs_before_returning_very_low_cases_last_week(
mock_logger: Mock, my_county: County, effective_date: date
) -> None:
last_month_cases = 50
cases_over_time = [100, 100, 100, 100, 100, 101, 101, 100, 100, 100, 101, 101, 101, 101, 101]
add_cumulative_cases(my_county, effective_date, last_month_cases, cases_over_time)
my_county.population = 2_000_000
cases_last_week = my_county.cases_last_week
assert cases_last_week == 1
cases_week_before = my_county.cases_week_before
assert cases_week_before == 0
data = my_county.as_app_data()
assert data is not None
mock_logger.info.assert_called_with(
"Less than 1 case per million in last week - County level (2,000,000 people): Only 1 cases last week when population is 2000000 in My County"
)
@patch("update_prevalence.logger", spec=Logger)
def test_County_as_app_data_logs_before_returning_very_low_cases_last_month(
mock_logger: Mock, my_county: County, effective_date: date
) -> None:
last_month_cases = 99
cases_over_time = [100, 100, 100, 100, 100, 101, 101, 100, 100, 100, 101, 101, 101, 101, 101]
add_cumulative_cases(my_county, effective_date, last_month_cases, cases_over_time)
my_county.population = 2_000_000
cases_last_week = my_county.cases_last_week
assert cases_last_week == 1
cases_week_before = my_county.cases_week_before
assert cases_week_before == 0
data = my_county.as_app_data()
assert data is not None
mock_logger.info.assert_has_calls(
[
call(
"Less than 4 cases per million in last month - County level (2,000,000 people): Only 2 cases last month when population is 2000000 in My County"
)
]
)
@patch("update_prevalence.logger", spec=Logger)
def test_County_as_app_data_logs_before_returning_zero_cases_last_week(
mock_logger: Mock, my_county: County, effective_date: date
) -> None:
last_month_cases = 4
cases_over_time = [4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
add_cumulative_cases(my_county, effective_date, last_month_cases, cases_over_time)
cases_last_week = my_county.cases_last_week
assert cases_last_week == 0
cases_week_before = my_county.cases_week_before
assert cases_week_before > 0
data = my_county.as_app_data()
assert my_county.cases_last_month_rough == 1
assert data is not None
assert mock_logger.info.mock_calls == [
call(
"No cases noted for last week - but there were some in the last month - County level (123 people): No cases reported for last week in My County, My State despite there being cases in the last month"
),
]
assert data.updatedAt == (effective_date - timedelta(days=9)).strftime("%B %d, %Y")
@patch("update_prevalence.logger", spec=Logger)
def test_County_as_app_data_logs_before_returning_zero_cases_last_month(
mock_logger: Mock, my_county: County, effective_date: date
) -> None:
last_month_cases = 100
cases_over_time = [
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
]
add_cumulative_cases(my_county, effective_date, last_month_cases, cases_over_time)
cases_last_week = my_county.cases_last_week
assert cases_last_week == 0
cases_week_before = my_county.cases_week_before
assert cases_week_before == 0
assert my_county.cases_last_month_rough == 0
data = my_county.as_app_data()
assert data is not None
assert [
call(
"No cases noted for a month - County level (123 people): No cases reported in at least one month in My County, My State"
),
] == mock_logger.info.mock_calls
assert data.updatedAt == (effective_date - timedelta(days=15)).strftime("%B %d, %Y")
@patch("update_prevalence.logger", spec=Logger)
def test_Place_recent_daily_cumulative_cases(
mock_logger: Mock, my_county: County, effective_date: date
) -> None:
assert [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5] == my_county.recent_daily_cumulative_cases
@patch("update_prevalence.logger", spec=Logger)
def test_Place_recent_daily_cumulative_cases_date_missing(
mock_logger: Mock, my_county: County, effective_date: date
) -> None:
del my_county.cumulative_cases[effective_date - timedelta(days=3)]
with pytest.raises(ValueError) as e:
my_county.recent_daily_cumulative_cases
assert "Missing data for" in str(e.value)
@patch("update_prevalence.logger", spec=Logger)
def test_AppLocation_prevalenceRatio_also_validates_positivity_rate(
mock_logger: Mock, my_app_location: AppLocation
) -> None:
my_app_location.positiveCasePercentage = -23
ratio = my_app_location.prevalenceRatio()
assert ratio is not None
mock_logger.info.assert_called_with("Positivity rate is negative (123 people): -23")
class NewDatetime(datetime):
@classmethod
def now(cls, tz: Optional[tzinfo] = None) -> typing.Any:
return datetime(2022, 1, 1, 12, 0, 0)
@patch("update_prevalence.datetime", new=NewDatetime)
@patch("update_prevalence.logger", spec=Logger)
def test_AppLocation_prevalenceRatio_caps_positivity_rate(
mock_logger: Mock,
my_app_location: AppLocation,
effective_date: date,
) -> None:
my_app_location.positiveCasePercentage = 150
assert my_app_location.prevalenceRatio() == 3.430615164520744
def test_AllData_get_country_or_raise_raises() -> None:
all_data = AllData()
with pytest.raises(Exception):
all_data.get_country_or_raise("unknown country")
def test_AllData_get_country_or_raise_returns_data() -> None:
all_data = AllData()
all_data.get_country("new country")
assert all_data.get_country_or_raise("new country") is not None
@patch("update_prevalence.logger", spec=Logger)
def test_AllData_rollup_totals_no_county_data(mock_logger: Mock, effective_date: date) -> None:
all_data = AllData()
us = all_data.get_country("US")
wyoming = all_data.get_state("Wyoming", country="US")
wyoming.population = 50
add_increasing_cumulative_cases(wyoming, effective_date)
assert wyoming.cases_last_week == 5
county = all_data.get_county("mumble", state="Wyoming", country="US")
county.population = 10
all_data.rollup_totals()
mock_logger.warning.assert_not_called()
mock_logger.info.assert_called_with(
"No county-level case data (10 people): discarding County(fullname='mumble, Wyoming, US', name='mumble', population=10, test_positivity_rate=None, cumulative_cases=Counter(), tests_in_past_week=None, vaccines_by_type=None, vaccines_total=Vaccination(partial_vaccinations=0, completed_vaccinations=0), country='US', state='Wyoming', fips=None) with no case data"
)
assert us.cases_last_week == 5
@patch("update_prevalence.logger", spec=Logger)
def test_AllData_rollup_totals_no_state_data(mock_logger: Mock, effective_date: date) -> None:
all_data = AllData()
us = all_data.get_country("US")
wyoming = all_data.get_state("Wyoming", country="US")
wyoming.population = 50
add_increasing_cumulative_cases(wyoming, effective_date)
montana = all_data.get_state("Montana", country="US")
montana.population = 50
all_data.rollup_totals()
mock_logger.warning.assert_not_called()
mock_logger.info.assert_called_with(
"No state-level case data (50 people): Discarding State(fullname='Montana, US', name='Montana', population=50, test_positivity_rate=None, cumulative_cases=Counter(), tests_in_past_week=None, vaccines_by_type=None, vaccines_total=Vaccination(partial_vaccinations=0, completed_vaccinations=0), country='US', fips=None, counties={}) with no case data"
)
@patch("update_prevalence.logger", spec=Logger)
def test_AllData_rollup_totals_county_has_no_population(mock_logger: Mock, effective_date: date) -> None:
all_data = AllData()
us = all_data.get_country("US")
wyoming = all_data.get_state("Wyoming", country="US")
wyoming.population = 50
add_increasing_cumulative_cases(wyoming, effective_date)
montana = all_data.get_state("Montana", country="US")
add_increasing_cumulative_cases(montana, effective_date)
montana.population = 0
random_county = all_data.get_county("Random county", state="Montana", country="US")
random_county.population = 0
all_data.rollup_totals()
mock_logger.warning.assert_called_with(
"Discarding country US due to error: ValueError('Missing population data for Random county, Montana, US')"
)
@patch("update_prevalence.logger", spec=Logger)
def test_AllData_rollup_totals_state_has_no_population(mock_logger: Mock, effective_date: date) -> None:
all_data = AllData()
us = all_data.get_country("US")
wyoming = all_data.get_state("Wyoming", country="US")
wyoming.population = 50
add_increasing_cumulative_cases(wyoming, effective_date)
montana = all_data.get_state("Montana", country="US")
add_increasing_cumulative_cases(montana, effective_date)
montana.population = 0
all_data.rollup_totals()
mock_logger.warning.assert_called_with(
"Discarding country US due to error: ValueError('Missing population data for Montana, US')"
)
@patch("update_prevalence.logger", spec=Logger)
def test_AllData_rollup_totals_no_country_data(mock_logger: Mock, effective_date: date) -> None:
all_data = AllData()
us = all_data.get_country("US")
us.population = 999
all_data.rollup_totals()
mock_logger.warning.assert_called_with(
"Discarding country US due to error: ValueError(\"No country-level case data for Country(fullname='US', name='US', population=999, test_positivity_rate=None, cumulative_cases=Counter(), tests_in_past_week=None, vaccines_by_type=None, vaccines_total=Vaccination(partial_vaccinations=0, completed_vaccinations=0), iso3=None, states={})\")"
)
@patch("update_prevalence.logger", spec=Logger)
def test_AllData_rollup_totals_state_no_population(mock_logger: Mock, effective_date: date) -> None:
all_data = AllData()
us = all_data.get_country("US")
wyoming = all_data.get_state("Wyoming", country="US")
wyoming.population = 0
add_increasing_cumulative_cases(wyoming, effective_date)
all_data.rollup_totals()
mock_logger.warning.assert_called_with(
"Discarding country US due to error: ValueError('Missing population data for Wyoming, US')"
)
mock_logger.info.assert_not_called()
@patch("update_prevalence.logger", spec=Logger)
def test_AllData_rollup_totals_fake_region_with_no_cases_last_week_removed(
mock_logger: Mock, effective_date: date
) -> None:
all_data = AllData()
us = all_data.get_country("US")
us.population = 123
unk = all_data.get_state("Unknown", country="US")
unk.population = 0
add_stable_cumulative_cases(unk, effective_date)
all_data.rollup_totals()
assert len(us.states) == 0
@patch("update_prevalence.logger", spec=Logger)
def test_AllData_rollup_testing(mock_logger: Mock, effective_date: date) -> None:
all_data = AllData()
us = all_data.get_country("US")
wyoming = all_data.get_state("Wyoming", country="US")
add_increasing_cumulative_cases(wyoming, effective_date)
wyoming.population = 123
wyoming.tests_in_past_week = 123
assert wyoming.tests_in_past_week == 123
assert wyoming.cases_last_week == 5
all_data.rollup_totals()
assert wyoming.test_positivity_rate == 5 / 123
assert us.cases_last_week == 5
assert us.test_positivity_rate == 5 / 123
mock_logger.warning.assert_not_called()
mock_logger.info.assert_not_called()
@patch("update_prevalence.logger", spec=Logger)
def test_AllData_rollup_testing_unexpected_rollup_fails_fast(mock_logger: Mock, effective_date: date) -> None:
all_data = AllData()
us = all_data.get_country("US")
wyoming = all_data.get_state("Wyoming", country="US")
add_increasing_cumulative_cases(wyoming, effective_date)
wyoming.population = 123
wyoming.tests_in_past_week = 123
us.population = 123
us.tests_in_past_week = 123
with pytest.raises(NotImplementedError) as e:
all_data.rollup_totals()
assert "Tried to overwrite" in str(e)
@patch("update_prevalence.logger", spec=Logger)
def test_AllData_rollup_totals(mock_logger: Mock, effective_date: date) -> None:
all_data = AllData()
us = all_data.get_country("US")
wyoming = all_data.get_state("Wyoming", country="US")
wyoming.population = 50
add_increasing_cumulative_cases(wyoming, effective_date)
all_data.rollup_totals()
mock_logger.warning.assert_not_called()
mock_logger.info.assert_not_called()
@patch("update_prevalence.logger", spec=Logger)