Beispiel #1
0
def test_simple_rule():    
    # skip this test if simplegeneric is not installed
    try:
        import simplegeneric
    except ImportError:
        return
    
    # create a Person instance
    p = Person('Jonathan', 'LaCour')
    
    # encode the object using the existing "default" rules
    result = loads(encode(p))
    assert result['first_name'] == 'Jonathan'
    assert result['last_name'] == 'LaCour'
    assert len(result) == 2
    
    # register a generic JSON rule
    @jsonify.when_type(Person)
    def jsonify_person(obj):
        return dict(
            name=obj.name
        )
    
    # encode the object using our new rule
    result = loads(encode(p))
    assert result['name'] == 'Jonathan LaCour'
    assert len(result) == 1
 def test_detached_saobj():
     s = create_session()
     t = s.query(Test1).get(1)
     # ensure it can be serialized now
     jsonify.encode(t)
     s.expunge(t)
     assert_raises(ValueError, lambda: jsonify.encode(t))
 def test_detached_saobj():
     s = create_session()
     t = s.query(Test1).get(1)
     # ensure it can be serialized now
     jsonify.encode(t)
     s.expunge(t)
     assert_raises(ValueError, lambda: jsonify.encode(t))
Beispiel #4
0
def test_simple_rule():
    # skip this test if simplegeneric is not installed
    try:
        import simplegeneric
    except ImportError:
        return

    # create a Person instance
    p = Person('Jonathan', 'LaCour')

    # encode the object using the existing "default" rules
    result = loads(encode(p))
    assert result['first_name'] == 'Jonathan'
    assert result['last_name'] == 'LaCour'
    assert len(result) == 2

    # register a generic JSON rule
    @jsonify.when_type(Person)
    def jsonify_person(obj):
        return dict(name=obj.name)

    # encode the object using our new rule
    result = loads(encode(p))
    assert result['name'] == 'Jonathan LaCour'
    assert len(result) == 1
 def test_explicit_saobj():
     s = create_session()
     t = s.query(Test3).get(1)
     encoded = jsonify.encode(t)
     expected = json.loads('{"id": 1, "val": "bob", "customized": true}')
     result = json.loads(encoded)
     assert result == expected, encoded
 def test_saobj():
     s = create_session()
     t = s.query(Test1).get(1)
     encoded = jsonify.encode(t)
     expected = json.loads('{"id": 1, "val": "bob"}')
     result = json.loads(encoded)
     assert result == expected, encoded
Beispiel #7
0
def test_simple_rule():
    # create a Person instance
    p = Person("Jonathan", "LaCour")

    # encode the object using the existing "default" rules
    result = loads(encode(p))
    assert result["first_name"] == "Jonathan"
    assert result["last_name"] == "LaCour"
    assert len(result) == 2

    person_encoder = JSONEncoder(custom_encoders={Person: lambda p: dict(name=p.name)})

    # encode the object using our new rule
    result = loads(encode(p, encoder=person_encoder))
    assert result["name"] == "Jonathan LaCour"
    assert len(result) == 1
Beispiel #8
0
    def render_json(template_name, template_vars, **render_params):
        key = render_params.pop('key', None)
        if key is not None:
            template_vars = template_vars[key]

        encode = JSONRenderer._get_configured_encode(render_params)
        return encode(template_vars)
 def test_explicit_saobj():
     s = create_session()
     t = s.query(Test3).get(1)
     encoded = jsonify.encode(t)
     expected = json.loads('{"id": 1, "val": "bob", "customized": true}')
     result = json.loads(encoded)
     assert result == expected, encoded
 def test_select_rows():
     s = create_session()
     t = test2.select().execute()
     encoded = jsonify.encode(dict(results=t))
     expected = json.loads("""{"results": {"count": -1, "rows": [{"count": 1, "rows": {"test1id": 1, "id": 1, "val": "fred"}}, {"count": 1, "rows": {"test1id": 1, "id": 2, "val": "alice"}}]}}""")
     result = json.loads(encoded)
     assert result == expected, encoded
