コード例 #1
0
ファイル: test_separators.py プロジェクト: bingwei/pyutil
    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)
コード例 #2
0
 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)
コード例 #3
0
    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')
コード例 #4
0
    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')
コード例 #5
0
    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')
コード例 #6
0
ファイル: __init__.py プロジェクト: dsmith/python-simplegeo
 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))
コード例 #7
0
    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)
コード例 #8
0
    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')
コード例 #9
0
    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))
コード例 #10
0
        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}))
コード例 #11
0
    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')
コード例 #12
0
    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
コード例 #13
0
    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')
コード例 #14
0
ファイル: __init__.py プロジェクト: dsmith/python-simplegeo
    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])
コード例 #15
0
ファイル: __init__.py プロジェクト: ieure/python-simplegeo
    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])
コード例 #16
0
    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')
コード例 #17
0
 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)
コード例 #18
0
ファイル: __init__.py プロジェクト: simplegeo/python-geojson
def dumps(obj, *args, **kwargs):
    return json.dumps(obj.to_dict(), *args, **kwargs)
コード例 #19
0
        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}))
コード例 #20
0
    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')
コード例 #21
0
    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')
コード例 #22
0
    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')
コード例 #23
0
 def test_floats(self):
     for num in [1617161771.7650001, math.pi, math.pi**100, math.pi**-100]:
         self.assertEquals(float(json.dumps(num)), num)
コード例 #24
0
ファイル: test_default.py プロジェクト: bingwei/pyutil
 def test_default(self):
     self.assertEquals(
         json.dumps(type, default=repr),
         json.dumps(repr(type)))
コード例 #25
0
ファイル: test_unicode.py プロジェクト: bingwei/pyutil
 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"]')
コード例 #26
0
def ue(N):
    return jsonutil.dumps(l)
コード例 #27
0
 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))
コード例 #28
0
 def test_dumps(self):
     self.assertEquals(json.dumps({}), '{}')
コード例 #29
0
ファイル: test_unicode.py プロジェクト: bingwei/pyutil
 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,))
コード例 #30
0
    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')
コード例 #31
0
    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')
コード例 #32
0
 def test_encode(self):
     self.failUnlessEqual(jsonutil.dumps(zero_point_one), "0.1")
コード例 #33
0
    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')
コード例 #34
0
ファイル: test_unicode.py プロジェクト: bingwei/pyutil
 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)
コード例 #35
0
    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')
コード例 #36
0
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')
コード例 #37
0
    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')
コード例 #38
0
 def to_json(self):
     return json.dumps(self.to_dict())
コード例 #39
0
ファイル: test_pass3.py プロジェクト: bingwei/pyutil
 def test_parse(self):
     # test in/out equivalence and parsing
     res = json.loads(JSON)
     out = json.dumps(res)
     self.assertEquals(res, json.loads(out))
コード例 #40
0
ファイル: test_unicode.py プロジェクト: bingwei/pyutil
 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"')