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
Dan Langer
March 14, 2012
Technology
1
2.5k
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.3k
Other Decks in Technology
See All in Technology
AOAI をきっかけに 社内の Azure 管理を見直した話
recruitengineers
PRO
1
270
コンテナセキュリティの基本と脅威への対策
kyohmizu
3
760
JAWS-UG Bedrock Claude Night
yamahiro
3
570
地理空間データ可視化・解析・活用ソリューション Pacific Spatial Solutions (PSS)
pacificspatialsolutions
0
200
ChatworkのSRE部って実は 半分くらいPlatform Engineering部かもしれない
saramune
0
160
Tellus の衛星データを見てみよう #mf_fukuoka
kongmingstrap
0
180
オーナーシップを持つ領域を明確にする
konifar
13
3.1k
Google Cloud Next '24でブログを10本書いた方法と勉強会を沸かせた方法
yasumuusan
0
290
障害対応をちょっとずつよくしていくための 演習の作りかた
heleeen
0
140
ユーザーストーリーのレビューを自動化したみたの
bun913
1
420
Reducing Cross-Zone Egress at Spotify with Custom gRPC Load Balancing Recap
koh_naga
0
200
一生覚えておきたい「システム開発=コミュニケーション」〜初めての実務案件振り返りLT〜
maimyyym
0
130
Featured
See All Featured
Writing Fast Ruby
sferik
621
60k
Navigating Team Friction
lara
178
13k
ParisWeb 2013: Learning to Love: Crash Course in Emotional UX Design
dotmariusz
104
6.6k
Designing the Hi-DPI Web
ddemaree
276
33k
GraphQLとの向き合い方2022年版
quramy
32
12k
Bootstrapping a Software Product
garrettdimon
PRO
302
110k
Art, The Web, and Tiny UX
lynnandtonic
289
19k
Web development in the modern age
philhawksworth
202
10k
jQuery: Nuts, Bolts and Bling
dougneiner
59
7.1k
Documentation Writing (for coders)
carmenintech
60
3.9k
Keith and Marios Guide to Fast Websites
keithpitt
408
22k
Practical Orchestrator
shlominoach
182
9.7k
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/