| 1 |
.. module:: mockito |
| 2 |
|
| 3 |
|
| 4 |
Recipes |
| 5 |
======= |
| 6 |
|
| 7 |
|
| 8 |
Classes as factories |
| 9 |
-------------------- |
| 10 |
|
| 11 |
We want to test the following code:: |
| 12 |
|
| 13 |
import requests |
| 14 |
|
| 15 |
def fetch(url): |
| 16 |
session = requests.Session() |
| 17 |
return session.get(url) |
| 18 |
|
| 19 |
In a traditional sense this code is not designed for *testability*. But we don't care here. |
| 20 |
|
| 21 |
Python has no `new` keyword to get fresh instances from classes. Man, that was a good decision, Guido! So the uppercase `S` in `requests.Session()` doesn't have to stop us in any way. It looks like a function call, and we treat it like such: The plan is to replace `Session` with a factory function that returns a (mocked) session:: |
| 22 |
|
| 23 |
from mockito import when, mock, verifyStubbedInvocationsAreUsed |
| 24 |
|
| 25 |
def test_fetch(unstub): |
| 26 |
url = 'http://example.com/' |
| 27 |
response = mock({'text': 'Ok'}, spec=requests.Response) |
| 28 |
# remember: `mock` here just creates an empty object specced after |
| 29 |
# requests.Session |
| 30 |
session = mock(requests.Session) |
| 31 |
# `when` here configures the mock |
| 32 |
when(session).get(url).thenReturn(response) |
| 33 |
# `when` *patches* the globally available *requests* module |
| 34 |
when(requests).Session().thenReturn(session) # <= |
| 35 |
|
| 36 |
res = fetch(url) |
| 37 |
assert res.text == 'Ok' |
| 38 |
|
| 39 |
# no need to verify anything here, if we get the expected response |
| 40 |
# back, `url` must have been passed through the system, otherwise |
| 41 |
# mockito would have thrown. |
| 42 |
# We *could* ensure that our mocks are actually used, if we want: |
| 43 |
verifyStubbedInvocationsAreUsed() |
| 44 |
|
| 45 |
|
| 46 |
Faking magic methods |
| 47 |
-------------------- |
| 48 |
|
| 49 |
We want to test the following code:: |
| 50 |
|
| 51 |
import requests |
| 52 |
|
| 53 |
def fetch_2(url): |
| 54 |
with requests.Session() as session: |
| 55 |
return session.get(url) |
| 56 |
|
| 57 |
It's basically the same problem, but we need to add support for the context manager, the `with` interface:: |
| 58 |
|
| 59 |
from mockito import when, mock, args |
| 60 |
|
| 61 |
def test_fetch_with(unstub): |
| 62 |
url = 'http://example.com/' |
| 63 |
response = mock({'text': 'Ok'}, spec=requests.Response) |
| 64 |
|
| 65 |
session = mock(requests.Session) |
| 66 |
when(session).get(url).thenReturn(response) |
| 67 |
when(session).__enter__().thenReturn(session) # <= |
| 68 |
when(session).__exit__(*args) # <= |
| 69 |
|
| 70 |
when(requests).Session().thenReturn(session) |
| 71 |
|
| 72 |
res = fetch_2(url) |
| 73 |
assert res.text == 'Ok' |
| 74 |
|
| 75 |
|