-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathpopulations_test.py
More file actions
496 lines (438 loc) · 18 KB
/
populations_test.py
File metadata and controls
496 lines (438 loc) · 18 KB
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
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Data Commons Python Client API unit tests.
Unit tests for Population and Observation methods in the Data Commons Python
Client API.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import base64
from unittest import mock
import datacommons as dc
import datacommons.utils as utils
import json
import unittest
import urllib
import zlib
# new_mixer_api specifies whether to use the Mixer API
# that gives dictionaries instead of lists for places-in,
# population, and observation functions.
def request_mock_base(*args, **kwargs):
""" A mock urlopen request sent in the requests package. """
# Create the mock response object.
class MockResponse:
def __init__(self, json_data):
self.json_data = json_data
def read(self):
return self.json_data
# Get the request json and allowed constraining properties
req = args[0]
if req.data:
data = json.loads(req.data)
api_key = req.get_header('X-api-key')
if api_key != 'TEST-API-KEY':
return urllib.error.HTTPError(None, 403, None, None, None)
constrained_props = [
{
'property': 'placeOfBirth',
'value': 'BornInOtherStateInTheUnitedStates'
},
{
'property': 'age',
'value': 'Years5To17'
}
]
# Mock responses for urlopen request to get_populations.
if req.full_url == utils._API_ROOT + utils._API_ENDPOINTS['get_populations']\
and data['population_type'] == 'Person'\
and data['pvs'] == constrained_props:
if data['dcids'] == ['geoId/06085', 'geoId/4805000']:
# Response returned when querying for multiple valid dcids.
res_json =json.dumps({
'geoId/06085': 'dc/p/crgfn8blpvl35',
'geoId/4805000': 'dc/p/f3q9whmjwbf36'}) if kwargs['new_mixer_api'] else json.dumps([
{
'dcid': 'geoId/06085',
'population': 'dc/p/crgfn8blpvl35'
},
{
'dcid': 'geoId/4805000',
'population': 'dc/p/f3q9whmjwbf36'
}])
return MockResponse(json.dumps({'payload': res_json}))
if data['dcids'] == ['geoId/06085', 'dc/MadDcid']:
# Response returned when querying for a dcid that does not exist.
res_json = json.dumps({'geoId/06085': 'dc/p/crgfn8blpvl35'}) if kwargs['new_mixer_api'] else json.dumps([
{
'dcid': 'geoId/06085',
'population': 'dc/p/crgfn8blpvl35'
},
])
return MockResponse(json.dumps({'payload': res_json}))
if data['dcids'] == ['dc/MadDcid', 'dc/MadderDcid'] or data['dcids'] == []:
# Response returned when both given dcids do not exist or no dcids are
# provided to the method.
res_json = json.dumps({} if kwargs['new_mixer_api'] else [])
return MockResponse(json.dumps({'payload': res_json}))
# Mock responses for urlopen request to get_observations
if req.full_url == utils._API_ROOT + utils._API_ENDPOINTS['get_observations']\
and data['measured_property'] == 'count'\
and data['stats_type'] == 'measuredValue'\
and data['observation_date'] == '2018-12'\
and data['observation_period'] == 'P1M'\
and data['measurement_method'] == 'BLSSeasonallyAdjusted':
if data['dcids'] == ['dc/p/x6t44d8jd95rd', 'dc/p/lr52m1yr46r44', 'dc/p/fs929fynprzs']:
# Response returned when querying for multiple valid dcids.
res_json = json.dumps({'dc/p/x6t44d8jd95rd': '18704962.000000', 'dc/p/lr52m1yr46r44': '3075662.000000', 'dc/p/fs929fynprzs': '1973955.000000'}) if kwargs['new_mixer_api'] else json.dumps([
{
'dcid': 'dc/p/x6t44d8jd95rd',
'observation': '18704962.000000'
},
{
'dcid': 'dc/p/lr52m1yr46r44',
'observation': '3075662.000000'
},
{
'dcid': 'dc/p/fs929fynprzs',
'observation': '1973955.000000'
}
])
return MockResponse(json.dumps({'payload': res_json}))
if data['dcids'] == ['dc/p/x6t44d8jd95rd', 'dc/MadDcid']:
# Response returned when querying for a dcid that does not exist.
res_json = json.dumps({'dc/p/x6t44d8jd95rd' : '18704962.000000'}) if kwargs['new_mixer_api'] else json.dumps([
{
'dcid': 'dc/p/x6t44d8jd95rd',
'observation': '18704962.000000'
},
])
return MockResponse(json.dumps({'payload': res_json}))
if data['dcids'] == ['dc/MadDcid', 'dc/MadderDcid'] or data['dcids'] == []:
# Response returned when both given dcids do not exist or no dcids are
# provided to the method.
res_json = json.dumps({} if kwargs['new_mixer_api'] else [])
return MockResponse(json.dumps({'payload': res_json}))
# Mock responses for urlopen request to get_place_obs
if req.full_url == utils._API_ROOT + utils._API_ENDPOINTS['get_place_obs']\
and data['place_type'] == 'City'\
and data['observation_date'] == '2017'\
and data['population_type'] == 'Person'\
and data['pvs'] == constrained_props:
res_json = json.dumps({
'places': [
{
'name': 'Marcus Hook borough',
'place': 'geoId/4247344',
'populations': {
'dc/p/pq6frs32sfvk': {
'observations': [
{
'marginOfError': 39,
'measuredProp': 'count',
'measuredValue': 67,
}
],
}
}
}
]
})
return MockResponse(json.dumps(
{'payload': base64.encodebytes(zlib.compress(res_json.encode('utf-8'))).decode('ascii')}))
# Mock responses for get requests to get_pop_obs.
if req.full_url == utils._API_ROOT + utils._API_ENDPOINTS['get_pop_obs'] + '?dcid=geoId/06085':
# Response returned when querying for a city in the graph.
res_json = json.dumps({
'name': 'Mountain View',
'placeType': 'City',
'populations': {
'dc/p/013ldrstf6lnf': {
'numConstraints': 6,
'observations': [
{
'marginOfError': 119,
'measuredProp': 'count',
'measuredValue': 225,
'measurementMethod': 'CensusACS5yrSurvey',
'observationDate': '2014'
}, {
'marginOfError': 108,
'measuredProp': 'count',
'measuredValue': 180,
'measurementMethod': 'CensusACS5yrSurvey',
'observationDate': '2012'
}
],
'popType': 'Person',
'propertyValues': {
'age': 'Years16Onwards',
'gender': 'Male',
'income': 'USDollar30000To34999',
'incomeStatus': 'WithIncome',
'race': 'USC_HispanicOrLatinoRace',
'workExperience': 'USC_NotWorkedFullTime'
}
}
}
})
return MockResponse(json.dumps(
{'payload': base64.encodebytes(zlib.compress(res_json.encode('utf-8'))).decode('ascii')}))
# Otherwise, return an empty response and a 404.
return urllib.error.HTTPError(None, 404, None, None, None)
def request_mock(*args, **kwargs):
return request_mock_base(new_mixer_api=False, *args, **kwargs)
def request_mock_new_mixer_api(*args, **kwargs):
return request_mock_base(new_mixer_api=True, *args, **kwargs)
class TestGetPopulations(unittest.TestCase):
""" Unit tests for get_populations. """
_constraints = {
'placeOfBirth': 'BornInOtherStateInTheUnitedStates',
'age': 'Years5To17'
}
@mock.patch('urllib.request.urlopen', side_effect=request_mock)
def test_multiple_dcids(self, urlopen):
""" Calling get_populations with proper dcids returns valid results. """
# Set the API key
dc.set_api_key('TEST-API-KEY')
# Call get_populations
populations = dc.get_populations(['geoId/06085', 'geoId/4805000'], 'Person',
constraining_properties=self._constraints)
self.assertDictEqual(populations, {
'geoId/06085': 'dc/p/crgfn8blpvl35',
'geoId/4805000': 'dc/p/f3q9whmjwbf36'
})
@mock.patch('urllib.request.urlopen', side_effect=request_mock_new_mixer_api)
def test_multiple_dcids_new_mixer_api(self, urlopen):
""" Calling get_populations with proper dcids returns valid results. """
# Set the API key
dc.set_api_key('TEST-API-KEY')
# Call get_populations
populations = dc.get_populations(['geoId/06085', 'geoId/4805000'], 'Person',
constraining_properties=self._constraints)
self.assertDictEqual(populations, {
'geoId/06085': 'dc/p/crgfn8blpvl35',
'geoId/4805000': 'dc/p/f3q9whmjwbf36'
})
@mock.patch('urllib.request.urlopen', side_effect=request_mock)
def test_bad_dcids(self, urlopen):
""" Calling get_populations with dcids that do not exist returns empty
results.
"""
# Set the API key
dc.set_api_key('TEST-API-KEY')
# Call get_populations
pops_1 = dc.get_populations(['geoId/06085', 'dc/MadDcid'], 'Person',
constraining_properties=self._constraints)
pops_2 = dc.get_populations(['dc/MadDcid', 'dc/MadderDcid'], 'Person',
constraining_properties=self._constraints)
# Verify the results
self.assertDictEqual(pops_1, {'geoId/06085': 'dc/p/crgfn8blpvl35'})
self.assertDictEqual(pops_2, {})
@mock.patch('urllib.request.urlopen', side_effect=request_mock_new_mixer_api)
def test_bad_dcids_new_mixer_api(self, urlopen):
""" Calling get_populations with dcids that do not exist returns empty
results.
"""
# Set the API key
dc.set_api_key('TEST-API-KEY')
# Call get_populations
pops_1 = dc.get_populations(['geoId/06085', 'dc/MadDcid'], 'Person',
constraining_properties=self._constraints)
pops_2 = dc.get_populations(['dc/MadDcid', 'dc/MadderDcid'], 'Person',
constraining_properties=self._constraints)
# Verify the results
self.assertDictEqual(pops_1, {'geoId/06085': 'dc/p/crgfn8blpvl35'})
self.assertDictEqual(pops_2, {})
@mock.patch('urllib.request.urlopen', side_effect=request_mock)
def test_no_dcids(self, urlopen):
""" Calling get_populations with no dcids returns empty results. """
# Set the API key
dc.set_api_key('TEST-API-KEY')
pops = dc.get_populations(
[], 'Person', constraining_properties=self._constraints)
self.assertDictEqual(pops, {})
@mock.patch('urllib.request.urlopen', side_effect=request_mock_new_mixer_api)
def test_no_dcids_with_new_mixer_api(self, urlopen):
""" Calling get_populations with no dcids returns empty results. """
# Set the API key
dc.set_api_key('TEST-API-KEY')
pops = dc.get_populations(
[], 'Person', constraining_properties=self._constraints)
self.assertDictEqual(pops, {})
class TestGetObservations(unittest.TestCase):
""" Unit tests for get_observations. """
@mock.patch('urllib.request.urlopen', side_effect=request_mock)
def test_multiple_dcids(self, urlopen):
""" Calling get_observations with proper dcids returns valid results. """
# Set the API key
dc.set_api_key('TEST-API-KEY')
dcids = ['dc/p/x6t44d8jd95rd', 'dc/p/lr52m1yr46r44', 'dc/p/fs929fynprzs']
expected = {
'dc/p/lr52m1yr46r44': 3075662.0,
'dc/p/fs929fynprzs': 1973955.0,
'dc/p/x6t44d8jd95rd': 18704962.0
}
actual = dc.get_observations(dcids, 'count', 'measuredValue', '2018-12',
observation_period='P1M',
measurement_method='BLSSeasonallyAdjusted')
self.assertDictEqual(actual, expected)
@mock.patch('urllib.request.urlopen', side_effect=request_mock_new_mixer_api)
def test_multiple_dcids_with_new_mixer_api(self, urlopen):
""" Calling get_observations with proper dcids returns valid results. """
# Set the API key
dc.set_api_key('TEST-API-KEY')
dcids = ['dc/p/x6t44d8jd95rd', 'dc/p/lr52m1yr46r44', 'dc/p/fs929fynprzs']
expected = {
'dc/p/lr52m1yr46r44': 3075662.0,
'dc/p/fs929fynprzs': 1973955.0,
'dc/p/x6t44d8jd95rd': 18704962.0
}
actual = dc.get_observations(dcids, 'count', 'measuredValue', '2018-12',
observation_period='P1M',
measurement_method='BLSSeasonallyAdjusted')
self.assertDictEqual(actual, expected)
@mock.patch('urllib.request.urlopen', side_effect=request_mock)
def test_bad_dcids(self, urlopen):
""" Calling get_observations with dcids that do not exist returns empty
results.
"""
# Set the API key
dc.set_api_key('TEST-API-KEY')
# Get the input
dcids_1 = ['dc/p/x6t44d8jd95rd', 'dc/MadDcid']
dcids_2 = ['dc/MadDcid', 'dc/MadderDcid']
# Call get_observations
actual_1 = dc.get_observations(dcids_1, 'count', 'measuredValue', '2018-12',
observation_period='P1M',
measurement_method='BLSSeasonallyAdjusted')
actual_2 = dc.get_observations(dcids_2, 'count', 'measuredValue', '2018-12',
observation_period='P1M',
measurement_method='BLSSeasonallyAdjusted')
# Verify the results
self.assertDictEqual(actual_1, {'dc/p/x6t44d8jd95rd': 18704962.0})
self.assertDictEqual(actual_2, {})
@mock.patch('urllib.request.urlopen', side_effect=request_mock_new_mixer_api)
def test_bad_dcids_new_mixer_api(self, urlopen):
""" Calling get_observations with dcids that do not exist returns empty
results.
"""
# Set the API key
dc.set_api_key('TEST-API-KEY')
# Get the input
dcids_1 = ['dc/p/x6t44d8jd95rd', 'dc/MadDcid']
dcids_2 = ['dc/MadDcid', 'dc/MadderDcid']
# Call get_observations
actual_1 = dc.get_observations(dcids_1, 'count', 'measuredValue', '2018-12',
observation_period='P1M',
measurement_method='BLSSeasonallyAdjusted')
actual_2 = dc.get_observations(dcids_2, 'count', 'measuredValue', '2018-12',
observation_period='P1M',
measurement_method='BLSSeasonallyAdjusted')
# Verify the results
self.assertDictEqual(actual_1, {'dc/p/x6t44d8jd95rd': 18704962.0})
self.assertDictEqual(actual_2, {})
@mock.patch('urllib.request.urlopen', side_effect=request_mock)
def test_no_dcids(self, urlopen):
""" Calling get_observations with no dcids returns empty results. """
# Set the API key
dc.set_api_key('TEST-API-KEY')
actual = dc.get_observations([], 'count', 'measuredValue', '2018-12',
observation_period='P1M',
measurement_method='BLSSeasonallyAdjusted')
self.assertDictEqual(actual, {})
@mock.patch('urllib.request.urlopen', side_effect=request_mock_new_mixer_api)
def test_no_dcids_new_mixer_api(self, urlopen):
""" Calling get_observations with no dcids returns empty results. """
# Set the API key
dc.set_api_key('TEST-API-KEY')
actual = dc.get_observations([], 'count', 'measuredValue', '2018-12',
observation_period='P1M',
measurement_method='BLSSeasonallyAdjusted')
self.assertDictEqual(actual, {})
class TestGetPopObs(unittest.TestCase):
""" Unit tests for get_pop_obs. """
@mock.patch('urllib.request.urlopen', side_effect=request_mock)
def test_valid_dcid(self, urlopen):
""" Calling get_pop_obs with valid dcid returns valid results. """
# Set the API key
dc.set_api_key('TEST-API-KEY')
# Call get_pop_obs
pop_obs = dc.get_pop_obs('geoId/06085')
self.assertDictEqual(pop_obs, {
'name': 'Mountain View',
'placeType': 'City',
'populations': {
'dc/p/013ldrstf6lnf': {
'numConstraints': 6,
'observations': [
{
'marginOfError': 119,
'measuredProp': 'count',
'measuredValue': 225,
'measurementMethod': 'CensusACS5yrSurvey',
'observationDate': '2014'
}, {
'marginOfError': 108,
'measuredProp': 'count',
'measuredValue': 180,
'measurementMethod': 'CensusACS5yrSurvey',
'observationDate': '2012'
}
],
'popType': 'Person',
'propertyValues': {
'age': 'Years16Onwards',
'gender': 'Male',
'income': 'USDollar30000To34999',
'incomeStatus': 'WithIncome',
'race': 'USC_HispanicOrLatinoRace',
'workExperience': 'USC_NotWorkedFullTime'
}
}
}
})
class TestGetPlaceObs(unittest.TestCase):
""" Unit tests for get_place_obs. """
@mock.patch('urllib.request.urlopen', side_effect=request_mock)
def test_valid(self, urlopen):
""" Calling get_place_obs with valid parameters returns a valid result. """
# Set the API key
dc.set_api_key('TEST-API-KEY')
# Call get_place_obs
pvs = {
'placeOfBirth': 'BornInOtherStateInTheUnitedStates',
'age': 'Years5To17'
}
place_obs = dc.get_place_obs(
'City', '2017', 'Person', constraining_properties=pvs)
self.assertListEqual(place_obs, [
{
'name': 'Marcus Hook borough',
'place': 'geoId/4247344',
'populations': {
'dc/p/pq6frs32sfvk': {
'observations': [
{
'marginOfError': 39,
'measuredProp': 'count',
'measuredValue': 67,
}
],
}
}
}
])
if __name__ == '__main__':
unittest.main()