Beispiel #11
0
def test_nospecificjson():
    b = Baz()
    try:
        encoded = jsonify.encode(b)
    except TypeError as e:
        pass
    assert  "is not JSON serializable" in e.message 
Beispiel #12
0
def test_nospecificjson():
    b = Baz()
    try:
        encoded = jsonify.encode(b)
    except TypeError as e:
        pass
    assert "is not JSON serializable" in e.message
Beispiel #13
0
    def render_json(template_name, template_vars, **render_params):
        key = render_params.pop('key', None)
        if key is not None:
            template_vars = template_vars[key]

        encode = JSONRenderer._get_configured_encode(render_params)
        return encode(template_vars)
 def test_saobj():
     s = create_session()
     t = s.query(Test1).get(1)
     encoded = jsonify.encode(t)
     expected = json.loads('{"id": 1, "val": "bob"}')
     result = json.loads(encoded)
     assert result == expected, encoded
 def test_salist():
     s = create_session()
     t = s.query(Test1).get(1)
     encoded = jsonify.encode(dict(results=t.test2s))
     expected = json.loads('''{"results": [{"test1id": 1, "id": 1, "val": "fred"}, {"test1id": 1, "id": 2, "val": "alice"}]}''')
     result = json.loads(encoded)
     assert result == expected, encoded
Beispiel #16
0
def test_datetime_time_iso():
    isodates_encoder = jsonify.JSONEncoder(isodates=True)

    d = datetime.utcnow().time()
    encoded = jsonify.encode({'date': d}, encoder=isodates_encoder)

    isoformat_without_millis = json.dumps({'date': d.isoformat()[:8]})
    assert isoformat_without_millis == encoded, (isoformat_without_millis, encoded)
Beispiel #17
0
def test_simple_rule():
    # create a Person instance
    p = Person('Jonathan', 'LaCour')

    # encode the object using the existing "default" rules
    result = loads(encode(p))
    assert result['first_name'] == 'Jonathan'
    assert result['last_name'] == 'LaCour'
    assert len(result) == 2

    person_encoder = JSONEncoder(
        custom_encoders={Person: lambda p: dict(name=p.name)})

    # encode the object using our new rule
    result = loads(encode(p, encoder=person_encoder))
    assert result['name'] == 'Jonathan LaCour'
    assert len(result) == 1
Beispiel #18
0
    def render_jsonp(template_name, template_vars, **kwargs):
        pname = kwargs.get('callback_param', 'callback')
        callback = tg.request.GET.get(pname)
        if callback is None:
            raise HTTPBadRequest('JSONP requires a "%s" parameter with callback name' % pname)

        values = encode(template_vars)
        return '%s(%s);' % (callback, values)
Beispiel #19
0
    def test_select_rows():
        s = create_session()
        t = test2.select().execute()
        encoded = jsonify.encode(t)

        # this may be added back later
        #
        assert encoded == '{"count": -1, "rows": [{"count": 1, "rows": {"test1id": 1, "id": 1, "val": "fred"}},\
 {"count": 1, "rows": {"test1id": 1, "id": 2, "val": "alice"}}]}', encoded
Beispiel #20
0
    def test_select_rows():
        s = create_session()
        t = test2.select().execute()
        encoded = jsonify.encode(t)

# this may be added back later
#
        assert encoded == '{"count": -1, "rows": [{"count": 1, "rows": {"test1id": 1, "id": 1, "val": "fred"}},\
 {"count": 1, "rows": {"test1id": 1, "id": 2, "val": "alice"}}]}', encoded
Beispiel #21
0
def test_objectid():
    try:
        from bson import ObjectId
    except:
        raise SkipTest()

    d = ObjectId('507f1f77bcf86cd799439011')
    encoded = jsonify.encode({'oid':d})
    assert encoded == '{"oid": "%s"}' % d, encoded
