Agenda
Why isolate dependencies during testing
The scope of patched object
The potential risks of mocking dependencies with mock package
The tricks of MagickMock
Slide 3
Slide 3 text
Why isolate dependencies during testing
The essence of the test
Tragedies while testing without isolation
When should I mock?
Slide 4
Slide 4 text
foo.py test_foo.py
Slide 5
Slide 5 text
foo.py test_foo.py
Function Test
Determines
Reflect
Slide 6
Slide 6 text
foo.py test_foo.py
Execute the logic Check the result
Call
Return
Slide 7
Slide 7 text
No content
Slide 8
Slide 8 text
Sometimes you should not really execute
the logic during the test
Slide 9
Slide 9 text
Otherwise…
Paid for your API calls
Got banned because high-frequency access
Pollute the storage
Execute unrecoverable operations
Slide 10
Slide 10 text
Lab 01
How py
te
st po
ll
u
te
your s
to
rage while unit-
te
s
ti
ng?
Slide 11
Slide 11 text
No content
Slide 12
Slide 12 text
The scope of patched object
Context manager
Function decorator
Class decorator
Construct and destruct manually (not recommend)
Slide 13
Slide 13 text
Lab 02 - 1
Con
te
xt manager
Slide 14
Slide 14 text
Lab 02 - 2
Func
ti
on decora
to
r
Slide 15
Slide 15 text
Lab 02 - 3
Class decora
to
r
Slide 16
Slide 16 text
Construct and Destruct Manually
Slide 17
Slide 17 text
The Potential Risks of Mocking Dependencies
Wrong parameters
Misspelling methods
Slide 18
Slide 18 text
Lab 03 - 1
Th
e unit
te
st was passed accidenta
ll
y (but maybe you
th
ink
th
at it should be like
th
is )
Slide 19
Slide 19 text
Lab 03 - 2
In some cases, mock wi
ll
catch
th
e issues for you
au
to
ma
ti
ca
ll
y
Slide 20
Slide 20 text
Lab 03 - 3
But some
ti
mes it won’t, so we had be
tt
er make
th
e schema of
patched object s
tr
ic
te
r by ourselves
Slide 21
Slide 21 text
The Tricks of MagicMock
Object attributes
Slide 22
Slide 22 text
Lab 04 - 1
Th
e valid a
tt
ribu
te
s of a MagicMock object
Slide 23
Slide 23 text
Lab 04 - 2
Apply
th
e
fi
xed a
tt
ribu
te
s recursively via
th
e au
to
spec kwarg