syrupy icon indicating copy to clipboard operation
syrupy copied to clipboard

JSONSnapshotExtension None is serialized as "None" instead of null

Open willhoyle opened this issue 2 years ago • 1 comments

Is it intended behaviour that None is not translated to null with the JSONSnapshotExtension?

@pytest.fixture
def snapshot_json(snapshot):
    return snapshot.use_extension(JSONSnapshotExtension)

def test_output(snapshot_json):
    assert {"x": None} == snapshot_json()

Actual Output:

{
    "x": "None"
}

Expected Output:

{
    "x": null
}

Digging into the code, it looks like there's no handling of None in _filter, and it eventually reaches return repr(None) line.

I can wrap the existing class with the following code:

import pytest
from syrupy.extensions.json import JSONSnapshotExtension

@pytest.fixture
def snapshot_json(snapshot):
    class CustomJSONExtension(JSONSnapshotExtension):
        @classmethod
        def _filter(
            cls,
            data,
            **kwargs
        ):
            if data is None:
                return data
            else:
                return super()._filter(data, **kwargs)

    return snapshot.use_extension(CustomJSONExtension)

Was wondering if there's a different way to get this behaviour?

willhoyle avatar Sep 25 '22 00:09 willhoyle

I think this was overlooked when the serializer was introduced. I agree with you that null makes sense for the None type.

Since this is a change to serialization, it'd be a breaking change, so we can add this to the next breaking change release, which is the v4 release.

If you're interested in putting up a PR, it'd be against the "next" branch.

noahnu avatar Sep 25 '22 00:09 noahnu

:tada: This issue has been resolved in version 4.0.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket:

tophat-opensource-bot avatar Feb 02 '23 20:02 tophat-opensource-bot