Exemple #1
0
def test_to_json():
    a = OrderedDict()
    a['name'] = "Monkey D. Luffy"
    a['birthday'] = datetime.datetime(2015, 7, 19, 9, 14, 22, 140921)
    a['level'] = 90
    a['length'] = Decimal('177.85')
    a['parents'] = OrderedDict()
    a['parents']["father"] = dict(name="Monkey D. Dragon")
    a['parents']["mother"] = dict(name="Unknown")

    class FakeDict(object):
        def to_dict(self):
            return a

    expected_json = """
{
    "name": "Monkey D. Luffy",
    "birthday": "2015-07-19T09:14:22.140921",
    "level": 90,
    "length": "177.85",
    "parents": {
        "father": {
            "name": "Monkey D. Dragon"
        },
        "mother": {
            "name": "Unknown"
        }
    }
}
""".strip()

    expected_json_3_6 = """
{
    "name": "Monkey D. Luffy",
    "birthday": "2015-07-19T09:14:22.140921",
    "level": 90,
    "length": 177.85,
    "parents": {
        "father": {
            "name": "Monkey D. Dragon"
        },
        "mother": {
            "name": "Unknown"
        }
    }
}
""".strip()

    assert to_json(a) == expected_json
    assert to_json(FakeDict()) == expected_json

    with assert_raises(TypeError, "<SimpleObject> is not JSON serializable"):
        class SimpleObject(object):
            def __repr__(self):
                return "<SimpleObject>"
        if sys.version_info >= (3,6):
            assert to_json(SimpleObject()) == expected_json_3_6
        else:
            assert to_json(SimpleObject()) == expected_json
Exemple #2
0
def test_db_api_to_dict_json(db):
    db.create_all()
    db.reflect()
    Actor, Movie = db['Actor'], db['Movie']
    dt = datetime.datetime(2015, 7, 19, 9, 14, 22, 140921)
    a1 = Actor.create(firstname="Leonardo", lastname="DiCaprio", birthday=dt)
    a2 = Actor.create(firstname="Mark", lastname="Ruffalo")
    m1 = Movie.create(title="Shutter Island")
    m1.actors.append(a1)
    m1.actors.append(a2)

    item = Actor.query.filter_by(firstname="Leonardo").first()
    item_dict = OrderedDict([('id', 1),
                             ('firstname', 'Leonardo'),
                             ('lastname', 'DiCaprio'),
                             ('birthday', dt)])
    assert item.to_dict() == item_dict
    expected_json = """
{
    "id": 1,
    "firstname": "Leonardo",
    "lastname": "DiCaprio",
    "birthday": "2015-07-19T09:14:22.140921"
}""".strip()
    assert item.to_json() == expected_json
    assert to_json(item) == expected_json