Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Mock
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Dan Langer
March 14, 2012
Technology
1
2.8k
Mock
Created for the Django Toronto meetup, a quick tour through the Python mock package.
Dan Langer
March 14, 2012
Tweet
Share
More Decks by Dan Langer
See All by Dan Langer
A Scenic Drive through the Django Request-Response Cycle
dlanger
1
1.4k
Other Decks in Technology
See All in Technology
AI時代のSaaSとETL
shoe116
1
180
ソフトバンク流!プラットフォームエンジニアリング実現へのアプローチ
sbtechnight
1
180
JAWSDAYS2026_A-6_現場SEが語る 回せるセキュリティ運用~設計で可視化、AIで加速する「楽に回る」運用設計のコツ~
shoki_hata
0
3k
Agent ServerはWeb Serverではない。ADKで考えるAgentOps
akiratameto
0
110
Lambda Web AdapterでLambdaをWEBフレームワーク利用する
sahou909
0
160
VLAモデル構築のための AIロボット向け模倣学習キット
kmatsuiugo
0
230
OSC仙台プレ勉強会 AlmaLinuxとは
koedoyoshida
0
180
脳内メモリ、思ったより揮発性だった
koutorino
0
370
OCHaCafe S11 #2 コンテナ時代の次の一手:Wasm 最前線
oracle4engineer
PRO
2
140
DevOpsエージェントで実現する!! AWS Well-Architected(W-A) を実現するシステム設計 / 20260307 Masaki Okuda
shift_evolve
PRO
3
910
(Test) ai-meetup slide creation
oikon48
3
430
Oracle Cloud Infrastructure IaaS 新機能アップデート 2025/12 - 2026/2
oracle4engineer
PRO
0
150
Featured
See All Featured
Speed Design
sergeychernyshev
33
1.6k
How STYLIGHT went responsive
nonsquared
100
6k
Mozcon NYC 2025: Stop Losing SEO Traffic
samtorres
0
180
KATA
mclloyd
PRO
35
15k
The Web Performance Landscape in 2024 [PerfNow 2024]
tammyeverts
12
1.1k
Why Mistakes Are the Best Teachers: Turning Failure into a Pathway for Growth
auna
0
83
ラッコキーワード サービス紹介資料
rakko
1
2.7M
YesSQL, Process and Tooling at Scale
rocio
174
15k
WENDY [Excerpt]
tessaabrams
9
36k
Navigating the Design Leadership Dip - Product Design Week Design Leaders+ Conference 2024
apolaine
0
230
世界の人気アプリ100個を分析して見えたペイウォール設計の心得
akihiro_kokubo
PRO
67
37k
Navigating Weather and Climate Data
rabernat
0
140
Transcript
mock==0.8.0
Who am I? Dan Langer @dlanger
[email protected]
daniel.langer.me
None
None
>> import mock >> dir(mock) ['Mock', 'patch', ...]
>> from mock import Mock
Mocks all the way down >> k = Mock() >>
k.foo.bar <Mock name="mock.foo.bar id=124> >> k.foo.bar() <Mock name="mock.foo.bar() id=128> >> k.foo.bar <Mock name="mock.foo.bar id=124> >> k.a.b.c.d.e.f.g.h.i.j.k.l.m <Mock name="..." id=1365>
Configure your mocks >> from django.contrib.auth.models import User >> user1_mock
= Mock() >> user1_mock.foo <Mock name=...> >> user2_mock = Mock(spec=User) >> user2_mock.foo AttributeError: ...
Configure your mocks >> rmock = Mock(return_value=5) >> rmock(), rmock(4),
rmock("W") (5, 5, 5) >> smock = Mock(side_effect=[1,2]) >> smock(), smock() (1, 2) >> emock = Mock(side_effect=Exception) >> emock() Exception: ...
Inspect your mocks >> imock = Mock(return_value=None) >> imock() >>
imock.call_count 1 >> imock(1, 2, 3, demo="ok") >> imock.call_args_list [call(1), call(1,2,3,demo='ok')]
>> from mock import patch
Daniel Coomber
Patch all the things # utils.py def load_token(user) r =
StrictRedis(host=...) [...] raw_token = r.rpop(token_id) return '--'.join([raw_token, ...]) # tests.py def test_load_token(self): redis_mock = Mock() redis_mock.return_value.rpop \ .return_value = 'TEST_TOKEN' with patch('utils.StrictRedis', redis_mock): load_token(self.test_user) self.assertEqual(...)
Patch celery # tasks.py @task def process_chunk(chunk): pass @task def
process_file(file): tasks = [] for ... st = process_chunk.subtask(chunk) tasks.append(st) process = TaskSet(tasks=tasks) process.apply_async()
Patch celery # tests.py def test_process_file__two_subtasks(self): pc_mock = Mock() with
patch('tasks.process_chunk', pc_mock): process_file.delay(...) self.assertEqual(pc_mock.call_count, 2) #Fails
Patch celery # tests.py def test_process_file__two_subtasks(self): pc_mock = Mock() with
patch('tasks.process_chunk.subtask', pc_mock): process_file.delay(...) self.assertEqual(pc_mock.call_count, 2)
Patch built-ins # utils.py import message_defs def load_defaults(id) if getattr(message_defs,
id, None): [...] # tests.py def test_load_defaults(self): with patch('__builtins__.getattr', return_value='Hi'): load_defaults('welcome') self.assertEqual(...)
Patch built-ins # utils.py import message_defs def load_defaults(id) if getattr(message_defs,
id, None): [...] # tests.py def test_load_defaults(self): with patch('utils.getattr', create=True, return_value='Hi'): load_defaults('welcome') self.assertEqual(...)
Patch Django def test_template: mock_get_template = Mock( return_value=Template("Hi {{ username
}}")) with patch('package.module.get_template', mock_get_template): [...] def test_verify_user(self): mock_get = Mock() mock_get.return_value = Mock(spec=User) with patch('utils.User.objects.get', mock_get): [...]
Patch the ORM...sparingly # User.objects.filter(...).exclude(...) \ # .order_by(...) def test_user_filter(self):
mock_filter = Mock() mock_filter.return_value.exclude \ .return_value.order_by.return_value = [...] with patch('utils.User.objects.filter', mock_filter): [...]
Keep Reading @decorator syntax create_autospec MagicMock [...] http://www.voidspace.org. uk/python/mock/