Python Mock Tutorial Documentation

Similar documents
Python Unit Testing and CI Workflow. Tim Scott, Python Meetup 11/07/17

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

Iterators & Generators

Ensure Documentation. Release Andrey Kislyuk

Mock Documentation. Release Michael Foord

edeposit.amqp.calibre Release 1.1.4

Requests Mock Documentation

aiounittest Documentation

redis-lua Documentation

Errors. And How to Handle Them

django-redis-cache Documentation

COMP1730/COMP6730 Programming for Scientists. Testing and Debugging.

Unit testing with pytest and nose 1

prompt Documentation Release Stefan Fischer

doubles Documentation

bzz Documentation Release Rafael Floriano and Bernardo Heynemann

pytest-benchmark Release 2.5.0

OstrichLib Documentation

python-aspectlib Release 0.4.1

logstack Documentation

UNIVERSITY OF TORONTO Faculty of Arts and Science. Midterm 1 CSC148H1F L0201 (Liu)

An introduction to the ipaddress module Release 3.4.3

python-aspectlib Release 0.5.0

sphinx.rfc2119 Documentation

The First Three Rules

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Sure Documentation. Release Gabriel Falcão

WTForms-Appengine Documentation

Marshmallow-Mongoengine Documentation

CSE : Python Programming. Packages (Tutorial, Section 6.4) Announcements. Today. Packages: Concretely. Packages: Overview

sinon Documentation Release Kir Chou

django-crucrudile Documentation

Introduction to Python programming, II

micawber Documentation

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

kvkit Documentation Release 0.1 Shuhao Wu

PyTrie Documentation. Release 0.3. George Sakkis

Mock Documentation. Release Michael Foord

Python simple arp table reader Documentation

Lecture 18. Classes and Types

PySpec Documentation. Release Zac Stewart

Review 3. Exceptions and Try-Except Blocks

IPython Cypher Documentation

Mock Documentation. Release dev6. Michael Foord

Software Carpentry. Nicola Chiapolini. Physik-Institut University of Zurich. June 16, 2015

The WSGI Reference Library

Representing Documents; Unit Testing II

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8


Checked and Unchecked Exceptions in Java

ipython-gremlin Documentation

NeurAL Documentation. Release 1.0. Bill Gross

TAIL RECURSION, SCOPE, AND PROJECT 4 11

Pizco Documentation. Release 0.1. Hernan E. Grecco

Hystrix Python Documentation

Exceptions in Python. AMath 483/583 Lecture 27 May 27, Exceptions in Python. Exceptions in Python

Object-Oriented Python

Python-RHEV Documentation

tolerance Documentation

Lecture 21. Programming with Subclasses

CSI33 Data Structures

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

flexmock Documentation

61A Lecture 25. Friday, October 28

WordEmbeddingLoader Documentation

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Release 0.8. Repoze Developers

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013

Bricks Documentation. Release 1.0. Germano Guerrini

Python STL. Release dev

Unit Testing and Python. Pat Pannuto / Marcus Darden

Sherlock Documentation

Unit Tests. # Store the result of a boolean expression in a variable. >>> result = str(5)=='5'

Python for Astronomers. Errors and Exceptions

translationstring Documentation

edeposit.amqp.antivirus Release 1.0.1

msgpack Documentation

Exceptions. raise type(message) raise Exception(message)

Hashing. So what we do instead is to store in each slot of the array a linked list of (key, record) - pairs, as in Fig. 1. Figure 1: Chaining

semidbm Documentation

JSONRPC Documentation

Mastering Python Decorators

Exam #3, Form 3 A CSE 231 Fall 2015 (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

Pairs and Lists. (cons 1 2) 1 2. (cons 2 nil) 2 nil. Not a well-formed list! 1 > (cdr x) 2 > (cons 1 (cons 2 (cons 3 (cons 4 nil)))) ( ) (Demo)

Effective Programming Practices for Economists

Unit Testing In Python

Data Structures I: Linked Lists

chatterbot-weather Documentation

Structure and Flow. CS 3270 Chapter 5

slack Documentation Release 0.1 Avencall

Index. Cache, 20 Callables, 185 call () method, 290 chain() function, 41 Classes attributes descriptors, 145 properties, 143

Chapter 9: Dealing with Errors

Exceptions and File I/O

Fasteners Documentation

django-precise-bbcode Documentation

pyvcd Documentation Release Peter Grayson and Steven Sprouse

Clique. Release 1.3.1

Python Release September 11, 2014

lime Documentation Release 0.1 Marco Tulio Ribeiro

Transcription:

Python Mock Tutorial Documentation Release 0.1 Javier Collado Nov 14, 2017

Contents 1 Introduction 3 2 Mock 5 2.1 What is a mock object?.......................................... 5 2.2 What makes mock objects useful for testing?.............................. 6 2.3 How are methods mocked?........................................ 6 3 Indices and tables 9 i

