tophat / syrupy

:pancakes: The sweeter pytest snapshot plugin
https://tophat.github.io/syrupy
Apache License 2.0
501 stars 33 forks source link

More generic serialization of function types #808

Closed ManiacDC closed 9 months ago

ManiacDC commented 10 months ago

Is your feature request related to a problem? Please describe.

When trying to compare snapshots with attributes that contain functions, the function repr is returned as <function request_response.<locals>.app at 0x7fbf103dc0e0>

The "at 0x..." part changes with each run of the test, I'm assuming it's a memory location.

Describe the solution you'd like

I'd like the at 0x... part to be removed.

Describe alternatives you've considered

I've worked around this using a matcher:

    def function_matcher(data, path):
        if isinstance(data, FunctionType):
            return f"<function '{data.__qualname__}'>"
        else:
            return data

Additional context

This could be implemented in the ambr and json snapshot extensions.

In ambr (serializer.py):

...
        elif isinstance(data, FunctionType):
            serialize_method = cls.serialize_function
...

    @classmethod
    def serialize_function(cls, data: FunctionType, *, depth: int = 0, **kwargs: Any) -> str:
        return cls.__serialize_plain(data=f"<{FunctionType.__name__} {data.__qualname__}>", depth=depth)

In json:

        if isinstance(data, FunctionType):
            return f"<{FunctionType.__name__} '{data.__qualname__}'>"
noahnu commented 10 months ago

<...> is the old amber syntax and didn't support syntax highlighting too well.

In the latest version of syrupy, classes are serialized as MyClass(...). We can probably do something similar for functions.

Would you be interested in opening a PR and contributing?

ManiacDC commented 10 months ago

Sure, I'll try to get to that soon.

ManiacDC commented 9 months ago

@noahnu sorry for the delay, I've opened a PR to address this issue.

tophat-opensource-bot commented 9 months ago

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

The release is available on:

Your semantic-release bot :package::rocket: