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
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
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
ハーネス設計入門 〜プロンプト、コンテキストの次〜
kinopeee
53
35k
My Marp Sample
sinoue0108
0
140
iOS開発×AI駆動開発 〜最近使って便利だったスキルの話〜
nogu66
0
140
LLMは4年分のCompose移行を再現できるのか?実プロダクト279件のXMLで探る自動化の境界線
makun
0
380
AIと壁打ちしながら進めるコスト管理
fufuhu
2
1.9k
20260828_品質と開発生産性を両立させる、AI時代のE2Eテストの考え方
magicpod
0
140
Press start. Python's next generation.
willingc
PRO
3
300
Kiroで創り、AgentCoreで繋ぐ!AWSで実践する「AI-DLC」から「AIエージェント統合」までの最新地図
licux
2
300
Deep dive into the select statement (GopherCon UK)
jespino
0
170
新人はどこまで自力でやり、どこからAIに頼るべきか/エンジニア育成に向き合う_先輩たちの悩みと知見共有会
toppan_digital_dev
1
560
kubernetes コンポーネント開発入門 / 新卒N年目の勉強会&交流会!〜〇〇への誘い〜 #n_study
mazrean
0
160
初心者DevRelとして参加者だった私が、DevRel Talks!#2に登壇するまでにしてきたこと
sokohirai
0
330
Featured
See All Featured
The Straight Up "How To Draw Better" Workshop
denniskardys
239
140k
The Mindset for Success: Future Career Progression
greggifford
PRO
0
490
AI Search: Where Are We & What Can We Do About It?
aleyda
0
7.9k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
46
3k
Tips & Tricks on How to Get Your First Job In Tech
honzajavorek
1
720
Claude Code どこまでも/ Claude Code Everywhere
nwiizo
67
58k
Why Your Marketing Sucks and What You Can Do About It - Sophie Logan
marketingsoph
0
400
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
640
Have SEOs Ruined the Internet? - User Awareness of SEO in 2025
akashhashmi
0
490
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
133
19k
Stewardship and Sustainability of Urban and Community Forests
pwiseman
0
510
エンジニアに許された特別な時間の終わり
watany
108
250k
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