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
Testing with unittest.mock
Search
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
Ana Yankova
May 20, 2014
Programming
350
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Testing with unittest.mock
Ana Yankova
May 20, 2014
More Decks by Ana Yankova
See All by Ana Yankova
Everyday Refactoring of a Django Project
anah
0
270
Other Decks in Programming
See All in Programming
Lean は証明の正しさを確認するためだけのツールって思ってませんか?
inoueasei
1
160
人間の目はかわらない、だからJPEGは30年もつ
yuzneri
12
18k
jsmini JavaScript Engine を作ってみた話
yosuke_furukawa
PRO
0
320
ルールを書いて終わらせないハーネスエンジニアリング
yug1224
4
1.9k
【やさしく解説 設計編・中級 #6】良いアーキテクチャとは ~ 一本の登り道の、行き先 ~
panda728
PRO
0
210
変わらないものが、変わるものを決める — 意図駆動開発 × イベントソーシング × イミュータブル | What Doesn't Change Decides What Can — IDD × Event Sourcing × Immutability
tomohisa
0
1.7k
改善しないと、タスクが回らない。 “てんこ盛りポジション” を引き継いだ情シスの、入社3ヶ月の業務改善録
krm963
0
260
TSX の <Hoge<Fuga>> という構文に驚いた話 / tsx-type-argument-syntax
kanaru0928
0
230
属人化した知識を、 AIが辿れる地図にする
pkshadeck
PRO
1
170
実装をデザインガイドラインに追従させるための取り組み / 260731-dip-mosh-design-system
dachi023
0
450
いまどきの Codex で開発する visionOS アプリの開発スタイルについて
karad
0
140
テーブルをDELETEした
yuzneri
0
140
Featured
See All Featured
Reality Check: Gamification 10 Years Later
codingconduct
0
2.3k
Design in an AI World
tapps
1
280
SEOcharity - Dark patterns in SEO and UX: How to avoid them and build a more ethical web
sarafernandez
0
240
AI in Enterprises - Java and Open Source to the Rescue
ivargrimstad
0
1.4k
How to Align SEO within the Product Triangle To Get Buy-In & Support - #RIMC
aleyda
2
1.8k
HTML-Aware ERB: The Path to Reactive Rendering @ RubyCon 2026, Rimini, Italy
marcoroth
3
430
A brief & incomplete history of UX Design for the World Wide Web: 1989–2019
jct
2
470
How to Ace a Technical Interview
jacobian
281
24k
Making the Leap to Tech Lead
cromwellryan
135
10k
Taking LLMs out of the black box: A practical guide to human-in-the-loop distillation
inesmontani
PRO
3
2.3k
Learning to Love Humans: Emotional Interface Design
aarron
275
41k
Leveraging Curiosity to Care for An Aging Population
cassininazir
1
470
Transcript
Testing with unittest.mock Ana Hristova
♥ Every tester has the heart of a developer
Crowd Investment Platform CONNECTING INVESTORS AND ENTREPRENEURS THROUGH FUNDING
[email protected]
None
Sweden
unittest.mock Testing library
Part of the Python Standard Library as of Python 3.3
unittest.mock
For older versions: unittest.mock $ pip install mock
unittest.mock helps you create mock objects and make assertions about
them
How is this helpful?
You want to test code that depends on the "
date or time
You are building a shiny new app … # $
% % % % % & ' ( )
Please wait… … while your tests are running *
Mock MagicMock patch( )
Mock objects Callable
Mock objects Create attributes on demand
Mock objects Record how you use the attributes
Allow you to set return values or limit the available
attributes Mock objects
Examples
>>> class Comment: ... ... def create(self, text, parent=None): ...
pass ... comment = Comment()
>>> comment.create = Mock(return_value=True) >>> comment.create(text=‘hello') True >>> comment.create. \
... assert_called_once_with(text=‘hello’) >>> comment.create.called True >>> comment.create.call_args call(text='hello') >>> comment.call_count 1
>>> mock = Mock() >>> mock <Mock id='4353021072'> >>> mock.method
<Mock name='mock.method' id=‘4352854800'> >>> mock.assetr_called_with(keyword=None)
... AttributeError: Mock object has no attribute 'remove' >>> comment.remove
>>> from unittest.mock import create_autospec >>> >>> comment = create_autospec(Comment)
side effects
>>> comment.create.side_effect = \ ... ConnectionError(“Connection refused”) >>> ... ConnectionError:
Connection refused >>> comment.create.mock_calls [call(parent=None, text='Hello')] >>> >>> comment.create(text="Hello", parent=None)
magic methods Mocking
>>> mock = Mock() >>> mock.__len__ = Mock() >>> mock.__len__.return_value
= 42 >>> len(mock) 42 ! !
MagicMock with default implementations of magic methods Subclass of Mock
>>> mock = MagicMock() >>> int(mock) 1 >>> len(mock) 0
>>> list(mock) [] >>> mock.__int__.called True
patch( ) Used to patch objects within the scope of
the test
#event.py from datetime import date ! class Event(): ! def
get_state(self): if self.end_date < date.today(): return "PAST" if self.start_date > date.today(): return "FUTURE" if self.start_date <= date.today() <= self.end_date: return "CURRENT"
#test.py from datetime import date ! class EventTests(TestCase): def setUp(self):
self.pycon = Event() self.pycon.start_date = date(2014, 5, 20) self.pycon.end_date = date(2014, 5, 21) ! @patch('event.date') def test_event_has_passed(self, mock_date): mock_date.today.return_value = date(2014, 5, 22) assert self.pycon.get_state() == "PAST"
@patch('event.date') def test_event_has_passed(self, mock_date): mock_date.today.return_value = date(2014, 5, 22) assert
self.pycon.get_state() == "PAST"
class UserProfileSaveTests(TestCase): ! def setUp(self): self.profile = UserProfileFactory.build(user=UserFactory()) ! !
@patch("notifications.tasks.subscribe_to_newsletter.delay") def test_subscribe_to_newsletter(self, subscribe_mock): self.profile.newsletter = True self.profile.save() subscribe_mock.assert_called_once_with(self.profile.user)
Mock wisely!
@anhristova + , anah