Thu, 22 Jan 2015 13:21:57 +0100
Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6
michael@0 | 1 | ========== |
michael@0 | 2 | Sentinel |
michael@0 | 3 | ========== |
michael@0 | 4 | |
michael@0 | 5 | |
michael@0 | 6 | .. currentmodule:: mock |
michael@0 | 7 | |
michael@0 | 8 | .. testsetup:: |
michael@0 | 9 | |
michael@0 | 10 | class ProductionClass(object): |
michael@0 | 11 | def something(self): |
michael@0 | 12 | return self.method() |
michael@0 | 13 | |
michael@0 | 14 | class Test(unittest2.TestCase): |
michael@0 | 15 | def testSomething(self): |
michael@0 | 16 | pass |
michael@0 | 17 | self = Test('testSomething') |
michael@0 | 18 | |
michael@0 | 19 | |
michael@0 | 20 | .. data:: sentinel |
michael@0 | 21 | |
michael@0 | 22 | The ``sentinel`` object provides a convenient way of providing unique |
michael@0 | 23 | objects for your tests. |
michael@0 | 24 | |
michael@0 | 25 | Attributes are created on demand when you access them by name. Accessing |
michael@0 | 26 | the same attribute will always return the same object. The objects |
michael@0 | 27 | returned have a sensible repr so that test failure messages are readable. |
michael@0 | 28 | |
michael@0 | 29 | |
michael@0 | 30 | .. data:: DEFAULT |
michael@0 | 31 | |
michael@0 | 32 | The `DEFAULT` object is a pre-created sentinel (actually |
michael@0 | 33 | `sentinel.DEFAULT`). It can be used by :attr:`~Mock.side_effect` |
michael@0 | 34 | functions to indicate that the normal return value should be used. |
michael@0 | 35 | |
michael@0 | 36 | |
michael@0 | 37 | Sentinel Example |
michael@0 | 38 | ================ |
michael@0 | 39 | |
michael@0 | 40 | Sometimes when testing you need to test that a specific object is passed as an |
michael@0 | 41 | argument to another method, or returned. It can be common to create named |
michael@0 | 42 | sentinel objects to test this. `sentinel` provides a convenient way of |
michael@0 | 43 | creating and testing the identity of objects like this. |
michael@0 | 44 | |
michael@0 | 45 | In this example we monkey patch `method` to return |
michael@0 | 46 | `sentinel.some_object`: |
michael@0 | 47 | |
michael@0 | 48 | .. doctest:: |
michael@0 | 49 | |
michael@0 | 50 | >>> real = ProductionClass() |
michael@0 | 51 | >>> real.method = Mock(name="method") |
michael@0 | 52 | >>> real.method.return_value = sentinel.some_object |
michael@0 | 53 | >>> result = real.method() |
michael@0 | 54 | >>> assert result is sentinel.some_object |
michael@0 | 55 | >>> sentinel.some_object |
michael@0 | 56 | sentinel.some_object |
michael@0 | 57 | |
michael@0 | 58 |