Is there a way to automatically mock Python classes completely with methods using type hints?

Viewed 25

I am writing a program which interacts with many external services such as Gmail and Discord through their respective SDKs. The problem I am running into is that the program makes a lot of network calls and runs expensive computations in development I would rather avoid with stub objects. The SDKs I am using expose their functionality through standard Python classes with type hints. At the moment, I am creating stubs for them manually but it would not be feasible in the long run.

For example, this is a simplified example to illustrate what I am trying to achieve.

@dataclass
class EmailReceipt:
receiver_email_address:str
email_text:str
...

class GmailService:
...

    def send_email(receiver_email:str)->EmailReceipt:
    "A network call is made to send email address here"

# More methods follow
    
...

class GmailServiceStub:

    def send_email((receiver_email:str))->>EmailReceipt:
    "The code instantiates a random object of class EmailReceipt and returns it"

# More stub methods follow

In development I would like to avoid making a request to the mail server, so I am creating a mock class. The codebase uses dependency injection throughout so it is trivial to swap different versions of GmailService class. I am using mocked versions of external servives for rapid development but I think it could also be used for testing.

All I am doing here is just implementing the contract, that send_email method returns an instance of EmailReceipt disregarding any domain logic so that it can be used downstream by other classes. At the moment, it is just 2 services with 10 methods in total but it is growing and I would rather have a tool or a library generate it for me.

So I am wondering if there is a tool or a library which could do it or something close to it, ideally with this interface.

mocked_service=mocker.mock_class(service)
# All methods of mocked_service return appropriate objects/types which can be used downstream.

If it is not possible in Python, are there other programming languages where this would be possible?

0 Answers
Related