Skip to content

Change the representation of Pydantic models to enable the use of dirty_equals. #343

Description

@15r10nk

Implement a custom matcher which can be used to represent pydantic models.

features:

  • Model can be refactored and attributes can be added/removed. The tests will fail but inline-snapshot can fix them because == returns False.
  • dirty-equals can be used as arguments
  • This new code can be generated by default with the new @customize hook
from pydantic import BaseModel

from inline_snapshot import snapshot

class IsPydantic:
    def __init__(self,typ,/,**attributes):
        self.typ=typ
        self.attributes=attributes

    def __eq__(self,other):
        if type(other) is not self.typ:
            return NotImplemented

        for name,attribute in self.attributes.items():
            if not hasattr(other,name):
                return False
            if not getattr(other,name) == attribute:
                return False

        # todo: we have to check that missing attributes are equal to the default value

        return True

class M(BaseModel):
    x:int
    y:int

def test_is_pydantic():

    # old style
    assert M(x=1,y=2) == snapshot(M(x=1,y=2))

    # proposed new style
    assert M(x=1,y=2) == snapshot(IsPydantic(M,x=1,y=2))

    # can handle invalid arguments (return False and raise no exception)
    assert M(x=1,y=2) == snapshot(IsPydantic(M,x=1,y=2,invalid=5))

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions