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