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
Amazon SageMakerでImagenを動かして猫画像生成してみた
hotoke_neko
0
120
Records の使い方はこれでいいの? をみんなで考えたい / Java DO #20
gishi_yama
0
130
一口目から美味しいReactのスルメ本🦑
taro28
2
670
読みやすいコード クラスメソッド 2022 年度新卒研修
januswel
0
2.9k
FargateとAthenaで作る、機械学習システム
nayuts
0
190
OSS貢献を気軽にしたい Let's Go Talk #1
yuyaabo
2
240
ふんわり理解するcontext
rukiadia
1
180
料理の注文メニューの3D化への挑戦
hideg
0
290
Regular expressions basics/正規表現の基本
kishikawakatsumi
6
260
SwiftUIで「意図」を伝える / swiftui_intention
uhooi
2
150
FullStack eXchange, July 2022
brucel
0
200
RustのWebフレームワーク周りの概観
hayao
0
180
Featured
See All Featured
The Brand Is Dead. Long Live the Brand.
mthomps
46
2.7k
Building Better People: How to give real-time feedback that sticks.
wjessup
344
17k
What's new in Ruby 2.0
geeforr
335
30k
Scaling GitHub
holman
451
140k
A Philosophy of Restraint
colly
192
15k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
349
27k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
6
570
Designing Experiences People Love
moore
130
22k
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
181
15k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
351
21k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
107
16k
How to name files
jennybc
40
63k
Transcript
Testing with unittest.mock Ana Hristova
♥ Every tester has the heart of a developer
Crowd Investment Platform CONNECTING INVESTORS AND ENTREPRENEURS THROUGH FUNDING ana@fundedbyme.com
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