File: sentinel.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 (56 lines) | stat: -rw-r--r-- 1,826 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
==========
 Sentinel
==========


.. currentmodule:: mock

.. testsetup::

    import os, sys, unittest
    if not os.getcwd() in sys.path:
        sys.path.append(os.getcwd())
        
    from mock import Mock, sentinel
    
    class ProductionClass(object):
        def something(self):
            return self.method()
    
    class Test(unittest.TestCase):
        def testSomething(self):
            pass
    self = Test('testSomething')


.. data:: sentinel

    The ``sentinel`` object provides a convenient way of providing unique objects for your tests.

    Attributes are created on demand when you access them by name. Accessing the same attribute will always return the same object. The objects returned have a sensible repr so that test failure messages are readable.

    
.. data:: DEFAULT

    The ``DEFAULT`` object is a pre-created sentinel (actually ``sentinel.DEFAULT``). It can be used by :attr:`Mock.side_effect` functions to indicate that the normal
    return value should be used.

Sentinel Example
================

Sometimes when testing you need to test that a specific object is passed as an argument to another method, or returned. It can be common to create named sentinel objects to test this. ``sentinel`` provides a convenient way of creating and testing the identity of objects like this.

In this example we monkey patch ``method`` to return ``sentinel.return_value``. We want to test that this is the value returned when we call ``something``:

.. doctest::

    >>> real = ProductionClass()
    >>> real.method = Mock()
    >>> real.method.return_value = sentinel.return_value
    >>> returned = real.something()
    >>> self.assertEquals(returned, sentinel.return_value, "something returned the wrong value")
    
    >>> sentinel.return_value
    <SentinelObject "return_value">