File: getting-started.txt

package info (click to toggle)
python-mock 0.6.0-1.1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 780 kB
  • ctags: 245
  • sloc: python: 755; makefile: 28
file content (159 lines) | stat: -rw-r--r-- 5,012 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
===========================
 Getting Started with Mock
===========================

.. index:: Getting Started

.. testsetup::

    import os, sys
    if not os.getcwd() in sys.path:
        sys.path.append(os.getcwd())
        
    from mock import Mock, sentinel
    
    class ProductionClass(object):
        pass


Using Mock
==========

``Mock`` objects can be used for:

* Patching methods
* Recording method calls on objects

.. doctest::

    >>> from mock import Mock
    >>> real = ProductionClass()
    >>> real.method = Mock()
    >>> 
    >>> real.method(3, 4, 5, key='value')
    <mock.Mock object at 0x...>
    >>>

Once the mock has been used it has methods and attributes that allow you to make assertions about how it has been used:

.. doctest::
    
    >>> real.method.assert_called_with(3, 4, 5, key='value')
    >>> real.method.called
    True
    >>> real.method.call_args
    ((3, 4, 5), {'key': 'value'})
    >>>

Mocks also record calls made to attributes, their 'child' attributes:

.. doctest::

    >>> mock = Mock()
    >>> mock.something()
    <mock.Mock object at 0x...>
    >>> mock.method_calls
    [('something', (), {})]
    
You can also create Mock objects that behave like the class they are intended to mock. This is done with the ``spec`` keyword argument, which either takes a list of strings describing the attributes that the mock should have - or you can pass in the object (class or instance) that you are mocking out. Attempting to access an attribute on the mock that isn't in the spec will raise an ``AttributeError``.

.. doctest::

    >>> mock = Mock(spec=['something'])
    >>> mock.something()
    <mock.Mock object at 0x...>
    >>> mock.something_else()
    Traceback (most recent call last):
       ...
    AttributeError: object has no attribute 'something_else'

There are various ways of configuring the mock, including setting return values
on the mock and its methods. A useful attribute is ``side_effect``. If you set
this to an exception class or instance then the exception will be raised when
the mock is called. If you set it to a callable then it will be called whenever
the mock is called. This allows you to do things like return members of a
sequence from repeated calls:


.. doctest::

    >>> mock = Mock()
    >>> mock.side_effect = Exception('Boom!')
    >>> mock()
    Traceback (most recent call last):
      ...
    Exception: Boom!
    
    >>> results = [1, 2, 3]
    >>> def side_effect(*args, **kwargs):
    ...     return results.pop()
    ... 
    >>> mock.side_effect = side_effect
    >>> mock(), mock(), mock()
    (3, 2, 1)


Sentinel
========

``sentinel`` is a useful object for providing unique objects in your tests:

.. doctest::

    >>> from mock import sentinel
    >>> real = ProductionClass()
    >>> real.method = Mock()
    >>> 
    >>> real.method.return_value = sentinel.return_value
    >>> real.method()
    <SentinelObject "return_value">


Patch Decorators
================

There are also decorators for doing module and class level patching. As modules and classes are effectively globals any patching has to be undone (or it persists into other tests). These decorators do the unpatching for you, making it easier to test with module and class level patching. 

The two decorators are 'patch' and 'patch_object'. 'patch' takes a single string, of the form ``package.module.Class.attribute`` to specify the attribute you are patching. It also optionally takes a value that you want the attribute (or class or whatever) to be replaced with. 'patch_object' takes an object and the name of the attribute you would like patched, plus optionally the value to patch it with.

::

    
    original = SomeClass.attribute
    @patch_object(SomeClass, 'attribute', sentinel.Attribute)
    def test():
        self.assertEquals(SomeClass.attribute, sentinel.Attribute, "class attribute not patched")
    test()
    
    self.assertEquals(SomeClass.attribute, original, "attribute not restored")
    
    
    @patch('Package.Module.attribute', sentinel.Attribute)
    def test():
        "do something"
    test()


If you don't want to call the decorated test function yourself, you can add ``apply`` as a decorator on top::

    @apply
    @patch('Package.Module.attribute', sentinel.Attribute)
    def test():
        "do something"

(Note that this leaves test == None)


A nice pattern is to actually decorate test methods themselves::

    @patch('Package.Module.attribute', sentinel.Attribute)
    def testMethod(self):
        "do something"
    

If you want to patch with a Mock, you can use ``patch`` with only one argument (or ``patch_object`` with two arguments). The mock will be created for you and passed into the test function / method::

    @patch('Package.Module.Class')
    def testMethod(self, mMckClass):
        "do something"