PageRenderTime 84ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/test_client.py

https://github.com/wadey/python-simplegeo
Python | 278 lines | 231 code | 44 blank | 3 comment | 21 complexity | 4f9900420f5d3a6ae1d390ca3860b9a2 MD5 | raw file
  1. import time
  2. import random
  3. import unittest
  4. import simplejson as json
  5. import geohash
  6. import random
  7. import socket
  8. from simplegeo import Client, Record, APIError
  9. MY_OAUTH_KEY = 'MY_OAUTH_KEY'
  10. MY_OAUTH_SECRET = 'MY_SECRET_KEY'
  11. TESTING_LAYER = 'TESTING_LAYER'
  12. if MY_OAUTH_KEY == 'MY_OAUTH_KEY' or \
  13. MY_OAUTH_SECRET == 'MY_SERCRET_KEY' or \
  14. TESTING_LAYER == 'TESTING_LAYER':
  15. raise Exception('Please provide the proper credentials.')
  16. API_VERSION = '0.1'
  17. API_HOST = 'api.simplegeo.com'
  18. API_PORT = 80
  19. INVALID_API_PORT = 4280
  20. TESTING_LAT = '37.7481624945'
  21. TESTING_LON = '-122.433287165'
  22. TESTING_GEOHASH = geohash.encode(float(TESTING_LAT), float(TESTING_LON))
  23. TESTING_LAT_NON_US = '48.8566667'
  24. TESTING_LON_NON_US = '2.3509871'
  25. RECORD_TYPES = ['person', 'place', 'object']
  26. TESTING_BOUNDS = [-122.43409, 37.747296999999996, -122.424768, 37.751841999999996]
  27. class ClientTest(unittest.TestCase):
  28. def tearDown(self):
  29. for record in self.created_records:
  30. try:
  31. self.client.delete_record(record.layer, record.id)
  32. except APIError, e:
  33. # If we get a 404, then our job is done.
  34. pass
  35. def setUp(self):
  36. self.client = Client(MY_OAUTH_KEY, MY_OAUTH_SECRET, API_VERSION, API_HOST, API_PORT)
  37. self.created_records = []
  38. def _record(self):
  39. """ Generate a record in San Francisco. """
  40. top_left = [37.801646236899785, -122.47833251953125]
  41. bottom_right = [37.747371884118664, -122.3931884765625]
  42. record = Record(
  43. layer=TESTING_LAYER,
  44. id=str(int(random.random() * 1000000)),
  45. lat=str(random.uniform(top_left[0], bottom_right[0])),
  46. lon=str(random.uniform(top_left[1], bottom_right[1])),
  47. type=RECORD_TYPES[random.randint(0, 2)]
  48. )
  49. return record
  50. def test_multi_record_post(self):
  51. post_records = [self._record() for i in range(10)]
  52. self.addRecordsAndSleep(TESTING_LAYER, post_records)
  53. get_records = self.client.get_records(TESTING_LAYER,
  54. [record.id for record in post_records])
  55. self.assertEquals(len(get_records), len(post_records))
  56. post_record_ids = [post_record.id for post_record in post_records]
  57. for get_record in get_records:
  58. self.assertTrue(get_record['id'] in post_record_ids)
  59. def test_too_many_records(self):
  60. record_limit = 100
  61. records = []
  62. for i in range(record_limit + 1):
  63. records.append(self._record())
  64. self.assertRaises(APIError, self.client.add_records, TESTING_LAYER,
  65. records)
  66. def test_add_record(self):
  67. record = self._record()
  68. self.addRecordAndSleep(record)
  69. result = self.client.get_record(record.layer, record.id)
  70. self.assertPointIsRecord(result, record)
  71. def test_add_update_delete_record(self):
  72. record = self._record()
  73. self.addRecordAndSleep(record)
  74. result = self.client.get_record(record.layer, record.id)
  75. self.assertPointIsRecord(result, record)
  76. updated_record = self._record()
  77. updated_record.id = record.id
  78. self.addRecordAndSleep(updated_record)
  79. updated_result = self.client.get_record(record.layer, record.id)
  80. self.assertPointIsRecord(updated_result, updated_record)
  81. self.client.delete_record(record.layer, record.id)
  82. time.sleep(5)
  83. self.assertRaises(APIError, self.client.get_record, record.layer, record.id)
  84. self.assertRaises(APIError, self.client.get_record, updated_record.layer, updated_record.id)
  85. def test_record_history(self):
  86. post_records = [self._record() for i in range(10)]
  87. current_time = int(time.time())
  88. for record in post_records:
  89. record.id = post_records[0].id
  90. record.created = current_time
  91. current_time -= 1
  92. self.addRecordsAndSleep(TESTING_LAYER, post_records)
  93. history = self.client.get_history(TESTING_LAYER, post_records[0].id)
  94. points = history.get('geometries')
  95. self.assertEquals(len(points), 10)
  96. count = 0
  97. for point in points:
  98. self.assertEquals(str(point.get('coordinates')[0]), post_records[count].lon)
  99. self.assertEquals(str(point.get('coordinates')[1]), post_records[count].lat)
  100. count += 1
  101. def test_nearby_geohash_search(self):
  102. limit = 5
  103. records = []
  104. for i in range(limit):
  105. record = self._record()
  106. record.lat = float(TESTING_LAT) + (i / 10000000)
  107. record.lon = float(TESTING_LON) - (i / 10000000)
  108. records.append(record)
  109. self.addRecordsAndSleep(TESTING_LAYER, records)
  110. nearby_result = self.client.get_nearby_geohash(TESTING_LAYER, TESTING_GEOHASH, limit=limit)
  111. features = nearby_result.get('features')
  112. self.assertTrue(len(features) <= limit)
  113. bounding_box = geohash.bbox(TESTING_GEOHASH)
  114. for feature in features:
  115. self.assertTrue(bounding_box.get('s') <= feature.get('geometry').get('coordinates')[1] <= bounding_box.get('n'))
  116. self.assertTrue(bounding_box.get('e') >= feature.get('geometry').get('coordinates')[0] >= bounding_box.get('w'))
  117. def test_nearby_lat_lon_search(self):
  118. limit = 5
  119. records = []
  120. for i in range(limit):
  121. record = self._record()
  122. record.lat = float(TESTING_LAT) + (i / 10000000)
  123. record.lon = float(TESTING_LON) - (i / 10000000)
  124. records.append(record)
  125. self.addRecordsAndSleep(TESTING_LAYER, records)
  126. radius = 1.5
  127. nearby_result = self.client.get_nearby(TESTING_LAYER, TESTING_LAT, TESTING_LON, limit=limit, radius=radius)
  128. features = nearby_result.get('features')
  129. self.assertTrue(len(features) <= limit)
  130. for feature in features:
  131. self.assertTrue(float(feature.get('distance')) <= radius*1000)
  132. def test_nearby_tag_search(self):
  133. limit = 5
  134. records = []
  135. for i in range(limit):
  136. record = self._record()
  137. record.lat = float(TESTING_LAT) + (i / 10000000)
  138. record.lon = float(TESTING_LON) - (i / 10000000)
  139. record.tags = ['restaurant', 'featured']
  140. records.append(record)
  141. records[0].tags = ['featured']
  142. self.addRecordsAndSleep(TESTING_LAYER, records)
  143. nearby_result = self.client.get_nearby(TESTING_LAYER, TESTING_LAT, TESTING_LON, tag='featured')
  144. features = nearby_result.get('features')
  145. self.assertEquals(len(features), 5)
  146. nearby_result = self.client.get_nearby(TESTING_LAYER, TESTING_LAT, TESTING_LON, tag='restaurant')
  147. features = nearby_result.get('features')
  148. self.assertEquals(len(features), 4)
  149. def test_nearby_address_search(self):
  150. address_result = self.client.get_nearby_address(TESTING_LAT, TESTING_LON)
  151. self.assertAddressEquals(address_result)
  152. self.assertRaises(APIError, self.client.get_nearby_address, TESTING_LAT_NON_US, TESTING_LON_NON_US)
  153. def test_contains_and_boundary(self):
  154. contains_result = self.client.get_contains(TESTING_LAT, TESTING_LON)
  155. for feature in contains_result:
  156. self.assertTrue(feature.get('bounds')[0] <= float(TESTING_LON) <= feature.get('bounds')[2])
  157. self.assertTrue(feature.get('bounds')[1] <= float(TESTING_LAT) <= feature.get('bounds')[3])
  158. boundary_dict = self.client.get_boundary(feature.get('id'))
  159. self.assertTrue(feature.get('id'), boundary_dict.get('id'))
  160. def test_overlaps(self):
  161. limit = 1
  162. overlaps_result = self.client.get_overlaps(TESTING_BOUNDS[1], TESTING_BOUNDS[0], TESTING_BOUNDS[3], TESTING_BOUNDS[2], limit=limit)
  163. self.assertOverlapEquals(overlaps_result[0])
  164. def test_density(self):
  165. density_results = self.client.get_density(TESTING_LAT, TESTING_LON, 'mon')
  166. features = density_results.get('features')
  167. self.assertEquals(len(features), 24)
  168. for feature in features:
  169. self.assertEquals(feature.get('properties').get('dayname'), 'mon')
  170. self.assertCorrectCoordinates(feature.get('geometry').get('coordinates'))
  171. def test_hour_density(self):
  172. density_results = self.client.get_density(TESTING_LAT, TESTING_LON, 'mon', 0)
  173. self.assertEqual(density_results.get('properties').get('dayname'), 'mon')
  174. self.assertEqual(density_results.get('properties').get('hour'), 0)
  175. self.assertCorrectCoordinates(density_results.get('geometry').get('coordinates'))
  176. def test_connection_refused(self):
  177. self.client = Client(MY_OAUTH_KEY, MY_OAUTH_SECRET, API_VERSION, API_HOST, INVALID_API_PORT)
  178. self.assertRaises(socket.error, lambda: self.client.get_layer(TESTING_LAYER))
  179. # Utility functions
  180. def assertPointIsRecord(self, point, record):
  181. self.assertEquals(point['type'], 'Feature')
  182. self.assertEquals(point['id'], record.id)
  183. self.assertEquals(point['layerLink']['href'],
  184. 'http://api.simplegeo.com/0.1/layer/%s.json'
  185. % record.layer)
  186. self.assertEquals(point['selfLink']['href'],
  187. 'http://api.simplegeo.com/0.1/records/%s/%s.json'
  188. % (record.layer, record.id))
  189. self.assertEquals(point['created'], record.created)
  190. self.assertEquals(point['geometry']['type'], 'Point')
  191. self.assertEquals(point['geometry']['coordinates'][0], float(record.lon))
  192. self.assertEquals(point['geometry']['coordinates'][1], float(record.lat))
  193. def addRecordAndSleep(self, record):
  194. self.client.add_record(record)
  195. self.created_records.append(record)
  196. time.sleep(5)
  197. def addRecordsAndSleep(self, layer, records):
  198. self.client.add_records(layer, records)
  199. self.created_records += records
  200. time.sleep(5)
  201. def assertAddressEquals(self, record):
  202. self.assertEquals(record.get('properties').get('state_name'), 'California')
  203. self.assertEquals(record.get('properties').get('street_number'), '4176')
  204. self.assertEquals(record.get('properties').get('country'), 'US')
  205. self.assertEquals(record.get('properties').get('street'), '26th St')
  206. self.assertEquals(record.get('properties').get('postal_code'), '94131')
  207. self.assertEquals(record.get('properties').get('county_name'), 'San Francisco')
  208. self.assertEquals(record.get('properties').get('county_code'), '075')
  209. self.assertEquals(record.get('properties').get('state_code'), 'CA')
  210. self.assertEquals(record.get('properties').get('place_name'), 'San Francisco')
  211. def assertOverlapEquals(self, record):
  212. self.assertEquals(record.get('name'), '06075021500')
  213. self.assertEquals(record.get('type'), 'Census Tract')
  214. self.assertEquals(record.get('bounds')[0], -122.431477)
  215. self.assertEquals(record.get('bounds')[1], 37.741833)
  216. self.assertEquals(record.get('bounds')[2], -122.421328)
  217. self.assertEquals(record.get('bounds')[3], 37.748123999999997)
  218. self.assertEquals(record.get('abbr'), '')
  219. self.assertEquals(record.get('id'), 'Census_Tract:06075021500:9q8ywp')
  220. def assertCorrectCoordinates(self, coordinate_list):
  221. self.assertEquals(coordinate_list[0][0], 37.748046875)
  222. self.assertEquals(coordinate_list[0][1], -122.43359375)
  223. self.assertEquals(coordinate_list[1][0], 37.7490234375)
  224. self.assertEquals(coordinate_list[1][1], -122.43359375)
  225. self.assertEquals(coordinate_list[2][0], 37.7490234375)
  226. self.assertEquals(coordinate_list[2][1], -122.4326171875)
  227. self.assertEquals(coordinate_list[3][0], 37.748046875)
  228. self.assertEquals(coordinate_list[3][1], -122.4326171875)
  229. self.assertEquals(coordinate_list[4][0], 37.748046875)
  230. self.assertEquals(coordinate_list[4][1], -122.43359375)
  231. if __name__ == '__main__':
  232. unittest.main()