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
2.8k
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Mock
Created for the Django Toronto meetup, a quick tour through the Python mock package.
Dan Langer
March 14, 2012
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
Building applications in the Gemini API family.
line_developers_tw
PRO
0
3.2k
Oracle AI Database@AWS:サービス概要のご紹介
oracle4engineer
PRO
4
2.9k
エラーバジェットのアラートのタイミングを考える.pdf
kairim0
0
140
RSA暗号を手計算したくなること、ありますよね?? (20260615_orestudy6_rsa)
thousanda
0
340
あなたの知らないPDFのアクセシビリティ
lycorptech_jp
PRO
0
160
SONiC Scale-Up Working Group から探る Scale-UpやUltraEthernet機能の実装方法
ebiken
PRO
2
240
AIネイティブな開発のサプライチェーンリスク対策 〜激動の開発現場でリスクに立ち向かう〜【ZennFes】
cscengineer
PRO
2
110
手塩にかけりゃいいってもんじゃない
ming_ayami
0
550
protovalidate-es を導入してみた
bengo4com
0
180
【セミナー資料】Claude Code をセキュアに使うための考え方と設定の勘どころ / Claude Code Webinar 20260616
masahirokawahara
1
110
Claude Code×Terraform IaC テンプレート駆動開発
itouhi
1
510
「エンジニア進化論」2028年の開発完全自動化、エンジニアはどう進化するか
cyberagentdevelopers
PRO
6
5k
Featured
See All Featured
Bridging the Design Gap: How Collaborative Modelling removes blockers to flow between stakeholders and teams @FastFlow conf
baasie
0
580
Documentation Writing (for coders)
carmenintech
77
5.4k
Skip the Path - Find Your Career Trail
mkilby
1
150
Balancing Empowerment & Direction
lara
6
1.2k
Fantastic passwords and where to find them - at NoRuKo
philnash
52
3.7k
WENDY [Excerpt]
tessaabrams
11
38k
The Pragmatic Product Professional
lauravandoore
37
7.3k
Building an army of robots
kneath
306
46k
Six Lessons from altMBA
skipperchong
29
4.3k
HU Berlin: Industrial-Strength Natural Language Processing with spaCy and Prodigy
inesmontani
PRO
0
410
Believing is Seeing
oripsolob
1
140
Reflections from 52 weeks, 52 projects
jeffersonlam
356
21k
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/