| 1 |
from datetime import datetime, date |
| 2 |
from decimal import Decimal |
| 3 |
from json import loads |
| 4 |
try: |
| 5 |
from sqlalchemy import orm, schema, types |
| 6 |
from sqlalchemy.engine import create_engine |
| 7 |
from sqlalchemy.orm import registry |
| 8 |
except ImportError: |
| 9 |
create_engine = None # noqa |
| 10 |
|
| 11 |
from webtest import TestApp |
| 12 |
from webob.multidict import MultiDict |
| 13 |
|
| 14 |
from pecan.jsonify import jsonify, encode, ResultProxy, RowProxy |
| 15 |
from pecan import Pecan, expose |
| 16 |
from pecan.tests import PecanTestCase |
| 17 |
|
| 18 |
|
| 19 |
def make_person(): |
| 20 |
class Person(object): |
| 21 |
def __init__(self, first_name, last_name): |
| 22 |
self.first_name = first_name |
| 23 |
self.last_name = last_name |
| 24 |
|
| 25 |
@property |
| 26 |
def name(self): |
| 27 |
return '%s %s' % (self.first_name, self.last_name) |
| 28 |
return Person |
| 29 |
|
| 30 |
|
| 31 |
def test_simple_rule(): |
| 32 |
Person = make_person() |
| 33 |
|
| 34 |
# create a Person instance |
| 35 |
p = Person('Jonathan', 'LaCour') |
| 36 |
|
| 37 |
# register a generic JSON rule |
| 38 |
@jsonify.when_type(Person) |
| 39 |
def jsonify_person(obj): |
| 40 |
return dict( |
| 41 |
name=obj.name |
| 42 |
) |
| 43 |
|
| 44 |
# encode the object using our new rule |
| 45 |
result = loads(encode(p)) |
| 46 |
assert result['name'] == 'Jonathan LaCour' |
| 47 |
assert len(result) == 1 |
| 48 |
|
| 49 |
|
| 50 |
class TestJsonify(PecanTestCase): |
| 51 |
|
| 52 |
def test_simple_jsonify(self): |
| 53 |
Person = make_person() |
| 54 |
|
| 55 |
# register a generic JSON rule |
| 56 |
@jsonify.when_type(Person) |
| 57 |
def jsonify_person(obj): |
| 58 |
return dict( |
| 59 |
name=obj.name |
| 60 |
) |
| 61 |
|
| 62 |
class RootController(object): |
| 63 |
@expose('json') |
| 64 |
def index(self): |
| 65 |
# create a Person instance |
| 66 |
p = Person('Jonathan', 'LaCour') |
| 67 |
return p |
| 68 |
|
| 69 |
app = TestApp(Pecan(RootController())) |
| 70 |
|
| 71 |
r = app.get('/') |
| 72 |
assert r.status_int == 200 |
| 73 |
assert loads(r.body.decode()) == {'name': 'Jonathan LaCour'} |
| 74 |
|
| 75 |
|
| 76 |
class TestJsonifyGenericEncoder(PecanTestCase): |
| 77 |
def test_json_callable(self): |
| 78 |
class JsonCallable(object): |
| 79 |
def __init__(self, arg): |
| 80 |
self.arg = arg |
| 81 |
|
| 82 |
def __json__(self): |
| 83 |
return {"arg": self.arg} |
| 84 |
|
| 85 |
result = encode(JsonCallable('foo')) |
| 86 |
assert loads(result) == {'arg': 'foo'} |
| 87 |
|
| 88 |
def test_datetime(self): |
| 89 |
today = date.today() |
| 90 |
now = datetime.now() |
| 91 |
|
| 92 |
result = encode(today) |
| 93 |
assert loads(result) == str(today) |
| 94 |
|
| 95 |
result = encode(now) |
| 96 |
assert loads(result) == str(now) |
| 97 |
|
| 98 |
def test_decimal(self): |
| 99 |
# XXX Testing for float match which is inexact |
| 100 |
|
| 101 |
d = Decimal('1.1') |
| 102 |
result = encode(d) |
| 103 |
assert loads(result) == float(d) |
| 104 |
|
| 105 |
def test_multidict(self): |
| 106 |
md = MultiDict() |
| 107 |
md.add('arg', 'foo') |
| 108 |
md.add('arg', 'bar') |
| 109 |
result = encode(md) |
| 110 |
assert loads(result) == {'arg': ['foo', 'bar']} |
| 111 |
|
| 112 |
def test_fallback_to_builtin_encoder(self): |
| 113 |
class Foo(object): |
| 114 |
pass |
| 115 |
|
| 116 |
self.assertRaises(TypeError, encode, Foo()) |
| 117 |
|
| 118 |
|
| 119 |
class TestJsonifySQLAlchemyGenericEncoder(PecanTestCase): |
| 120 |
|
| 121 |
def setUp(self): |
| 122 |
super(TestJsonifySQLAlchemyGenericEncoder, self).setUp() |
| 123 |
if not create_engine: |
| 124 |
self.create_fake_proxies() |
| 125 |
else: |
| 126 |
self.create_sa_proxies() |
| 127 |
|
| 128 |
def create_fake_proxies(self): |
| 129 |
|
| 130 |
# create a fake SA object |
| 131 |
class FakeSAObject(object): |
| 132 |
def __init__(self): |
| 133 |
self._sa_class_manager = object() |
| 134 |
self._sa_instance_state = 'awesome' |
| 135 |
self.id = 1 |
| 136 |
self.first_name = 'Jonathan' |
| 137 |
self.last_name = 'LaCour' |
| 138 |
|
| 139 |
# create a fake result proxy |
| 140 |
class FakeResultProxy(ResultProxy): |
| 141 |
def __init__(self): |
| 142 |
self.rowcount = -1 |
| 143 |
self.rows = [] |
| 144 |
|
| 145 |
def __iter__(self): |
| 146 |
return iter(self.rows) |
| 147 |
|
| 148 |
def append(self, row): |
| 149 |
self.rows.append(row) |
| 150 |
|
| 151 |
# create a fake row proxy |
| 152 |
class FakeRowProxy(RowProxy): |
| 153 |
def __init__(self, arg=None): |
| 154 |
self.row = dict(arg) |
| 155 |
|
| 156 |
def __getitem__(self, key): |
| 157 |
return self.row.__getitem__(key) |
| 158 |
|
| 159 |
def keys(self): |
| 160 |
return self.row.keys() |
| 161 |
|
| 162 |
# get the SA objects |
| 163 |
self.sa_object = FakeSAObject() |
| 164 |
self.result_proxy = FakeResultProxy() |
| 165 |
self.result_proxy.append( |
| 166 |
FakeRowProxy([ |
| 167 |
('id', 1), |
| 168 |
('first_name', 'Jonathan'), |
| 169 |
('last_name', 'LaCour') |
| 170 |
]) |
| 171 |
) |
| 172 |
self.result_proxy.append( |
| 173 |
FakeRowProxy([ |
| 174 |
('id', 2), ('first_name', 'Ryan'), ('last_name', 'Petrello') |
| 175 |
])) |
| 176 |
self.row_proxy = FakeRowProxy([ |
| 177 |
('id', 1), ('first_name', 'Jonathan'), ('last_name', 'LaCour') |
| 178 |
]) |
| 179 |
|
| 180 |
def create_sa_proxies(self): |
| 181 |
|
| 182 |
# create the table and mapper |
| 183 |
mapper_registry = registry() |
| 184 |
metadata = schema.MetaData() |
| 185 |
user_table = schema.Table( |
| 186 |
'user', |
| 187 |
metadata, |
| 188 |
schema.Column('id', types.Integer, primary_key=True), |
| 189 |
schema.Column('first_name', types.Unicode(25)), |
| 190 |
schema.Column('last_name', types.Unicode(25)) |
| 191 |
) |
| 192 |
|
| 193 |
class User(object): |
| 194 |
pass |
| 195 |
mapper_registry.map_imperatively(User, user_table) |
| 196 |
|
| 197 |
# create the session |
| 198 |
engine = create_engine('sqlite:///:memory:') |
| 199 |
metadata.bind = engine |
| 200 |
metadata.create_all(metadata.bind) |
| 201 |
session = orm.sessionmaker(bind=engine)() |
| 202 |
|
| 203 |
# add some dummy data |
| 204 |
session.add(User(first_name='Jonathan', last_name='LaCour')) |
| 205 |
session.add(User(first_name='Ryan', last_name='Petrello')) |
| 206 |
session.commit() |
| 207 |
|
| 208 |
# get the SA objects |
| 209 |
self.sa_object = session.query(User).first() |
| 210 |
select = user_table.select() |
| 211 |
self.result_proxy = session.execute(select) |
| 212 |
self.row_proxy = session.execute(select).fetchone() |
| 213 |
|
| 214 |
def test_sa_object(self): |
| 215 |
result = encode(self.sa_object) |
| 216 |
assert loads(result) == { |
| 217 |
'id': 1, 'first_name': 'Jonathan', 'last_name': 'LaCour' |
| 218 |
} |
| 219 |
|
| 220 |
def test_result_proxy(self): |
| 221 |
result = encode(self.result_proxy) |
| 222 |
assert loads(result) == {'count': 2, 'rows': [ |
| 223 |
{'id': 1, 'first_name': 'Jonathan', 'last_name': 'LaCour'}, |
| 224 |
{'id': 2, 'first_name': 'Ryan', 'last_name': 'Petrello'} |
| 225 |
]} |
| 226 |
|
| 227 |
def test_row_proxy(self): |
| 228 |
result = encode(self.row_proxy) |
| 229 |
assert loads(result) == { |
| 230 |
'id': 1, 'first_name': 'Jonathan', 'last_name': 'LaCour' |
| 231 |
} |