Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(62)

Side by Side Diff: testing_support/auto_stub.py

Issue 8688011: Move auto_stub.py from commit-queue (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/tools/depot_tools
Patch Set: Created 9 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « .gitignore ('k') | testing_support/trial_dir.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 # Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5 import inspect
6 import unittest
7
8
9 class OrderedDict(object):
10 """Incomplete and inefficient implementation of collections.OrderedDict."""
11 def __init__(self):
12 self._keys = []
13
14 def setdefault(self, key, value):
15 try:
16 self._getindex(key)
17 except KeyError:
18 self._keys.append((key, value))
19 return self[key]
20
21 def _getindex(self, key):
22 for i, v in enumerate(self._keys):
23 if v[0] == key:
24 return i
25 raise KeyError(key)
26
27 def __getitem__(self, key):
28 return self._keys[self._getindex(key)][1]
29
30 def iteritems(self):
31 for i in self._keys:
32 yield i
33
34
35 class AutoStubMixIn(object):
36 """Automatically restores stubbed functions on unit test teardDown.
37
38 It's an extremely lightweight mocking class that doesn't require bookeeping.
39 """
40 _saved = None
41
42 def mock(self, obj, member, mock):
43 self._saved = self._saved or OrderedDict()
44 old_value = self._saved.setdefault(
45 obj, OrderedDict()).setdefault(member, getattr(obj, member))
46 setattr(obj, member, mock)
47 return old_value
48
49 def tearDown(self):
50 """Restore all the mocked members."""
51 if self._saved:
52 for obj, items in self._saved.iteritems():
53 for member, previous_value in items.iteritems():
54 setattr(obj, member, previous_value)
55
56
57 class SimpleMock(object):
58 """Really simple manual class mock."""
59 calls = []
60
61 def __init__(self, unit_test):
62 """Do not call __init__ if you want to use the global call list to detect
63 ordering across different instances.
64 """
65 self.calls = []
66 self.unit_test = unit_test
67 self.assertEquals = unit_test.assertEquals
68
69 def pop_calls(self):
70 """Returns the list of calls up to date.
71
72 Good to do self.assertEquals(expected, mock.pop_calls()).
73 """
74 calls = self.calls
75 self.calls = []
76 return calls
77
78 def check_calls(self, expected):
79 self.assertEquals(expected, self.pop_calls())
80
81 def _register_call(self, *args, **kwargs):
82 """Registers the name of the caller function."""
83 caller_name = kwargs.pop('caller_name', None) or inspect.stack()[1][3]
84 str_args = ', '.join(repr(arg) for arg in args)
85 str_kwargs = ', '.join('%s=%r' % (k, v) for k, v in kwargs.iteritems())
86 self.calls.append('%s(%s)' % (
87 caller_name, ', '.join(filter(None, [str_args, str_kwargs]))))
88
89
90 class TestCase(unittest.TestCase, AutoStubMixIn):
91 """Adds python 2.7 functionality."""
92
93 def tearDown(self):
94 AutoStubMixIn.tearDown(self)
95 unittest.TestCase.tearDown(self)
96
97 def has_failed(self):
98 """Returns True if the test has failed."""
99 if hasattr(self, '_exc_info'):
100 # Only present in python <= 2.6
101 # pylint: disable=E1101
102 return bool(self._exc_info()[0])
103
104 # Only present in python >= 2.7
105 # pylint: disable=E1101
106 return not self._resultForDoCleanups.wasSuccessful()
107
108 def assertIs(self, expr1, expr2, msg=None):
109 if hasattr(super(TestCase, self), 'assertIs'):
110 return super(TestCase, self).assertIs(expr1, expr2, msg)
111 if expr1 is not expr2:
112 self.fail(msg or '%r is not %r' % (expr1, expr2))
113
114 def assertIsNot(self, expr1, expr2, msg=None):
115 if hasattr(super(TestCase, self), 'assertIsNot'):
116 return super(TestCase, self).assertIsNot(expr1, expr2, msg)
117 if expr1 is expr2:
118 self.fail(msg or 'unexpectedly identical: %r' % expr1)
119
120 def assertIn(self, expr1, expr2, msg=None):
121 if hasattr(super(TestCase, self), 'assertIn'):
122 return super(TestCase, self).assertIn(expr1, expr2, msg)
123 if expr1 not in expr2:
124 self.fail(msg or '%r not in %r' % (expr1, expr2))
125
126 def assertLess(self, a, b, msg=None):
127 if hasattr(super(TestCase, self), 'assertLess'):
128 return super(TestCase, self).assertLess(a, b, msg)
129 if not a < b:
130 self.fail(msg or '%r not less than %r' % (a, b))
OLDNEW
« no previous file with comments | « .gitignore ('k') | testing_support/trial_dir.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698