Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Python Unlocked

You're reading from   Python Unlocked Become more fluent in Python—learn strategies and techniques for smart and high-performance Python programming

Arrow left icon
Product type Paperback
Published in Dec 2015
Publisher
ISBN-13 9781785885990
Length 172 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Arun Tigeraniya Arun Tigeraniya
Author Profile Icon Arun Tigeraniya
Arun Tigeraniya
Arrow right icon
View More author details
Toc

Mock for tests


Key 1: Mock what you do not have.

When we are using test driven development, we have to write test cases for the components that rely on other components that are not written yet or take a lot of time to execute. This is close to impossible until we create mocks and stubs. In this scenario, stubs or mocks are very useful. We use a fake object instead of a real one to write the test case. This can be made very easy if we use tools that are provided by the language. For example, in the following code, we only have the interface for the worker class, and no real implementation of it. We want to test the assign_if_free function.

Instead of writing any stub ourselves, we use the create_autospec function to create a mock object from the definition of the Worker abstract class. We also set up a return value for the function call of checking whether worker was busy or not:

import six
import unittest
import sys
import abc
if sys.version_info[0:2] >= (3, 3):
    from unittest.mock...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image