Home > Software engineering >  Automated mock that returns for each attribute the attribute name as string
Automated mock that returns for each attribute the attribute name as string

Time:09-29

Is there an existing fixture, or a simple one that can be created, that would return magically for any attribute of this mock object, as a value a string made by the name of the attribute?

foo = AutoAttributeMock()
assert foo.bar == "bar" # True
assert foo.other == "other" # True
assert foo.third != "bar" # False

Thank you!

CodePudding user response:

Well, attribute access is done through __getattr__, so it would be possible to simply do the following:

class AutoAttributeMock:
    def __getattr__(self, name: str) -> str:
        return name

Though I struggle to see a reasonable use case for this.

  • Related