Beispiel #22
0
 def test_select_rows_datetime():
     s = create_session()
     t = test5.select().execute()
     encoded = jsonify.encode(dict(results=t),
                              encoder=jsonify.JSONEncoder(isodates=True))
     expected = """{"results": {"count": -1, "rows": [{"count": 1, "rows": {"date": "2016-12-11T10:09:08", "id": 1, "val": "sometime", "time": "21:20:19"}}]}}"""
     encoded = json.loads(encoded)
     expected = json.loads(expected)
     assert encoded == expected, encoded
Beispiel #23
0
def test_datetime_time_iso():
    isodates_encoder = jsonify.JSONEncoder(isodates=True)

    d = datetime.utcnow().time()
    encoded = jsonify.encode({'date': d}, encoder=isodates_encoder)

    isoformat_without_millis = json.dumps({'date': d.isoformat()[:8]})
    assert isoformat_without_millis == encoded, (isoformat_without_millis,
                                                 encoded)
 def test_salist():
     s = create_session()
     t = s.query(Test1).get(1)
     encoded = jsonify.encode(dict(results=t.test2s))
     expected = json.loads(
         '''{"results": [{"test1id": 1, "id": 1, "val": "fred"}, {"test1id": 1, "id": 2, "val": "alice"}]}'''
     )
     result = json.loads(encoded)
     assert result == expected, encoded
Beispiel #25
0
def test_objectid():
    try:
        from bson import ObjectId
    except:
        raise SkipTest()

    d = ObjectId('507f1f77bcf86cd799439011')
    encoded = jsonify.encode({'oid': d})
    assert encoded == '{"oid": "%s"}' % d, encoded
 def test_select_rows():
     s = create_session()
     t = test2.select().execute()
     encoded = jsonify.encode(dict(results=t))
     expected = json.loads(
         """{"results": {"count": -1, "rows": [{"count": 1, "rows": {"test1id": 1, "id": 1, "val": "fred"}}, {"count": 1, "rows": {"test1id": 1, "id": 2, "val": "alice"}}]}}"""
     )
     result = json.loads(encoded)
     assert result == expected, encoded
Beispiel #27
0
    def _get_configured_encode(options):
        # Caching is not supported by JSON encoders
        options.pop('cache_expire', None)
        options.pop('cache_type', None)
        options.pop('cache_key', None)

        if not options:
            return encode
        else:
            return lambda obj: encode(obj, JSONEncoder(**options))
Beispiel #28
0
    def test_some(self):
        # fields = exclude_fields(Transaction, [Transaction.user, Transaction._user_id, Transaction.expenseTagGroup_id, Transaction.incomeTagGroup_id, Transaction.expenseTagGroup, Transaction.incomeTagGroup])
        transactions = DBSession.query(Transaction).options(
            subqueryload(Transaction.incomeTagGroup).subqueryload(TagGroup.tags),
            subqueryload(Transaction.expenseTagGroup).subqueryload(TagGroup.tags)
        ).all()

        transaction_json = jsonify.encode(dict(transactions=transactions))
        parsed = json.loads(transaction_json)
        print(json.dumps(parsed, indent=2, sort_keys=True), len(transactions))
Beispiel #29
0
def calculate_hash(e):
    prop_names = [
        prop.name for prop in mapper(e).properties
        if isinstance(prop, ming.odm.property.FieldProperty)
    ]
    for attr in ["hash", "_id", "tags"]:
        if attr in prop_names: prop_names.remove(attr)
    entity = {k: getattr(e, k) for k in prop_names}
    entity_string = jsonify.encode(entity).encode()
    return 'k' + hashlib.blake2b(entity_string, digest_size=6).hexdigest()
Beispiel #30
0
    def _get_configured_encode(options):
        # Caching is not supported by JSON encoders
        options.pop('cache_expire', None)
        options.pop('cache_type', None)
        options.pop('cache_key', None)

        if not options:
            return encode
        else:
            return lambda obj: encode(obj, JSONEncoder(**options))
Beispiel #31
0
def test_date_iso():
    isodates_encoder = jsonify.JSONEncoder(isodates=True)

    d = datetime.utcnow().date()
    encoded = jsonify.encode({'date': d}, encoder=isodates_encoder)

    isoformat_without_millis = json.dumps({'date': d.isoformat()})
    assert isoformat_without_millis == encoded, (isoformat_without_millis, encoded)

    loaded_date = json.loads(encoded)
    assert len(loaded_date['date'].split('-')) == 3
def test_date_iso():
    isodates_encoder = jsonify.JSONEncoder(isodates=True)

    d = datetime.utcnow().date()
    encoded = jsonify.encode({'date': d}, encoder=isodates_encoder)

    isoformat_without_millis = json.dumps({'date': d.isoformat()})
    assert isoformat_without_millis == encoded, (isoformat_without_millis,
                                                 encoded)

    loaded_date = json.loads(encoded)
    assert len(loaded_date['date'].split('-')) == 3
Beispiel #33
0
def test_builtin_override():
    # create a few date objects
    d1 = date(1979, 10, 12)
    d2 = date(2000, 1, 1)
    d3 = date(2012, 1, 1)

    # jsonify using the built in rules
    result1 = encode(dict(date=d1))
    assert '"1979-10-12"' in result1
    result2 = encode(dict(date=d2))
    assert '"2000-01-01"' in result2
    result3 = encode(dict(date=d3))
    assert '"2012-01-01"' in result3

    def jsonify_date(obj):
        if obj.year == 1979 and obj.month == 10 and obj.day == 12:
            return "Jon's Birthday!"
        elif obj.year == 2000 and obj.month == 1 and obj.day == 1:
            return "Its Y2K! Panic!"
        return "%d/%d/%d" % (obj.month, obj.day, obj.year)

    custom_date_encoder = JSONEncoder(custom_encoders={date: jsonify_date})

    # jsonify using the built in rules
    result1 = encode(dict(date=d1), encoder=custom_date_encoder)
    assert '"Jon\'s Birthday!"' in result1
    result2 = encode(dict(date=d2), encoder=custom_date_encoder)
    assert '"Its Y2K! Panic!"' in result2
    result3 = encode(dict(date=d3), encoder=custom_date_encoder)
    assert '"1/1/2012"' in result3
Beispiel #34
0
def test_builtin_override():
    # create a few date objects
    d1 = date(1979, 10, 12)
    d2 = date(2000, 1, 1)
    d3 = date(2012, 1, 1)

    # jsonify using the built in rules
    result1 = encode(dict(date=d1))
    assert '"1979-10-12"' in result1
    result2 = encode(dict(date=d2))
    assert '"2000-01-01"' in result2
    result3 = encode(dict(date=d3))
    assert '"2012-01-01"' in result3

    def jsonify_date(obj):
        if obj.year == 1979 and obj.month == 10 and obj.day == 12:
            return "Jon's Birthday!"
        elif obj.year == 2000 and obj.month == 1 and obj.day == 1:
            return "Its Y2K! Panic!"
        return '%d/%d/%d' % (obj.month, obj.day, obj.year)

    custom_date_encoder = JSONEncoder(custom_encoders={date: jsonify_date})

    # jsonify using the built in rules
    result1 = encode(dict(date=d1), encoder=custom_date_encoder)
    assert '"Jon\'s Birthday!"' in result1
    result2 = encode(dict(date=d2), encoder=custom_date_encoder)
    assert '"Its Y2K! Panic!"' in result2
    result3 = encode(dict(date=d3), encoder=custom_date_encoder)
    assert '"1/1/2012"' in result3
