def check(indent, expected): d1 = sdjson.dumps(h, indent=indent) assert d1 == expected sio = StringIO() sdjson.dump(h, sio, indent=indent) assert sio.getvalue() == expected
def write_then_read(obj, tmpdir: PathPlus): tmpfile = tmpdir / "output.json" with open(tmpfile, 'w', encoding="UTF-8") as fp: sdjson.dump(obj, fp) with open(tmpfile, encoding="UTF-8") as fp: return sdjson.load(fp)
def write_then_read(obj): with TemporaryDirectory() as tmpdir: tmpfile = pathlib.Path(tmpdir) / "output.json" with open(tmpfile, "w") as fp: sdjson.dump(obj, fp) with open(tmpfile, "r") as fp: return sdjson.load(fp)
def test_custom_class() -> None: # Create and register the custom encoders # In this example we create three separate encoders even though all three classes # actually share a common subclass. In real usage they might not be. @sdjson.encoders.register(Character) def encode_character(obj): return dict(obj) @sdjson.encoders.register(Cheese) def encode_cheese(obj): return dict(obj) @sdjson.encoders.register(Shop) def encode_shop(obj): return dict(obj) # Create instances of classes runny_camembert = Cheese("Camembert", ["Very runny"]) shopkeeper = Character("Mr Wensleydale", "Michael Palin") customer = Character("The Customer", "John Cleese") cheese_shop = Shop( "The National Cheese Emporium", address="""12 Some Street Some Town England""", staff=[shopkeeper], customers=[customer], current_stock=[runny_camembert], music=False, dancing=False, ) expected_json = ( '{"name": "The National Cheese Emporium", "address": "12 Some Street\\n' 'Some Town\\nEngland", "is_open": true, "music": false, "dancing": false, ' '"staff": [{"name": "Mr Wensleydale", "actor": "Michael Palin", "armed": false}], ' '"customers": [{"name": "The Customer", "actor": "John Cleese", "armed": false}], ' '"current_stock": [{"name": "Camembert", "properties": ["Very runny"]}]}' ) with TemporaryPathPlus() as tmpdir: tmpfile = tmpdir / "output.json" with open(tmpfile, 'w', encoding="UTF-8") as fp: sdjson.dump(cheese_shop, fp) with open(tmpfile, encoding="UTF-8") as fp: assert fp.read() == expected_json assert sdjson.dumps(cheese_shop) == expected_json # Cleanup sdjson.unregister_encoder(Character) sdjson.unregister_encoder(Cheese) sdjson.unregister_encoder(Shop)
def test_dump() -> None: sio = StringIO() sdjson.dump({}, sio) assert sio.getvalue() == "{}"
def test_dump(): sio = StringIO() sdjson.dump({}, sio) assert sio.getvalue() == '{}'