Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Testing with unittest.mock
Search
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
Ana Yankova
May 20, 2014
Programming
370
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Testing with unittest.mock
Ana Yankova
May 20, 2014
Transcript
36 slides
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
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
あなたの await、OS まで届いてる? strace で覗く JavaScript の非同期
hasutosasaki
1
2.4k
Growing PicoRuby's Ecosystem on ESP32
yuuu
2
130
AIが生成したコードは読むべきか?抽象化設計とコードの品質保証 / abstraction-design-and-quality
minodriven
16
9.1k
조합이폭발하는디자인시스템이걸눈으로도테스트하라고요
giljongyu
0
750
そのデザイントークン、Flutterでも同じ見た目になりますか?
nakamizu
0
350
AI時代のFlutter品質設計 — アプリ品質を守るQuality Layers
omatty198
0
380
flutter_test のその先へ — Flutter アプリの LLM 機能に「評価」という品質保証を
kosukesaigusa
0
200
3回つくってわかった、 定期実行ジョブ基盤の本質情報
takai
4
3.9k
AI-Powered Domain-Driven Design
ziobrando
0
450
TanStack Vue Query と Pinia Colada から学ぶ非同期状態の型設計
aoshi
0
670
AI駆動開発4年目の現在地(『あなたはFDEになるべきか?』イベント資料)
kumaiu
0
620
止まらない比較を止める — 余帰納法で無限ストリームを比べる
tarao
0
140
Featured
See All Featured
Pawsitive SEO: Lessons from My Dog (and Many Mistakes) on Thriving as a Consultant in the Age of AI
davidcarrasco
1
300
How to Ace a Technical Interview
jacobian
280
24k
GraphQLとの向き合い方2022年版
quramy
50
15k
Mozcon NYC 2025: Stop Losing SEO Traffic
samtorres
1
600
Become a Pro
speakerdeck
PRO
31
6.4k
Chasing Engaging Ingredients in Design
codingconduct
0
400
Gemini Prompt Engineering: Practical Techniques for Tangible AI Outcomes
mfonobong
2
630
Deep Space Network (abreviated)
tonyrice
0
410
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
27k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
133
20k
StorybookのUI Testing Handbookを読んだ
zakiyama
31
7.1k
The Director’s Chair: Orchestrating AI for Truly Effective Learning
tmiket
1
350