ii

Python Mock Tutorial Documentation, Release 0.1 Contents: Contents 1

Python Mock Tutorial Documentation, Release 0.1 2 Contents

CHAPTER 1 Introduction mock is a python library than can be used together with unittest write better tests for your code. This document s goal is to get the reader started quickly using mock. None of the examples below will be difficult to follow, but a basic knowledge of python and unittest library is recommended. 3

Python Mock Tutorial Documentation, Release 0.1 4 Chapter 1. Introduction

CHAPTER 2 Mock 2.1 What is a mock object? A mock object is an instance of the Mock class or any of its subclasses: >>> from mock import Mock >>> my_mock = Mock() It supports attribute access and method calls: >>> my_mock.attribute <Mock name='mock.attribute' id='...'> >>> my_mock.method() <Mock name='mock.method()' id='...'> Index access is no supported by default because magic methods, those whose names are surrounded by double underscores, require a special configuration because of the way they are looked up internally in python. However, there is a special subclass of Mock called MagicMock that provides a default implementation for most magic methods including getitem : >>> from mock import MagicMock >>> my_mock = MagicMock() >>> my_mock['index'] <MagicMock name='mock. getitem ()' id='...'> Given that index access is usually required in test cases and that MagicMock provides that functionality out of the box, it s common to use MagicMock as an alias of Mock by default using import... as: >>> from mock import MagicMock as Mock >>> my_mock.attribute <MagicMock name='mock.attribute' id='...'> >>> my_mock.method() <MagicMock name='mock.method()' id='...'> 5

Python Mock Tutorial Documentation, Release 0.1 >>> my_mock['index'] <MagicMock name='mock. getitem ()' id='...'> 2.2 What makes mock objects useful for testing? As you may have noticed from the examples above, when an attribute is accessed (or any other of the supported operations), another mock object is returned. What you may have not noticed,though, is that always the same mock object is returned, that is, on the first call a new mock object is created that is cached and returned on any subsequent calls: >>> mock_attribute_1 = my_mock.attribute >>> mock_attribute_2 = my_mock.attribute >>> mock_attribute_1 is mock_attribute_2 True This is a useful property because it makes possible to get the mock objects that are going to be used in the unit under test in advance to configure them properly depending on the need of each test case. 2.3 How are methods mocked? 2.3.1 Setting return values Sometimes when a call is made on a mock object that pretends to be a method, the desired return value is not another mock object, but a python object that makes sense for a given test case. One way to set a return value, is to set the return_value attribute of a mock object to the desired value. For example: >>> my_mock.answer.return_value = 42 >>> my_mock.answer() 42 2.3.2 Setting side effects Some other times, when a method is called, an exception is supposed to be raised to simulate an error situation that the code being tested is expected to handle. In that case, the side_effect attribute provide the expected behavior: >>> my_mock.error.side_effect = ValueError('Error message') >>> my_mock.error() Traceback (most recent call last):... ValueError: Error message Additionally, the side_effect attribute can be used when different values are expected to be returned for each method call using an iterable: >>> my_mock.get_next.side_effect = [1, 2, 3] >>> my_mock.get_next() 1 >>> my_mock.get_next() 6 Chapter 2. Mock

Python Mock Tutorial Documentation, Release 0.1 2 >>> my_mock.get_next() 3 When a more advanced behavior is needed, instead of an iterable, a callable can be used to return whatever is needed. However, this is not commonly used. 2.3.3 Assertions Given that they are used for testing, mock objects are usually involved in assertions as well. In particular, they are commonly used to make sure that a method from an external dependency was called. One simple way to do this is just look at the called attribute: >>> my_mock.method() <MagicMock name='mock.method()' id='...'> >>> my_mock.method.called True However, that s not usually enough, since we need to figure out not only if a method was called, but also if it was called with the right arguments. In such a case, assert_called_with is a great helper method: >>> my_mock.method(1, 2, 3, a=4, b=5, c=6) <MagicMock name='mock.method()' id='...'> >>> my_mock.method.assert_called_with(1, 2, 3, a=4, b=5, c=6) Of course, if the method wasn t called with the expected arguments an AssertionError will be raised: >>> my_mock.method.assert_called_with('some', 'other', 'arguments') Traceback (most recent call last):... AssertionError: Expected call: method('some', 'other', 'arguments') Actual call: method(1, 2, 3, a=4, c=6, b=5) There are other helper methods that I recommend that can be used and are well described in the documentation. One that is particularly useful is assert_called_once_with that works exactly in the same way, but will fail if the method has been called more than once. 2.3. How are methods mocked? 7

Python Mock Tutorial Documentation, Release 0.1 8 Chapter 2. Mock

CHAPTER 3 Indices and tables genindex modindex search 9