Beispiel #35
0
    def render_jsonp(template_name, template_vars, **render_params):
        key = render_params.pop('key', None)
        if key is not None:
            template_vars = template_vars[key]

        pname = render_params.pop('callback_param', 'callback')
        callback = tg.request.GET.get(pname)
        if callback is None:
            raise HTTPBadRequest('JSONP requires a "%s" parameter with callback name' % pname)

        encode = JSONRenderer._get_configured_encode(render_params)
        values = encode(template_vars)
        return '%s(%s);' % (callback, values)
Beispiel #36
0
    def render_jsonp(template_name, template_vars, **render_params):
        key = render_params.pop('key', None)
        if key is not None:
            template_vars = template_vars[key]

        pname = render_params.pop('callback_param', 'callback')
        callback = tg.request.GET.get(pname)
        if callback is None:
            raise HTTPBadRequest(
                'JSONP requires a "%s" parameter with callback name' % pname)

        encode = JSONRenderer._get_configured_encode(render_params)
        values = encode(template_vars)
        return '%s(%s);' % (callback, values)
Beispiel #37
0
def test_builtin_override():
    # skip this test if simplegeneric is not installed
    try:
        import simplegeneric
    except ImportError:
        return
    
    # create a few date objects
    d1 = date(1979, 10, 12)
    d2 = date(2000, 1, 1)
    d3 = date(2012, 1, 1)
    
    # jsonify using the built in rules
    result1 = encode(dict(date=d1))
    assert '"1979-10-12"' in result1
    result2 = encode(dict(date=d2))
    assert '"2000-01-01"' in result2
    result3 = encode(dict(date=d3))
    assert '"2012-01-01"' in result3
    
    # create a custom rule
    @jsonify.when_type(date)
    def jsonify_date(obj):
        if obj.year == 1979 and obj.month == 10 and obj.day == 12:
            return "Jon's Birthday!"
        elif obj.year == 2000 and obj.month == 1 and obj.day == 1:
            return "Its Y2K! Panic!"
        return '%d/%d/%d' % (obj.month, obj.day, obj.year)
    
    # jsonify using the built in rules
    result1 = encode(dict(date=d1))
    assert '"Jon\'s Birthday!"' in result1
    result2 = encode(dict(date=d2))
    assert '"Its Y2K! Panic!"' in result2
    result3 = encode(dict(date=d3))
    assert  '"1/1/2012"' in result3
Beispiel #38
0
def test_builtin_override():
    # skip this test if simplegeneric is not installed
    try:
        import simplegeneric
    except ImportError:
        return

    # create a few date objects
    d1 = date(1979, 10, 12)
    d2 = date(2000, 1, 1)
    d3 = date(2012, 1, 1)

    # jsonify using the built in rules
    result1 = encode(dict(date=d1))
    assert '"1979-10-12"' in result1
    result2 = encode(dict(date=d2))
    assert '"2000-01-01"' in result2
    result3 = encode(dict(date=d3))
    assert '"2012-01-01"' in result3

    # create a custom rule
    @jsonify.when_type(date)
    def jsonify_date(obj):
        if obj.year == 1979 and obj.month == 10 and obj.day == 12:
            return "Jon's Birthday!"
        elif obj.year == 2000 and obj.month == 1 and obj.day == 1:
            return "Its Y2K! Panic!"
        return '%d/%d/%d' % (obj.month, obj.day, obj.year)

    # jsonify using the built in rules
    result1 = encode(dict(date=d1))
    assert '"Jon\'s Birthday!"' in result1
    result2 = encode(dict(date=d2))
    assert '"Its Y2K! Panic!"' in result2
    result3 = encode(dict(date=d3))
    assert '"1/1/2012"' in result3
Beispiel #39
0
def test_dictionary():
    d = {'a': 1, 'b': 2}
    encoded = jsonify.encode(d)
    expected = json.dumps(json.loads('{"a": 1, "b": 2}'))
    assert encoded == expected
