Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Speaker Deck
PRO
Sign in
Sign up for free
Testing with unittest.mock
Ana Yankova
May 20, 2014
Programming
0
150
Testing with unittest.mock
Ana Yankova
May 20, 2014
Tweet
Share
More Decks by Ana Yankova
See All by Ana Yankova
Everyday Refactoring of a Django Project
anah
0
240
Other Decks in Programming
See All in Programming
Remote SSHで行うVS Codeリモートホスト開発とトラブルシューティング
smt7174
1
520
tidy_rpart
bk_18
0
610
Hasura の Relationship と権限管理
karszawa
0
180
Listかもしれない
irof
1
290
爆速の日経電子版開発の今
shinyaigeek
2
660
Cloudflare Workersと状態管理
chimame
3
500
Form実装基本を学び直してみた
hyugatsukui
0
250
データドリブンな組織の不正検知
fkubota
0
310
domain層のモジュール化 / MoT TechTalk #15
mot_techtalk
0
150
Makuakeの認証基盤とRe-Architectureチーム
bmf_san
0
640
Swift Concurrency in GoodNotes
inamiy
4
1.4k
まだ日本国内で利用できないAppActionsにトライしてみた / MoT TechTalk #15
mot_techtalk
0
150
Featured
See All Featured
How GitHub (no longer) Works
holman
298
140k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
109
16k
From Idea to $5000 a Month in 5 Months
shpigford
374
44k
BBQ
matthewcrist
75
8.1k
Imperfection Machines: The Place of Print at Facebook
scottboms
254
12k
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
38
3.6k
Making Projects Easy
brettharned
102
4.8k
Making the Leap to Tech Lead
cromwellryan
117
7.7k
GraphQLの誤解/rethinking-graphql
sonatard
39
7.8k
Agile that works and the tools we love
rasmusluckow
321
20k
Designing with Data
zakiwarfel
91
4.2k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
24
4.6k
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