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
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
Dan Langer
March 14, 2012
Technology
1
2.7k
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
GitHub Issue Templates + Coding Agentで簡単みんなでIaC/Easy IaC for Everyone with GitHub Issue Templates + Coding Agent
aeonpeople
1
200
SREじゃなかった僕らがenablingを通じて「SRE実践者」になるまでのリアル / SRE Kaigi 2026
aeonpeople
6
2.2k
AIと新時代を切り拓く。これからのSREとメルカリIBISの挑戦
0gm
0
870
学生・新卒・ジュニアから目指すSRE
hiroyaonoe
2
580
生成AIを活用した音声文字起こしシステムの2つの構築パターンについて
miu_crescent
PRO
2
170
顧客との商談議事録をみんなで読んで顧客解像度を上げよう
shibayu36
0
210
GitLab Duo Agent Platform × AGENTS.md で実現するSpec-Driven Development / GitLab Duo Agent Platform × AGENTS.md
n11sh1
0
130
ブロックテーマ、WordPress でウェブサイトをつくるということ / 2026.02.07 Gifu WordPress Meetup
torounit
0
170
Bill One 開発エンジニア 紹介資料
sansan33
PRO
4
17k
CDKで始めるTypeScript開発のススメ
tsukuboshi
1
360
GSIが複数キー対応したことで、俺達はいったい何が嬉しいのか?
smt7174
3
150
予期せぬコストの急増を障害のように扱う――「コスト版ポストモーテム」の導入とその後の改善
muziyoshiz
1
1.8k
Featured
See All Featured
Why You Should Never Use an ORM
jnunemaker
PRO
61
9.7k
We Are The Robots
honzajavorek
0
160
Visualization
eitanlees
150
17k
Optimising Largest Contentful Paint
csswizardry
37
3.6k
Mind Mapping
helmedeiros
PRO
0
79
Building Adaptive Systems
keathley
44
2.9k
The AI Search Optimization Roadmap by Aleyda Solis
aleyda
1
5.2k
The Impact of AI in SEO - AI Overviews June 2024 Edition
aleyda
5
730
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
11
820
Into the Great Unknown - MozCon
thekraken
40
2.3k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
31
3.1k
A Modern Web Designer's Workflow
chriscoyier
698
190k
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/