Beispiel #40
0
def test_json_encode_generators():
    encoded = jsonify.encode({'values': (v for v in [1, 2, 3])})
    assert encoded == '{"values": [1, 2, 3]}', encoded
Beispiel #41
0
def test_string():
    d = "string"
    encoded = jsonify.encode(d)
    assert encoded == '"string"'
Beispiel #42
0
def test_list():
    d = ['a', 1, 'b', 2]
    encoded = jsonify.encode(d)
    assert encoded == '["a", 1, "b", 2]'
Beispiel #43
0
def test_string():
    d = "string"
    encoded = jsonify.encode(d)
    assert encoded == '"string"'
Beispiel #44
0
def test_list_iter():
    d = list(range(3))
    encoded = jsonify.encode_iter(d)
    assert ''.join(jsonify.encode_iter(d)) == jsonify.encode(d)
Beispiel #45
0
def test_exlicitjson():
    b = Bar("bq")
    encoded = jsonify.encode(b)
    assert encoded == '"bar-bq"'
Beispiel #46
0
def test_datetime():
    d = datetime.utcnow()
    encoded = jsonify.encode({'date': d})
    assert str(d.year) in encoded, (str(d), encoded)
Beispiel #47
0
def test_exlicitjson_in_dict():
    b = Bar("bq")
    d = {"b": b}
    encoded = jsonify.encode(d)
    assert encoded == '{"b": "bar-bq"}'
Beispiel #48
0
def test_datetime():
    d = datetime.utcnow()
    encoded = jsonify.encode({'date':d})
    assert str(d.year) in encoded, (str(d), encoded)
Beispiel #49
0
def test_list_iter():
    d = list(range(3))
    encoded = jsonify.encode_iter(d)
    assert ''.join(jsonify.encode_iter(d)) == jsonify.encode(d)
Beispiel #50
0
def test_dictionary():
    d = {'a': 1, 'b': 2}
    encoded = jsonify.encode(d)
    expected = json.dumps(json.loads('{"a": 1, "b": 2}'))
    assert encoded == expected
Beispiel #51
0
Datei: json.py Projekt: Cito/tg2
 def render_json(template_name, template_vars, **kwargs):
     return encode(template_vars)
Beispiel #52
0
def test_decimal():
    d = Decimal('3.14')
    encoded = jsonify.encode({'dec': d})
    assert '3.14' in encoded
Beispiel #53
0
def test_list():
    d = ['a', 1, 'b', 2]
    encoded = jsonify.encode(d)
    assert encoded == '["a", 1, "b", 2]'
Beispiel #54
0
def test_exlicitjson_in_list():
    b = Bar("bq")
    d = [b]
    encoded = jsonify.encode(d)
    assert encoded == '["bar-bq"]'
Beispiel #55
0
def test_list_allowed_iter():
    lists_encoder = jsonify.JSONEncoder(allow_lists=True)
    d = ['a', 1, 'b', 2]
    encoded = jsonify.encode(d, lists_encoder)
    assert encoded == '["a", 1, "b", 2]'
Beispiel #56
0
def test_exlicitjson():
    b = Bar("bq")
    encoded = jsonify.encode(b)
    assert encoded == '"bar-bq"'
Beispiel #57
0
def test_json_encode_generators():
    encoded = jsonify.encode({'values': (v for v in [1, 2, 3])})
    assert encoded == '{"values": [1, 2, 3]}', encoded
Beispiel #58
0
def test_exlicitjson_in_list():
    b = Bar("bq")
    d = [b]
    encoded = jsonify.encode(d)
    assert encoded == '["bar-bq"]'
Beispiel #59
0
def test_exlicitjson_in_dict():
    b = Bar("bq")
    d = {"b": b}
    encoded = jsonify.encode(d)
    assert encoded == '{"b": "bar-bq"}'