def test_separators(self): h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth', {'nifty': 87}, {'field': 'yes', 'morefield': False} ] expect = textwrap.dedent("""\ [ [ "blorpie" ] , [ "whoops" ] , [] , "d-shtaeou" , "d-nthiouh" , "i-vhbjkhnth" , { "nifty" : 87 } , { "field" : "yes" , "morefield" : false } ]""") d1 = json.dumps(h) d2 = json.dumps(h, indent=2, sort_keys=True, separators=(' ,', ' : ')) h1 = json.loads(d1) h2 = json.loads(d2) self.assertEquals(h1, h) self.assertEquals(h2, h) self.assertEquals(d2, expect)
def test_dictrecursion(self): x = {} x["test"] = x try: json.dumps(x) except ValueError: pass else: self.fail("didn't raise ValueError on dict recursion") x = {} {"a": x, "b": x} # ensure that the marker is cleared json.dumps(x)
def test_radius_search_by_address(self): mockhttp = mock.Mock() mockhttp.request.return_value = ({ 'status': '200', 'content-type': 'application/json', }, json.dumps({ 'type': "FeatureColllection", 'features': [] })) self.client.places.http = mockhttp lat = D('11.03') lon = D('10.04') radius = D('0.01') self.failUnlessRaises( (AssertionError, TypeError), self.client.places.search_by_address, lat, lon, radius=radius ) # Someone accidentally passed a lat,lon to search_by_address(). addr = '41 Decatur St, San Francisco, CA' res = self.client.places.search_by_address(addr, radius=radius) self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 0) self.assertEqual(mockhttp.method_calls[0][0], 'request') self.assertEqual( mockhttp.method_calls[0][1][0], 'http://api.simplegeo.com:80/%s/places/address.json?radius=%s&address=%s' % (API_VERSION, radius, urllib.quote_plus(addr))) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def test_search_by_my_ip_nonascii(self): rec1 = Feature((D('11.03'), D('10.04')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={ 'name': "Bob's House Of Monkeys", 'category': "monkey dealership" }) rec2 = Feature((D('11.03'), D('10.05')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={ 'name': "Monkey Food 'R' Us", 'category': "pet food store" }) mockhttp = mock.Mock() mockhttp.request.return_value = ({ 'status': '200', 'content-type': 'application/json', }, json.dumps({ 'type': "FeatureColllection", 'features': [rec1.to_dict(), rec2.to_dict()] })) self.client.places.http = mockhttp ipaddr = '192.0.32.10' self.failUnlessRaises( AssertionError, self.client.places.search_by_my_ip, ipaddr ) # Someone accidentally passed an ip addr to search_by_my_ip(). res = self.client.places.search_by_my_ip(query='monk❥y', category='animal') self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 2) self.failUnless(all(isinstance(f, Feature) for f in res)) self.assertEqual(mockhttp.method_calls[-1][0], 'request') urlused = mockhttp.method_calls[-1][1][0] urlused = urllib.unquote(urlused).decode('utf-8') self.assertEqual( urlused, u'http://api.simplegeo.com:80/%s/places/ip.json?q=monk❥y&category=animal' % (API_VERSION, )) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET') res = self.client.places.search_by_my_ip(query='monk❥y', category='anim❥l') self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 2) self.failUnless(all(isinstance(f, Feature) for f in res)) self.assertEqual(mockhttp.method_calls[-1][0], 'request') urlused = mockhttp.method_calls[-1][1][0] urlused = urllib.unquote(urlused).decode('utf-8') self.assertEqual( urlused, u'http://api.simplegeo.com:80/%s/places/ip.json?q=monk❥y&category=anim❥l' % (API_VERSION, )) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def test_radius_search_by_my_ip(self): mockhttp = mock.Mock() mockhttp.request.return_value = ({ 'status': '200', 'content-type': 'application/json', }, json.dumps({ 'type': "FeatureColllection", 'features': [] })) self.client.places.http = mockhttp ipaddr = '192.0.32.10' radius = D('0.01') self.failUnlessRaises( (AssertionError, TypeError), self.client.places.search_by_my_ip, ipaddr, radius=radius ) # Someone accidentally passed an ip addr to search_by_my_ip(). res = self.client.places.search_by_my_ip(radius=radius) self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 0) self.assertEqual(mockhttp.method_calls[0][0], 'request') self.assertEqual( mockhttp.method_calls[0][1][0], 'http://api.simplegeo.com:80/%s/places/ip.json?radius=%s' % (API_VERSION, radius)) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def add_records(self, layer, records): features = { 'type': 'FeatureCollection', 'features': [record.to_dict() for record in records], } endpoint = self._endpoint('add_records', layer=layer) self._request(endpoint, "POST", json.dumps(features))
def test_dont_Featureify_results(self): """ _request() is required to return the exact string that the HTTP server sent to it -- no transforming it, such as by json-decoding and then constructing a Feature. """ EXAMPLE_RECORD_JSONSTR=json.dumps({ 'geometry' : { 'type' : 'Point', 'coordinates' : [D('10.0'), D('11.0')] }, 'id' : 'my_id', 'type' : 'Feature', 'properties' : { 'key' : 'value' , 'type' : 'object' } }) mockhttp = mock.Mock() mockhttp.request.return_value = ({'status': '200', 'content-type': 'application/json', }, EXAMPLE_RECORD_JSONSTR) self.client.places.http = mockhttp res = self.client.places._request("http://thing", 'POST')[1] self.failUnlessEqual(res, EXAMPLE_RECORD_JSONSTR)
def test_search_nonascii(self): rec1 = Feature((D('11.03'), D('10.04')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={ 'name': u"B❤b's House Of Monkeys", 'category': u"m❤nkey dealership" }) rec2 = Feature((D('11.03'), D('10.05')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={ 'name': u"M❤nkey Food 'R' Us", 'category': "pet food store" }) mockhttp = mock.Mock() mockhttp.request.return_value = ({ 'status': '200', 'content-type': 'application/json', }, json.dumps({ 'type': "FeatureColllection", 'features': [rec1.to_dict(), rec2.to_dict()] })) self.client.places.http = mockhttp self.failUnlessRaises(AssertionError, self.client.places.search, -91, 100) self.failUnlessRaises(AssertionError, self.client.places.search, -81, 361) lat = D('11.03') lon = D('10.04') res = self.client.places.search(lat, lon, query=u'm❤nkey', category='animal') self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 2) self.failUnless(all(isinstance(f, Feature) for f in res)) self.assertEqual(mockhttp.method_calls[0][0], 'request') urlused = mockhttp.method_calls[0][1][0] urlused = urllib.unquote(urlused).decode('utf-8') self.assertEqual( urlused, u'http://api.simplegeo.com:80/%s/places/%s,%s.json?q=m❤nkey&category=animal' % (API_VERSION, lat, lon)) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def test_annotate(self): mockhttp = mock.Mock() headers = {'status': '200', 'content-type': 'application/json'} mockhttp.request.return_value = (headers, json.dumps(EXAMPLE_ANNOTATE_RESPONSE)) self.client.http = mockhttp res = self.client.annotate(self.handle, EXAMPLE_ANNOTATIONS, True) self.assertEqual(mockhttp.method_calls[0][0], 'request') self.assertEqual(mockhttp.method_calls[0][1][0], 'http://api.simplegeo.com:80/%s/features/%s/annotations.json' % (API_VERSION, self.handle)) self.assertEqual(mockhttp.method_calls[0][1][1], 'POST') # Make sure client returns a dict. self.failUnless(isinstance(res, dict))
def mockrequest(*args, **kwargs): self.assertEqual( args[0], 'http://api.simplegeo.com:80/%s/places' % (API_VERSION, )) self.assertEqual(args[1], 'POST') bodyobj = json.loads(kwargs['body']) self.failUnlessEqual(bodyobj['id'], None) methods_called.append(('request', args, kwargs)) mockhttp.request = mockrequest2 return ({ 'status': '202', 'content-type': 'application/json', 'location': newloc }, json.dumps({'id': handle}))
def test_search_by_ip(self): rec1 = Feature((D('11.03'), D('10.04')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={ 'name': "Bob's House Of Monkeys", 'category': "monkey dealership" }) rec2 = Feature((D('11.03'), D('10.05')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={ 'name': "Monkey Food 'R' Us", 'category': "pet food store" }) mockhttp = mock.Mock() mockhttp.request.return_value = ({ 'status': '200', 'content-type': 'application/json', }, json.dumps({ 'type': "FeatureColllection", 'features': [rec1.to_dict(), rec2.to_dict()] })) self.client.places.http = mockhttp self.failUnlessRaises(AssertionError, self.client.places.search_by_ip, 'this is not an IP address at all, silly') self.failUnlessRaises( AssertionError, self.client.places.search_by_ip, -81, 181) # Someone accidentally passed lat, lon to search_by_ip(). ipaddr = '192.0.32.10' res = self.client.places.search_by_ip(ipaddr, query='monkeys', category='animal') self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 2) self.failUnless(all(isinstance(f, Feature) for f in res)) self.assertEqual(mockhttp.method_calls[0][0], 'request') self.assertEqual( mockhttp.method_calls[0][1][0], 'http://api.simplegeo.com:80/%s/places/%s.json?q=monkeys&category=animal' % (API_VERSION, ipaddr)) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def test_dont_Recordify_results(self): """ _request() is required to return the exact string that the HTTP server sent to it -- no transforming it, such as by json-decoding and then constructing a Record. """ EXAMPLE_RECORD_JSONSTR=json.dumps({ 'geometry' : { 'type' : 'Point', 'coordinates' : [D('10.0'), D('11.0')] }, 'id' : 'my_id', 'type' : 'Feature', 'properties' : { 'key' : 'value' , 'type' : 'object' } }) mockagent = MockAgent(FakeSuccessResponse([EXAMPLE_RECORD_JSONSTR], {'status': '200', 'content-type': 'application/json'})) self.client.agent = mockagent d = self.client._request("http://thing", 'POST') d.addCallback(get_body) def check(res): self.failUnlessEqual(res, EXAMPLE_RECORD_JSONSTR) d.addCallback(check) return d
def test_no_terms_search_by_address(self): rec1 = Feature((D('11.03'), D('10.04')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={ 'name': "Bob's House Of Monkeys", 'category': "monkey dealership" }) rec2 = Feature((D('11.03'), D('10.05')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={ 'name': "Monkey Food 'R' Us", 'category': "pet food store" }) mockhttp = mock.Mock() mockhttp.request.return_value = ({ 'status': '200', 'content-type': 'application/json', }, json.dumps({ 'type': "FeatureColllection", 'features': [rec1.to_dict(), rec2.to_dict()] })) self.client.places.http = mockhttp lat = D('11.03') lon = D('10.04') self.failUnlessRaises( AssertionError, self.client.places.search_by_address, lat, lon) # Someone accidentally passed a lat,lon search_by_address(). addr = '41 Decatur St, San Francisco, CA' res = self.client.places.search_by_address(addr) self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 2) self.failUnless(all(isinstance(f, Feature) for f in res)) self.assertEqual(mockhttp.method_calls[0][0], 'request') self.assertEqual( mockhttp.method_calls[0][1][0], 'http://api.simplegeo.com:80/%s/places/address.json?address=%s' % (API_VERSION, urllib.quote_plus(addr))) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def annotate(self, simplegeohandle, annotations, private): if not isinstance(annotations, dict): raise TypeError('annotations must be of type dict') if not len(annotations.keys()): raise ValueError('annotations dict is empty') for annotation_type in annotations.keys(): if not len(annotations[annotation_type].keys()): raise ValueError('annotation type "%s" is empty' % annotation_type) if not isinstance(private, bool): raise TypeError('private must be of type bool') data = {'annotations': annotations, 'private': private} endpoint = self._endpoint('annotations', simplegeohandle=simplegeohandle) return json_decode( self._request(endpoint, 'POST', data=json.dumps(data))[1])
def annotate(self, simplegeohandle, annotations, private): if not isinstance(annotations, dict): raise TypeError('annotations must be of type dict') if not len(annotations.keys()): raise ValueError('annotations dict is empty') for annotation_type in annotations.keys(): if not len(annotations[annotation_type].keys()): raise ValueError('annotation type "%s" is empty' % annotation_type) if not isinstance(private, bool): raise TypeError('private must be of type bool') data = {'annotations': annotations, 'private': private} endpoint = self._endpoint('annotations', simplegeohandle=simplegeohandle) return json_decode(self._request(endpoint, 'POST', data=json.dumps(data))[1])
def test_radius_search(self): mockhttp = mock.Mock() mockhttp.request.return_value = ({ 'status': '200', 'content-type': 'application/json', }, json.dumps({ 'type': "FeatureColllection", 'features': [] })) self.client.places.http = mockhttp lat = D('11.03') lon = D('10.04') radius = D('0.01') res = self.client.places.search(lat, lon, radius=radius) self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 0) self.assertEqual(mockhttp.method_calls[0][0], 'request') self.assertEqual( mockhttp.method_calls[0][1][0], 'http://api.simplegeo.com:80/%s/places/%s,%s.json?radius=%s' % (API_VERSION, lat, lon, radius)) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def test_listrecursion(self): x = [] x.append(x) try: json.dumps(x) except ValueError: pass else: self.fail("didn't raise ValueError on list recursion") x = [] y = [x] x.append(y) try: json.dumps(x) except ValueError: pass else: self.fail("didn't raise ValueError on alternating list recursion") y = [] x = [y, y] # ensure that the marker is cleared json.dumps(x)
def dumps(obj, *args, **kwargs): return json.dumps(obj.to_dict(), *args, **kwargs)
def mockrequest(*args, **kwargs): self.assertEqual(args[0], 'http://api.simplegeo.com:80/%s/places' % (API_VERSION,)) self.assertEqual(args[1], 'POST') bodyobj = json.loads(kwargs['body']) self.failUnlessEqual(bodyobj['id'], None) methods_called.append(('request', args, kwargs)) mockhttp.request = mockrequest2 return ({'status': '202', 'content-type': 'application/json', 'location': newloc}, json.dumps({'id': handle}))
def test_no_terms_search_by_ip(self): rec1 = Feature((D('11.03'), D('10.04')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={'name': "Bob's House Of Monkeys", 'category': "monkey dealership"}) rec2 = Feature((D('11.03'), D('10.05')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={'name': "Monkey Food 'R' Us", 'category': "pet food store"}) mockhttp = mock.Mock() mockhttp.request.return_value = ({'status': '200', 'content-type': 'application/json', }, json.dumps({'type': "FeatureColllection", 'features': [rec1.to_dict(), rec2.to_dict()]})) self.client.places.http = mockhttp ipaddr = '192.0.32.10' res = self.client.places.search_by_ip(ipaddr) self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 2) self.failUnless(all(isinstance(f, Feature) for f in res)) self.assertEqual(mockhttp.method_calls[0][0], 'request') self.assertEqual(mockhttp.method_calls[0][1][0], 'http://api.simplegeo.com:80/%s/places/%s.json' % (API_VERSION, ipaddr)) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def test_radius_search_by_my_ip(self): mockhttp = mock.Mock() mockhttp.request.return_value = ({'status': '200', 'content-type': 'application/json', }, json.dumps({'type': "FeatureColllection", 'features': []})) self.client.places.http = mockhttp ipaddr = '192.0.32.10' radius = D('0.01') self.failUnlessRaises((AssertionError, TypeError), self.client.places.search_by_my_ip, ipaddr, radius=radius) # Someone accidentally passed an ip addr to search_by_my_ip(). res = self.client.places.search_by_my_ip(radius=radius) self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 0) self.assertEqual(mockhttp.method_calls[0][0], 'request') self.assertEqual(mockhttp.method_calls[0][1][0], 'http://api.simplegeo.com:80/%s/places/ip.json?radius=%s' % (API_VERSION, radius)) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def test_search_by_address_nonascii(self): rec1 = Feature((D('11.03'), D('10.04')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={'name': "Bob's House Of Monkeys", 'category': "monkey dealership"}) rec2 = Feature((D('11.03'), D('10.05')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={'name': "Monkey Food 'R' Us", 'category': "pet food store"}) mockhttp = mock.Mock() mockhttp.request.return_value = ({'status': '200', 'content-type': 'application/json', }, json.dumps({'type': "FeatureColllection", 'features': [rec1.to_dict(), rec2.to_dict()]})) self.client.places.http = mockhttp lat = D('11.03') lon = D('10.04') self.failUnlessRaises(AssertionError, self.client.places.search_by_address, lat, lon) # Someone accidentally passed a lat,lon to search_by_address(). addr = u'41 Decatur St, San Francisc❦, CA' res = self.client.places.search_by_address(addr, query='monkeys', category='animal') self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 2) self.failUnless(all(isinstance(f, Feature) for f in res)) self.assertEqual(mockhttp.method_calls[-1][0], 'request') urlused = mockhttp.method_calls[-1][1][0] cod = urllib.quote_plus(addr.encode('utf-8')) self.assertEqual(urlused, 'http://api.simplegeo.com:80/%s/places/address.json?q=monkeys&category=animal&address=%s' % (API_VERSION, cod,)) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET') res = self.client.places.search_by_address(addr, query=u'monke❦s', category=u'ani❦al') self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 2) self.failUnless(all(isinstance(f, Feature) for f in res)) self.assertEqual(mockhttp.method_calls[-1][0], 'request') urlused = mockhttp.method_calls[-1][1][0] quargs = {'q': u'monke❦s', 'category': u'ani❦al', 'address': addr} equargs = dict( (k, v.encode('utf-8')) for k, v in quargs.iteritems() ) s2quargs = urllib.urlencode(equargs) self.assertEqual(urlused, 'http://api.simplegeo.com:80/%s/places/address.json?%s' % (API_VERSION, s2quargs)) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def test_floats(self): for num in [1617161771.7650001, math.pi, math.pi**100, math.pi**-100]: self.assertEquals(float(json.dumps(num)), num)
def test_default(self): self.assertEquals( json.dumps(type, default=repr), json.dumps(repr(type)))
def test_encoding4(self): u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' j = json.dumps([u]) self.assertEquals(j, '["\\u03b1\\u03a9"]')
def ue(N): return jsonutil.dumps(l)
def test_parse(self): # test in/out equivalence and parsing res = json.loads(JSON) out = json.dumps(res) self.assertEquals(res, json.loads(out)) self.failUnless("2.3456789012E+676" in json.dumps(res, allow_nan=False))
def test_dumps(self): self.assertEquals(json.dumps({}), '{}')
def test_encoding6(self): u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' j = json.dumps([u], ensure_ascii=False) self.assertEquals(j, u'["%s"]' % (u,))
def test_search(self): rec1 = Feature((D('11.03'), D('10.04')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={'name': "Bob's House Of Monkeys", 'category': "monkey dealership"}) rec2 = Feature((D('11.03'), D('10.05')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={'name': "Monkey Food 'R' Us", 'category': "pet food store"}) mockhttp = mock.Mock() mockhttp.request.return_value = ({'status': '200', 'content-type': 'application/json', }, json.dumps({'type': "FeatureColllection", 'features': [rec1.to_dict(), rec2.to_dict()]})) self.client.places.http = mockhttp self.failUnlessRaises(AssertionError, self.client.places.search, -91, 100) self.failUnlessRaises(AssertionError, self.client.places.search, -81, 361) lat = D('11.03') lon = D('10.04') res = self.client.places.search(lat, lon, query='monkeys', category='animal') self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 2) self.failUnless(all(isinstance(f, Feature) for f in res)) self.assertEqual(mockhttp.method_calls[0][0], 'request') self.assertEqual(mockhttp.method_calls[0][1][0], 'http://api.simplegeo.com:80/%s/places/%s,%s.json?q=monkeys&category=animal' % (API_VERSION, lat, lon)) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def test_search_by_my_ip_nonascii(self): rec1 = Feature((D('11.03'), D('10.04')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={'name': "Bob's House Of Monkeys", 'category': "monkey dealership"}) rec2 = Feature((D('11.03'), D('10.05')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={'name': "Monkey Food 'R' Us", 'category': "pet food store"}) mockhttp = mock.Mock() mockhttp.request.return_value = ({'status': '200', 'content-type': 'application/json', }, json.dumps({'type': "FeatureColllection", 'features': [rec1.to_dict(), rec2.to_dict()]})) self.client.places.http = mockhttp ipaddr = '192.0.32.10' self.failUnlessRaises(AssertionError, self.client.places.search_by_my_ip, ipaddr) # Someone accidentally passed an ip addr to search_by_my_ip(). res = self.client.places.search_by_my_ip(query='monk❥y', category='animal') self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 2) self.failUnless(all(isinstance(f, Feature) for f in res)) self.assertEqual(mockhttp.method_calls[-1][0], 'request') urlused = mockhttp.method_calls[-1][1][0] urlused = urllib.unquote(urlused).decode('utf-8') self.assertEqual(urlused, u'http://api.simplegeo.com:80/%s/places/ip.json?q=monk❥y&category=animal' % (API_VERSION,)) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET') res = self.client.places.search_by_my_ip(query='monk❥y', category='anim❥l') self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 2) self.failUnless(all(isinstance(f, Feature) for f in res)) self.assertEqual(mockhttp.method_calls[-1][0], 'request') urlused = mockhttp.method_calls[-1][1][0] urlused = urllib.unquote(urlused).decode('utf-8') self.assertEqual(urlused, u'http://api.simplegeo.com:80/%s/places/ip.json?q=monk❥y&category=anim❥l' % (API_VERSION,)) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def test_encode(self): self.failUnlessEqual(jsonutil.dumps(zero_point_one), "0.1")
def test_radius_search(self): mockhttp = mock.Mock() mockhttp.request.return_value = ({'status': '200', 'content-type': 'application/json', }, json.dumps({'type': "FeatureColllection", 'features': []})) self.client.places.http = mockhttp lat = D('11.03') lon = D('10.04') radius = D('0.01') res = self.client.places.search(lat, lon, radius=radius) self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 0) self.assertEqual(mockhttp.method_calls[0][0], 'request') self.assertEqual(mockhttp.method_calls[0][1][0], 'http://api.simplegeo.com:80/%s/places/%s,%s.json?radius=%s' % (API_VERSION, lat, lon, radius)) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def test_encoding2(self): u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' s = u.encode('utf-8') ju = json.dumps(u, encoding='utf-8') js = json.dumps(s, encoding='utf-8') self.assertEquals(ju, js)
def test_radius_search_by_address(self): mockhttp = mock.Mock() mockhttp.request.return_value = ({'status': '200', 'content-type': 'application/json', }, json.dumps({'type': "FeatureColllection", 'features': []})) self.client.places.http = mockhttp lat = D('11.03') lon = D('10.04') radius = D('0.01') self.failUnlessRaises((AssertionError, TypeError), self.client.places.search_by_address, lat, lon, radius=radius) # Someone accidentally passed a lat,lon to search_by_address(). addr = '41 Decatur St, San Francisco, CA' res = self.client.places.search_by_address(addr, radius=radius) self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 0) self.assertEqual(mockhttp.method_calls[0][0], 'request') self.assertEqual(mockhttp.method_calls[0][1][0], 'http://api.simplegeo.com:80/%s/places/address.json?radius=%s&address=%s' % (API_VERSION, radius, urllib.quote_plus(addr))) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
from decimal import Decimal as D import mock MY_OAUTH_KEY = 'MY_OAUTH_KEY' MY_OAUTH_SECRET = 'MY_SECRET_KEY' TESTING_LAYER = 'TESTING_LAYER' API_VERSION = '1.0' API_HOST = 'api.simplegeo.com' API_PORT = 80 ENDPOINT_DESCR=json.dumps({ "GET /1.0/features/<handle:[a-zA-Z0-9\\.,_-]+>.json": "Return a feature for a place.", "POST /1.0/features/<handle:.*>.json": "Update a feature.", "GET /1.0/places/<lat:-?[0-9\\.]+>,<lon:-?[0-9\\.]+>.json": "Search for places near a lat/lon. Query string includes ?q=term and ?q=term&category=cat", "POST /1.0/places": "Create a new record, returns the handle", "GET /1.0/debug/<number:\\d+>": "Undocumented.", "DELETE /1.0/features/<handle:.*>.json": "Delete a feature."}) class ClientTest(unittest.TestCase): def setUp(self): self.client = Client(MY_OAUTH_KEY, MY_OAUTH_SECRET, API_VERSION, API_HOST, API_PORT) def test_wrong_endpoint(self): self.assertRaises(Exception, self.client._endpoint, 'featuret') def test_missing_argument(self): self.assertRaises(Exception, self.client._endpoint, 'features')
def test_no_terms_search_by_address(self): rec1 = Feature((D('11.03'), D('10.04')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={'name': "Bob's House Of Monkeys", 'category': "monkey dealership"}) rec2 = Feature((D('11.03'), D('10.05')), simplegeohandle='SG_abcdefghijkmlnopqrstuv', properties={'name': "Monkey Food 'R' Us", 'category': "pet food store"}) mockhttp = mock.Mock() mockhttp.request.return_value = ({'status': '200', 'content-type': 'application/json', }, json.dumps({'type': "FeatureColllection", 'features': [rec1.to_dict(), rec2.to_dict()]})) self.client.places.http = mockhttp lat = D('11.03') lon = D('10.04') self.failUnlessRaises(AssertionError, self.client.places.search_by_address, lat, lon) # Someone accidentally passed a lat,lon search_by_address(). addr = '41 Decatur St, San Francisco, CA' res = self.client.places.search_by_address(addr) self.failUnless(isinstance(res, (list, tuple)), (repr(res), type(res))) self.failUnlessEqual(len(res), 2) self.failUnless(all(isinstance(f, Feature) for f in res)) self.assertEqual(mockhttp.method_calls[0][0], 'request') self.assertEqual(mockhttp.method_calls[0][1][0], 'http://api.simplegeo.com:80/%s/places/address.json?address=%s' % (API_VERSION, urllib.quote_plus(addr))) self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')
def to_json(self): return json.dumps(self.to_dict())
def test_parse(self): # test in/out equivalence and parsing res = json.loads(JSON) out = json.dumps(res) self.assertEquals(res, json.loads(out))
def test_big_unicode_encode(self): u = u'\U0001d120' self.assertEquals(json.dumps(u), '"\\ud834\\udd20"') self.assertEquals(json.dumps(u, ensure_ascii=False), u'"\U0001d120"')