Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Speaker Deck
PRO
Sign in
Sign up for free
Mock
Dan Langer
March 14, 2012
Technology
1
2.4k
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
ITエンジニアを取り巻く環境とキャリアパス / A career path for Japanese IT engineers
takatama
0
600
Oracle Database Technology Night #55 Oracle Autonomous Database 再入門
oracle4engineer
PRO
1
140
アルプの 認証/認可分離戦略と手法
ma2k8
PRO
2
360
0->1 フェーズで E2E 自動テストを導入した私たちの、これまでとこれから
yoyakoba
0
790
我々はなぜテストをするのか?
kawaguti
PRO
0
590
tfcon-2022-cpp
cpp
5
5.2k
Kubernetesの上に作る、統一されたマイクロサービス運用体験
tkuchiki
1
1.3k
LINE WORKS API 2.0について
mmclsntr
0
140
Oracle Cloud Infrastructure:2022年5月度サービス・アップデート
oracle4engineer
PRO
0
140
キャッチアップ Android 13 / Catch up Android 13
yanzm
2
1.2k
LINEポイントクラブにおける PerlからKotlinへの移行を振り返る / The migration from Perl to Kotlin at LINE Point Club
line_developers
PRO
0
150
Server-side Kotlin in LINE Messaging API
line_developers
PRO
0
160
Featured
See All Featured
From Idea to $5000 a Month in 5 Months
shpigford
372
44k
How to train your dragon (web standard)
notwaldorf
57
3.8k
Thoughts on Productivity
jonyablonski
43
2.2k
Optimizing for Happiness
mojombo
365
63k
Embracing the Ebb and Flow
colly
73
3.3k
Mobile First: as difficult as doing things right
swwweet
212
7.5k
Unsuck your backbone
ammeep
659
55k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
19
1.4k
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
29
4.3k
WebSockets: Embracing the real-time Web
robhawkes
57
5k
Automating Front-end Workflow
addyosmani
1351
200k
ReactJS: Keep Simple. Everything can be a component!
pedronauck
655
120k
Transcript
mock==0.8.0
Who am I? Dan Langer @dlanger daniel@langer.me 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/