def test_encode(): item = Item(item='word', start=12, end=23) itemdict = item._asdict() line = json.dumps(itemdict) line_formatted = json.dumps(itemdict, indent=2) assert item.json() == line assert item.json(indent=2) == line_formatted buffer = io.StringIO() Schema.dump(Schema([item]), buffer) assert ('[%s]' % (item.json(), )) == buffer.getvalue() buffer = io.StringIO() Schema([item]).dump(buffer) assert ('[%s]' % (item.json(), )) == buffer.getvalue() schema = Schema() schema.append(item) schema.append(item) assert len(schema) is 2 assert schema.json() == '[%s, %s]' % ((line, ) * 2) assert schema.json(indent=2) == '[\n%s,\n%s\n]' % ( (textwrap.indent(line_formatted, ' '), ) * 2) assert repr(schema) == ('Schema(%s)' % (schema.json())) class T: ok = False with raises(TypeError) as exc: assert json.dumps(T(), cls=JSONEncoder) assert "is not JSON serializable" in str(exc)
def test_roundtrip(): schema = Schema() testlen = 1 for i in range(testlen): schema.append( dict(item=random_str(), start=randint(0, 1e10), end=randint(0, 1e10))) schema.append( Item( OrderedDict(item=random_str(), start=randint(0, 1e10), end=randint(0, 1e10)))) schema.extend(list(schema)) assert len(schema) == testlen * 4 for item in schema: assert type(item) is Item json_ = schema.json() assert Schema.loads(json_) == schema schema = Schema.loads(json_) for item in schema: assert type(item) is Item