kaste / mockito-python

Mockito is a spying framework
MIT License
123 stars 12 forks source link

Support one liner stubs? #39

Closed dhulke closed 3 years ago

dhulke commented 3 years ago

Today I was trying to create a stub "factory" for requests.Response that supported the json() method and came up with the following snippet:

def jsonResponse(json):
    response = mock()
    when(response).json().thenReturn(json)
    return response

And I thought that it would have been much easier if I could do:

lambda json: when(response).json().thenReturn(json).mock()

I came up with a one liner but I had to dig into the code and it's undocumented territory:

lambda json: when(mock()).json().thenReturn(json).invocation.mock.mocked_obj

Would a method like mock() to return the original mocked obj be a feature aligned with the project?

kaste commented 3 years ago

This specific use case is actually in the docs https://mockito-python.readthedocs.io/en/latest/the-functions.html for the mock function. You basically pass a dict to the mock() function.

That should work nicely here, wdyt?

dhulke commented 3 years ago

I disregarded that part of the documentation when I saw the dict thinking you couldn't stub a method with it, but it makes total sense now that I see it. Pure beauty.

lambda json: mock({'json': lambda: json})

Thank you sir!

kaste commented 3 years ago

👍✌️