示例#1
0
def write_then_read(obj):
    with TemporaryDirectory() as tmpdir:
        tmpfile = pathlib.Path(tmpdir) / "output.json"

        with open(tmpfile, "w") as fp:
            sd_ujson.dump(obj, fp)

        with open(tmpfile, "r") as fp:
            return sd_ujson.load(fp)
示例#2
0
def test_custom_class():
    # 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.
    @sd_ujson.encoders.register(Character)
    def encode_character(obj):
        return dict(obj)

    @sd_ujson.encoders.register(Cheese)
    def encode_cheese(obj):
        return dict(obj)

    @sd_ujson.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", "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 TemporaryDirectory() as tmpdir:
        tmpfile = pathlib.Path(tmpdir) / "output.json"

        with open(tmpfile, "w") as fp:
            sd_ujson.dump(cheese_shop, fp)

        with open(tmpfile, "r") as fp:
            assert fp.read() == nospace(expected_json)

    assert sd_ujson.dumps(cheese_shop) == nospace(expected_json)

    # Cleanup
    sd_ujson.unregister_encoder(Character)
    sd_ujson.unregister_encoder(Cheese)
    sd_ujson.unregister_encoder(Shop)
示例#3
0
def test_dump_to_file_like_object():
    class FileLike:
        def __init__(self):
            self.bytes = ""

        def write(self, bytes):
            self.bytes += bytes

    f = FileLike()
    sd_ujson.dump([1, 2, 3], f)
    assert "[1,2,3]" == f.bytes
示例#4
0
def test_dump_file_args_error():
    with pytest.raises(AttributeError):
        sd_ujson.dump([], "")
示例#5
0
def test_dump_to_file():
    f = six.StringIO()
    sd_ujson.dump([1, 2, 3], f)
    assert "[1,2,3]" == f.getvalue()