libv8 6.0.286.54.3 → 6.2.414.42.0beta1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (86) hide show
  1. checksums.yaml +4 -4
  2. data/.travis.yml +5 -3
  3. data/CHANGELOG.md +4 -0
  4. data/Rakefile +3 -3
  5. data/lib/libv8/version.rb +1 -1
  6. data/patches/0001-Build-a-standalone-static-library.patch +4 -4
  7. data/patches/0002-Don-t-compile-unnecessary-stuff.patch +12 -14
  8. data/patches/0003-Use-the-fPIC-flag-for-the-static-library.patch +4 -4
  9. data/patches/0004-Do-not-embed-debug-symbols-in-macOS-libraries.patch +4 -4
  10. data/patches/0005-avoid-constructor-inheritance-due-to-compilation-iss.patch +81 -0
  11. data/patches/9001-Arm64-Fix-host-architecture-detection.patch +37 -0
  12. data/vendor/depot_tools/.gitignore +1 -0
  13. data/vendor/depot_tools/OWNERS +0 -1
  14. data/vendor/depot_tools/auth.py +154 -6
  15. data/vendor/depot_tools/bootstrap/win/manifest.txt +1 -1
  16. data/vendor/depot_tools/bootstrap/win/manifest_bleeding_edge.txt +1 -1
  17. data/vendor/depot_tools/cipd_bin_setup.sh +12 -2
  18. data/vendor/depot_tools/cipd_manifest.txt +4 -1
  19. data/vendor/depot_tools/fetch.py +2 -0
  20. data/vendor/depot_tools/gclient.py +4 -6
  21. data/vendor/depot_tools/gclient_scm.py +12 -5
  22. data/vendor/depot_tools/gerrit_util.py +23 -1
  23. data/vendor/depot_tools/git_cache.py +59 -23
  24. data/vendor/depot_tools/git_cl.py +114 -43
  25. data/vendor/depot_tools/git_common.py +7 -0
  26. data/vendor/depot_tools/git_rebase_update.py +1 -0
  27. data/vendor/depot_tools/git_upstream_diff.py +12 -5
  28. data/vendor/depot_tools/gsutil.py +10 -0
  29. data/vendor/depot_tools/infra/config/OWNERS +0 -1
  30. data/vendor/depot_tools/infra/config/cq.cfg +6 -5
  31. data/vendor/depot_tools/infra/config/recipes.cfg +1 -1
  32. data/vendor/depot_tools/mac_toolchain +12 -0
  33. data/vendor/depot_tools/man/html/git-upstream-diff.html +10 -6
  34. data/vendor/depot_tools/man/man1/git-upstream-diff.1 +18 -7
  35. data/vendor/depot_tools/man/src/git-upstream-diff.txt +8 -5
  36. data/vendor/depot_tools/owners.py +9 -2
  37. data/vendor/depot_tools/presubmit_canned_checks.py +122 -0
  38. data/vendor/depot_tools/presubmit_support.py +57 -4
  39. data/vendor/depot_tools/recipes/OWNERS +0 -1
  40. data/vendor/depot_tools/recipes/README.recipes.md +20 -17
  41. data/vendor/depot_tools/recipes/recipe_modules/bot_update/__init__.py +1 -1
  42. data/vendor/depot_tools/recipes/recipe_modules/bot_update/api.py +15 -4
  43. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/basic.json +23 -0
  44. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/basic_with_branch_heads.json +46 -0
  45. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/buildbot.json +23 -0
  46. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/clobber.json +46 -0
  47. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/deprecated_got_revision_mapping.json +22 -0
  48. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/gerrit_no_rebase_patch_ref.json +46 -0
  49. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/gerrit_no_reset.json +46 -0
  50. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/no_shallow.json +46 -0
  51. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/reset_root_solution_revision.json +46 -0
  52. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/trychange.json +46 -0
  53. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/trychange_oauth2_buildbot.json +46 -0
  54. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/trychange_oauth2_json.json +46 -0
  55. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/trychange_oauth2_json_win.json +46 -0
  56. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/tryjob.json +46 -0
  57. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/tryjob_empty_revision.json +46 -0
  58. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/tryjob_fail.json +4 -45
  59. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/tryjob_fail_patch.json +23 -0
  60. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/tryjob_fail_patch_download.json +23 -0
  61. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/tryjob_gerrit_angle.json +46 -0
  62. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/tryjob_gerrit_angle_deprecated.json +46 -0
  63. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/tryjob_gerrit_feature_branch.json +46 -0
  64. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/tryjob_gerrit_v8.json +46 -0
  65. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/tryjob_gerrit_v8_feature_branch.json +46 -0
  66. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/tryjob_gerrit_webrtc.json +46 -0
  67. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/tryjob_v8.json +46 -0
  68. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/tryjob_v8_head_by_default.json +46 -0
  69. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/with_manifest_name.json +194 -0
  70. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/with_manifest_name_no_patch.json +105 -0
  71. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.expected/with_tags.json +46 -0
  72. data/vendor/depot_tools/recipes/recipe_modules/bot_update/examples/full.py +12 -2
  73. data/vendor/depot_tools/recipes/recipe_modules/bot_update/resources/bot_update.py +226 -149
  74. data/vendor/depot_tools/recipes/recipe_modules/bot_update/test_api.py +16 -5
  75. data/vendor/depot_tools/recipes/recipe_modules/gclient/config.py +1 -2
  76. data/vendor/depot_tools/recipes/recipes/fetch_end_to_end_test.expected/basic.json +11 -0
  77. data/vendor/depot_tools/rietveld.py +1 -1
  78. data/vendor/depot_tools/roll_dep.py +4 -1
  79. data/vendor/depot_tools/split_cl.py +3 -0
  80. data/vendor/depot_tools/third_party/cq_client/OWNERS +0 -1
  81. data/vendor/depot_tools/third_party/mock/LICENSE.txt +26 -0
  82. data/vendor/depot_tools/third_party/mock/README.chromium +24 -0
  83. data/vendor/depot_tools/third_party/mock/__init__.py +2366 -0
  84. data/vendor/depot_tools/watchlists.py +12 -5
  85. metadata +12 -5
  86. data/patches/0005-Fix-GCC-7-build-errors.patch +0 -147
@@ -34,14 +34,25 @@ class BotUpdateTestApi(recipe_test_api.RecipeTestApi):
34
34
  'properties': properties,
35
35
  'step_text': 'Some step text'
36
36
  })
37
-
38
37
  output.update({
39
38
  'manifest': {
40
- project_name: {
41
- 'repository': 'https://fake.org/%s.git' % project_name,
42
- 'revision': self.gen_revision(project_name),
39
+ project_name: {
40
+ 'repository': 'https://fake.org/%s.git' % project_name,
41
+ 'revision': self.gen_revision(project_name),
42
+ }
43
+ for project_name in set(revision_mapping.values())}})
44
+
45
+ output.update({
46
+ 'source_manifest': {
47
+ 'version': 0,
48
+ 'directories': {
49
+ project_name: {
50
+ 'git_checkout': {
51
+ 'repo_url': 'https://fake.org/%s.git' % project_name,
52
+ 'revision': self.gen_revision(project_name),
53
+ }
54
+ } for project_name in set(revision_mapping.values())
43
55
  }
44
- for project_name in set(revision_mapping.values())
45
56
  }
46
57
  })
47
58
 
@@ -269,8 +269,7 @@ def boringssl(c):
269
269
  def dart(c):
270
270
  soln = c.solutions.add()
271
271
  soln.name = 'sdk'
272
- soln.url = ('https://chromium.googlesource.com/external/github.com/' +
273
- 'dart-lang/sdk.git')
272
+ soln.url = ('https://dart.googlesource.com/sdk.git')
274
273
  soln.deps_file = 'DEPS'
275
274
  soln.managed = False
276
275
 
@@ -46,6 +46,17 @@
46
46
  "@@@STEP_LOG_LINE@json.output@ \"got_revision_cp\": \"refs/heads/master@{#91780}\"@@@",
47
47
  "@@@STEP_LOG_LINE@json.output@ }, @@@",
48
48
  "@@@STEP_LOG_LINE@json.output@ \"root\": \"depot_tools\", @@@",
49
+ "@@@STEP_LOG_LINE@json.output@ \"source_manifest\": {@@@",
50
+ "@@@STEP_LOG_LINE@json.output@ \"directories\": {@@@",
51
+ "@@@STEP_LOG_LINE@json.output@ \"depot_tools\": {@@@",
52
+ "@@@STEP_LOG_LINE@json.output@ \"git_checkout\": {@@@",
53
+ "@@@STEP_LOG_LINE@json.output@ \"repo_url\": \"https://fake.org/depot_tools.git\", @@@",
54
+ "@@@STEP_LOG_LINE@json.output@ \"revision\": \"59bbfb4465019d8ed83bfe88fef566922953452a\"@@@",
55
+ "@@@STEP_LOG_LINE@json.output@ }@@@",
56
+ "@@@STEP_LOG_LINE@json.output@ }@@@",
57
+ "@@@STEP_LOG_LINE@json.output@ }, @@@",
58
+ "@@@STEP_LOG_LINE@json.output@ \"version\": 0@@@",
59
+ "@@@STEP_LOG_LINE@json.output@ }, @@@",
49
60
  "@@@STEP_LOG_LINE@json.output@ \"step_text\": \"Some step text\"@@@",
50
61
  "@@@STEP_LOG_LINE@json.output@}@@@",
51
62
  "@@@STEP_LOG_END@json.output@@@",
@@ -93,7 +93,7 @@ class Rietveld(object):
93
93
  url = '/%d/patchset/%d/get_depends_on_patchset' % (issue, patchset)
94
94
  resp = None
95
95
  try:
96
- resp = json.loads(self.post(url, []))
96
+ resp = json.loads(self.get(url))
97
97
  except (urllib2.HTTPError, ValueError):
98
98
  # The get_depends_on_patchset endpoint does not exist on this Rietveld
99
99
  # instance yet. Ignore the error and proceed.
@@ -152,7 +152,10 @@ def roll(root, deps_dir, roll_to, key, reviewers, bug, no_log, log_limit,
152
152
  # Keep the first N log entries.
153
153
  logs = ''.join(logs.splitlines(True)[:log_limit]) + '(...)\n'
154
154
  log_section += logs
155
- log_section += '\n\nCreated with:\n roll-dep %s\n' % deps_dir
155
+ log_section += '\n\nCreated with:\n roll-dep ' + deps_dir
156
+ if key:
157
+ log_section += ' ' + key
158
+ log_section += '\n'
156
159
 
157
160
  reviewer = 'R=%s\n' % ','.join(reviewers) if reviewers else ''
158
161
  bug = 'BUG=%s\n' % bug if bug else ''
@@ -164,7 +164,10 @@ def SplitCl(description_file, comment_file, changelist, cmd_upload):
164
164
 
165
165
  author = git.run('config', 'user.email').strip() or None
166
166
  refactor_branch = git.current_branch()
167
+ assert refactor_branch, "Can't run from detached branch."
167
168
  refactor_branch_upstream = git.upstream(refactor_branch)
169
+ assert refactor_branch_upstream, \
170
+ "Branch %s must have an upstream." % refactor_branch
168
171
 
169
172
  owners_database = owners.Database(change.RepositoryRoot(), file, os.path)
170
173
  owners_database.load_data_needed_for([f.LocalPath() for f in files])
@@ -1,3 +1,2 @@
1
- phajdan.jr@chromium.org
2
1
  sergiyb@chromium.org
3
2
  tandrii@chromium.org
@@ -0,0 +1,26 @@
1
+ Copyright (c) 2003-2012, Michael Foord
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are
6
+ met:
7
+
8
+ * Redistributions of source code must retain the above copyright
9
+ notice, this list of conditions and the following disclaimer.
10
+
11
+ * Redistributions in binary form must reproduce the above
12
+ copyright notice, this list of conditions and the following
13
+ disclaimer in the documentation and/or other materials provided
14
+ with the distribution.
15
+
16
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,24 @@
1
+ Name: mock
2
+ URL: http://www.voidspace.org.uk/python/mock/
3
+ Version: 1.0.0
4
+ License: BSD
5
+ License File: LICENSE.txt
6
+
7
+ Description:
8
+ mock is a library for testing in Python. It allows you to replace parts of your
9
+ system under test with mock objects and make assertions about how they have been
10
+ used. mock is now part of the Python standard library, available as
11
+ unittest.mock in Python 3.3 onwards.
12
+ mock provides a core Mock class removing the need to create a host of stubs
13
+ throughout your test suite. After performing an action, you can make assertions
14
+ about which methods / attributes were used and arguments they were called with.
15
+ You can also specify return values and set needed attributes in the normal way.
16
+ Additionally, mock provides a patch() decorator that handles patching module and
17
+ class level attributes within the scope of a test, along with sentinel for
18
+ creating unique objects. Mock is very easy to use and is designed for use with
19
+ unittest. Mock is based on the ‘action -> assertion’ pattern instead of
20
+ ‘record -> replay’ used by many mocking frameworks. mock is tested on Python
21
+ versions 2.4-2.7, Python 3 plus the latest versions of Jython and PyPy.
22
+
23
+ Modifications:
24
+ None.
@@ -0,0 +1,2366 @@
1
+ # Test tools for mocking and patching.
2
+ # Copyright (C) 2007-2012 Michael Foord & the mock team
3
+ # E-mail: fuzzyman AT voidspace DOT org DOT uk
4
+
5
+ # mock 1.0
6
+ # http://www.voidspace.org.uk/python/mock/
7
+
8
+ # Released subject to the BSD License
9
+ # Please see http://www.voidspace.org.uk/python/license.shtml
10
+
11
+ # Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
12
+ # Comments, suggestions and bug reports welcome.
13
+
14
+
15
+ __all__ = (
16
+ 'Mock',
17
+ 'MagicMock',
18
+ 'patch',
19
+ 'sentinel',
20
+ 'DEFAULT',
21
+ 'ANY',
22
+ 'call',
23
+ 'create_autospec',
24
+ 'FILTER_DIR',
25
+ 'NonCallableMock',
26
+ 'NonCallableMagicMock',
27
+ 'mock_open',
28
+ 'PropertyMock',
29
+ )
30
+
31
+
32
+ __version__ = '1.0.1'
33
+
34
+
35
+ import pprint
36
+ import sys
37
+
38
+ try:
39
+ import inspect
40
+ except ImportError:
41
+ # for alternative platforms that
42
+ # may not have inspect
43
+ inspect = None
44
+
45
+ try:
46
+ from functools import wraps as original_wraps
47
+ except ImportError:
48
+ # Python 2.4 compatibility
49
+ def wraps(original):
50
+ def inner(f):
51
+ f.__name__ = original.__name__
52
+ f.__doc__ = original.__doc__
53
+ f.__module__ = original.__module__
54
+ f.__wrapped__ = original
55
+ return f
56
+ return inner
57
+ else:
58
+ if sys.version_info[:2] >= (3, 3):
59
+ wraps = original_wraps
60
+ else:
61
+ def wraps(func):
62
+ def inner(f):
63
+ f = original_wraps(func)(f)
64
+ f.__wrapped__ = func
65
+ return f
66
+ return inner
67
+
68
+ try:
69
+ unicode
70
+ except NameError:
71
+ # Python 3
72
+ basestring = unicode = str
73
+
74
+ try:
75
+ long
76
+ except NameError:
77
+ # Python 3
78
+ long = int
79
+
80
+ try:
81
+ BaseException
82
+ except NameError:
83
+ # Python 2.4 compatibility
84
+ BaseException = Exception
85
+
86
+ try:
87
+ next
88
+ except NameError:
89
+ def next(obj):
90
+ return obj.next()
91
+
92
+
93
+ BaseExceptions = (BaseException,)
94
+ if 'java' in sys.platform:
95
+ # jython
96
+ import java
97
+ BaseExceptions = (BaseException, java.lang.Throwable)
98
+
99
+ try:
100
+ _isidentifier = str.isidentifier
101
+ except AttributeError:
102
+ # Python 2.X
103
+ import keyword
104
+ import re
105
+ regex = re.compile(r'^[a-z_][a-z0-9_]*$', re.I)
106
+ def _isidentifier(string):
107
+ if string in keyword.kwlist:
108
+ return False
109
+ return regex.match(string)
110
+
111
+
112
+ inPy3k = sys.version_info[0] == 3
113
+
114
+ # Needed to work around Python 3 bug where use of "super" interferes with
115
+ # defining __class__ as a descriptor
116
+ _super = super
117
+
118
+ self = 'im_self'
119
+ builtin = '__builtin__'
120
+ if inPy3k:
121
+ self = '__self__'
122
+ builtin = 'builtins'
123
+
124
+ FILTER_DIR = True
125
+
126
+
127
+ def _is_instance_mock(obj):
128
+ # can't use isinstance on Mock objects because they override __class__
129
+ # The base class for all mocks is NonCallableMock
130
+ return issubclass(type(obj), NonCallableMock)
131
+
132
+
133
+ def _is_exception(obj):
134
+ return (
135
+ isinstance(obj, BaseExceptions) or
136
+ isinstance(obj, ClassTypes) and issubclass(obj, BaseExceptions)
137
+ )
138
+
139
+
140
+ class _slotted(object):
141
+ __slots__ = ['a']
142
+
143
+
144
+ DescriptorTypes = (
145
+ type(_slotted.a),
146
+ property,
147
+ )
148
+
149
+
150
+ def _getsignature(func, skipfirst, instance=False):
151
+ if inspect is None:
152
+ raise ImportError('inspect module not available')
153
+
154
+ if isinstance(func, ClassTypes) and not instance:
155
+ try:
156
+ func = func.__init__
157
+ except AttributeError:
158
+ return
159
+ skipfirst = True
160
+ elif not isinstance(func, FunctionTypes):
161
+ # for classes where instance is True we end up here too
162
+ try:
163
+ func = func.__call__
164
+ except AttributeError:
165
+ return
166
+
167
+ if inPy3k:
168
+ try:
169
+ argspec = inspect.getfullargspec(func)
170
+ except TypeError:
171
+ # C function / method, possibly inherited object().__init__
172
+ return
173
+ regargs, varargs, varkw, defaults, kwonly, kwonlydef, ann = argspec
174
+ else:
175
+ try:
176
+ regargs, varargs, varkwargs, defaults = inspect.getargspec(func)
177
+ except TypeError:
178
+ # C function / method, possibly inherited object().__init__
179
+ return
180
+
181
+ # instance methods and classmethods need to lose the self argument
182
+ if getattr(func, self, None) is not None:
183
+ regargs = regargs[1:]
184
+ if skipfirst:
185
+ # this condition and the above one are never both True - why?
186
+ regargs = regargs[1:]
187
+
188
+ if inPy3k:
189
+ signature = inspect.formatargspec(
190
+ regargs, varargs, varkw, defaults,
191
+ kwonly, kwonlydef, ann, formatvalue=lambda value: "")
192
+ else:
193
+ signature = inspect.formatargspec(
194
+ regargs, varargs, varkwargs, defaults,
195
+ formatvalue=lambda value: "")
196
+ return signature[1:-1], func
197
+
198
+
199
+ def _check_signature(func, mock, skipfirst, instance=False):
200
+ if not _callable(func):
201
+ return
202
+
203
+ result = _getsignature(func, skipfirst, instance)
204
+ if result is None:
205
+ return
206
+ signature, func = result
207
+
208
+ # can't use self because "self" is common as an argument name
209
+ # unfortunately even not in the first place
210
+ src = "lambda _mock_self, %s: None" % signature
211
+ checksig = eval(src, {})
212
+ _copy_func_details(func, checksig)
213
+ type(mock)._mock_check_sig = checksig
214
+
215
+
216
+ def _copy_func_details(func, funcopy):
217
+ funcopy.__name__ = func.__name__
218
+ funcopy.__doc__ = func.__doc__
219
+ #funcopy.__dict__.update(func.__dict__)
220
+ funcopy.__module__ = func.__module__
221
+ if not inPy3k:
222
+ funcopy.func_defaults = func.func_defaults
223
+ return
224
+ funcopy.__defaults__ = func.__defaults__
225
+ funcopy.__kwdefaults__ = func.__kwdefaults__
226
+
227
+
228
+ def _callable(obj):
229
+ if isinstance(obj, ClassTypes):
230
+ return True
231
+ if getattr(obj, '__call__', None) is not None:
232
+ return True
233
+ return False
234
+
235
+
236
+ def _is_list(obj):
237
+ # checks for list or tuples
238
+ # XXXX badly named!
239
+ return type(obj) in (list, tuple)
240
+
241
+
242
+ def _instance_callable(obj):
243
+ """Given an object, return True if the object is callable.
244
+ For classes, return True if instances would be callable."""
245
+ if not isinstance(obj, ClassTypes):
246
+ # already an instance
247
+ return getattr(obj, '__call__', None) is not None
248
+
249
+ klass = obj
250
+ # uses __bases__ instead of __mro__ so that we work with old style classes
251
+ if klass.__dict__.get('__call__') is not None:
252
+ return True
253
+
254
+ for base in klass.__bases__:
255
+ if _instance_callable(base):
256
+ return True
257
+ return False
258
+
259
+
260
+ def _set_signature(mock, original, instance=False):
261
+ # creates a function with signature (*args, **kwargs) that delegates to a
262
+ # mock. It still does signature checking by calling a lambda with the same
263
+ # signature as the original.
264
+ if not _callable(original):
265
+ return
266
+
267
+ skipfirst = isinstance(original, ClassTypes)
268
+ result = _getsignature(original, skipfirst, instance)
269
+ if result is None:
270
+ # was a C function (e.g. object().__init__ ) that can't be mocked
271
+ return
272
+
273
+ signature, func = result
274
+
275
+ src = "lambda %s: None" % signature
276
+ checksig = eval(src, {})
277
+ _copy_func_details(func, checksig)
278
+
279
+ name = original.__name__
280
+ if not _isidentifier(name):
281
+ name = 'funcopy'
282
+ context = {'_checksig_': checksig, 'mock': mock}
283
+ src = """def %s(*args, **kwargs):
284
+ _checksig_(*args, **kwargs)
285
+ return mock(*args, **kwargs)""" % name
286
+ exec (src, context)
287
+ funcopy = context[name]
288
+ _setup_func(funcopy, mock)
289
+ return funcopy
290
+
291
+
292
+ def _setup_func(funcopy, mock):
293
+ funcopy.mock = mock
294
+
295
+ # can't use isinstance with mocks
296
+ if not _is_instance_mock(mock):
297
+ return
298
+
299
+ def assert_called_with(*args, **kwargs):
300
+ return mock.assert_called_with(*args, **kwargs)
301
+ def assert_called_once_with(*args, **kwargs):
302
+ return mock.assert_called_once_with(*args, **kwargs)
303
+ def assert_has_calls(*args, **kwargs):
304
+ return mock.assert_has_calls(*args, **kwargs)
305
+ def assert_any_call(*args, **kwargs):
306
+ return mock.assert_any_call(*args, **kwargs)
307
+ def reset_mock():
308
+ funcopy.method_calls = _CallList()
309
+ funcopy.mock_calls = _CallList()
310
+ mock.reset_mock()
311
+ ret = funcopy.return_value
312
+ if _is_instance_mock(ret) and not ret is mock:
313
+ ret.reset_mock()
314
+
315
+ funcopy.called = False
316
+ funcopy.call_count = 0
317
+ funcopy.call_args = None
318
+ funcopy.call_args_list = _CallList()
319
+ funcopy.method_calls = _CallList()
320
+ funcopy.mock_calls = _CallList()
321
+
322
+ funcopy.return_value = mock.return_value
323
+ funcopy.side_effect = mock.side_effect
324
+ funcopy._mock_children = mock._mock_children
325
+
326
+ funcopy.assert_called_with = assert_called_with
327
+ funcopy.assert_called_once_with = assert_called_once_with
328
+ funcopy.assert_has_calls = assert_has_calls
329
+ funcopy.assert_any_call = assert_any_call
330
+ funcopy.reset_mock = reset_mock
331
+
332
+ mock._mock_delegate = funcopy
333
+
334
+
335
+ def _is_magic(name):
336
+ return '__%s__' % name[2:-2] == name
337
+
338
+
339
+ class _SentinelObject(object):
340
+ "A unique, named, sentinel object."
341
+ def __init__(self, name):
342
+ self.name = name
343
+
344
+ def __repr__(self):
345
+ return 'sentinel.%s' % self.name
346
+
347
+
348
+ class _Sentinel(object):
349
+ """Access attributes to return a named object, usable as a sentinel."""
350
+ def __init__(self):
351
+ self._sentinels = {}
352
+
353
+ def __getattr__(self, name):
354
+ if name == '__bases__':
355
+ # Without this help(mock) raises an exception
356
+ raise AttributeError
357
+ return self._sentinels.setdefault(name, _SentinelObject(name))
358
+
359
+
360
+ sentinel = _Sentinel()
361
+
362
+ DEFAULT = sentinel.DEFAULT
363
+ _missing = sentinel.MISSING
364
+ _deleted = sentinel.DELETED
365
+
366
+
367
+ class OldStyleClass:
368
+ pass
369
+ ClassType = type(OldStyleClass)
370
+
371
+
372
+ def _copy(value):
373
+ if type(value) in (dict, list, tuple, set):
374
+ return type(value)(value)
375
+ return value
376
+
377
+
378
+ ClassTypes = (type,)
379
+ if not inPy3k:
380
+ ClassTypes = (type, ClassType)
381
+
382
+ _allowed_names = set(
383
+ [
384
+ 'return_value', '_mock_return_value', 'side_effect',
385
+ '_mock_side_effect', '_mock_parent', '_mock_new_parent',
386
+ '_mock_name', '_mock_new_name'
387
+ ]
388
+ )
389
+
390
+
391
+ def _delegating_property(name):
392
+ _allowed_names.add(name)
393
+ _the_name = '_mock_' + name
394
+ def _get(self, name=name, _the_name=_the_name):
395
+ sig = self._mock_delegate
396
+ if sig is None:
397
+ return getattr(self, _the_name)
398
+ return getattr(sig, name)
399
+ def _set(self, value, name=name, _the_name=_the_name):
400
+ sig = self._mock_delegate
401
+ if sig is None:
402
+ self.__dict__[_the_name] = value
403
+ else:
404
+ setattr(sig, name, value)
405
+
406
+ return property(_get, _set)
407
+
408
+
409
+
410
+ class _CallList(list):
411
+
412
+ def __contains__(self, value):
413
+ if not isinstance(value, list):
414
+ return list.__contains__(self, value)
415
+ len_value = len(value)
416
+ len_self = len(self)
417
+ if len_value > len_self:
418
+ return False
419
+
420
+ for i in range(0, len_self - len_value + 1):
421
+ sub_list = self[i:i+len_value]
422
+ if sub_list == value:
423
+ return True
424
+ return False
425
+
426
+ def __repr__(self):
427
+ return pprint.pformat(list(self))
428
+
429
+
430
+ def _check_and_set_parent(parent, value, name, new_name):
431
+ if not _is_instance_mock(value):
432
+ return False
433
+ if ((value._mock_name or value._mock_new_name) or
434
+ (value._mock_parent is not None) or
435
+ (value._mock_new_parent is not None)):
436
+ return False
437
+
438
+ _parent = parent
439
+ while _parent is not None:
440
+ # setting a mock (value) as a child or return value of itself
441
+ # should not modify the mock
442
+ if _parent is value:
443
+ return False
444
+ _parent = _parent._mock_new_parent
445
+
446
+ if new_name:
447
+ value._mock_new_parent = parent
448
+ value._mock_new_name = new_name
449
+ if name:
450
+ value._mock_parent = parent
451
+ value._mock_name = name
452
+ return True
453
+
454
+
455
+
456
+ class Base(object):
457
+ _mock_return_value = DEFAULT
458
+ _mock_side_effect = None
459
+ def __init__(self, *args, **kwargs):
460
+ pass
461
+
462
+
463
+
464
+ class NonCallableMock(Base):
465
+ """A non-callable version of `Mock`"""
466
+
467
+ def __new__(cls, *args, **kw):
468
+ # every instance has its own class
469
+ # so we can create magic methods on the
470
+ # class without stomping on other mocks
471
+ new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
472
+ instance = object.__new__(new)
473
+ return instance
474
+
475
+
476
+ def __init__(
477
+ self, spec=None, wraps=None, name=None, spec_set=None,
478
+ parent=None, _spec_state=None, _new_name='', _new_parent=None,
479
+ **kwargs
480
+ ):
481
+ if _new_parent is None:
482
+ _new_parent = parent
483
+
484
+ __dict__ = self.__dict__
485
+ __dict__['_mock_parent'] = parent
486
+ __dict__['_mock_name'] = name
487
+ __dict__['_mock_new_name'] = _new_name
488
+ __dict__['_mock_new_parent'] = _new_parent
489
+
490
+ if spec_set is not None:
491
+ spec = spec_set
492
+ spec_set = True
493
+
494
+ self._mock_add_spec(spec, spec_set)
495
+
496
+ __dict__['_mock_children'] = {}
497
+ __dict__['_mock_wraps'] = wraps
498
+ __dict__['_mock_delegate'] = None
499
+
500
+ __dict__['_mock_called'] = False
501
+ __dict__['_mock_call_args'] = None
502
+ __dict__['_mock_call_count'] = 0
503
+ __dict__['_mock_call_args_list'] = _CallList()
504
+ __dict__['_mock_mock_calls'] = _CallList()
505
+
506
+ __dict__['method_calls'] = _CallList()
507
+
508
+ if kwargs:
509
+ self.configure_mock(**kwargs)
510
+
511
+ _super(NonCallableMock, self).__init__(
512
+ spec, wraps, name, spec_set, parent,
513
+ _spec_state
514
+ )
515
+
516
+
517
+ def attach_mock(self, mock, attribute):
518
+ """
519
+ Attach a mock as an attribute of this one, replacing its name and
520
+ parent. Calls to the attached mock will be recorded in the
521
+ `method_calls` and `mock_calls` attributes of this one."""
522
+ mock._mock_parent = None
523
+ mock._mock_new_parent = None
524
+ mock._mock_name = ''
525
+ mock._mock_new_name = None
526
+
527
+ setattr(self, attribute, mock)
528
+
529
+
530
+ def mock_add_spec(self, spec, spec_set=False):
531
+ """Add a spec to a mock. `spec` can either be an object or a
532
+ list of strings. Only attributes on the `spec` can be fetched as
533
+ attributes from the mock.
534
+
535
+ If `spec_set` is True then only attributes on the spec can be set."""
536
+ self._mock_add_spec(spec, spec_set)
537
+
538
+
539
+ def _mock_add_spec(self, spec, spec_set):
540
+ _spec_class = None
541
+
542
+ if spec is not None and not _is_list(spec):
543
+ if isinstance(spec, ClassTypes):
544
+ _spec_class = spec
545
+ else:
546
+ _spec_class = _get_class(spec)
547
+
548
+ spec = dir(spec)
549
+
550
+ __dict__ = self.__dict__
551
+ __dict__['_spec_class'] = _spec_class
552
+ __dict__['_spec_set'] = spec_set
553
+ __dict__['_mock_methods'] = spec
554
+
555
+
556
+ def __get_return_value(self):
557
+ ret = self._mock_return_value
558
+ if self._mock_delegate is not None:
559
+ ret = self._mock_delegate.return_value
560
+
561
+ if ret is DEFAULT:
562
+ ret = self._get_child_mock(
563
+ _new_parent=self, _new_name='()'
564
+ )
565
+ self.return_value = ret
566
+ return ret
567
+
568
+
569
+ def __set_return_value(self, value):
570
+ if self._mock_delegate is not None:
571
+ self._mock_delegate.return_value = value
572
+ else:
573
+ self._mock_return_value = value
574
+ _check_and_set_parent(self, value, None, '()')
575
+
576
+ __return_value_doc = "The value to be returned when the mock is called."
577
+ return_value = property(__get_return_value, __set_return_value,
578
+ __return_value_doc)
579
+
580
+
581
+ @property
582
+ def __class__(self):
583
+ if self._spec_class is None:
584
+ return type(self)
585
+ return self._spec_class
586
+
587
+ called = _delegating_property('called')
588
+ call_count = _delegating_property('call_count')
589
+ call_args = _delegating_property('call_args')
590
+ call_args_list = _delegating_property('call_args_list')
591
+ mock_calls = _delegating_property('mock_calls')
592
+
593
+
594
+ def __get_side_effect(self):
595
+ sig = self._mock_delegate
596
+ if sig is None:
597
+ return self._mock_side_effect
598
+ return sig.side_effect
599
+
600
+ def __set_side_effect(self, value):
601
+ value = _try_iter(value)
602
+ sig = self._mock_delegate
603
+ if sig is None:
604
+ self._mock_side_effect = value
605
+ else:
606
+ sig.side_effect = value
607
+
608
+ side_effect = property(__get_side_effect, __set_side_effect)
609
+
610
+
611
+ def reset_mock(self):
612
+ "Restore the mock object to its initial state."
613
+ self.called = False
614
+ self.call_args = None
615
+ self.call_count = 0
616
+ self.mock_calls = _CallList()
617
+ self.call_args_list = _CallList()
618
+ self.method_calls = _CallList()
619
+
620
+ for child in self._mock_children.values():
621
+ if isinstance(child, _SpecState):
622
+ continue
623
+ child.reset_mock()
624
+
625
+ ret = self._mock_return_value
626
+ if _is_instance_mock(ret) and ret is not self:
627
+ ret.reset_mock()
628
+
629
+
630
+ def configure_mock(self, **kwargs):
631
+ """Set attributes on the mock through keyword arguments.
632
+
633
+ Attributes plus return values and side effects can be set on child
634
+ mocks using standard dot notation and unpacking a dictionary in the
635
+ method call:
636
+
637
+ >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
638
+ >>> mock.configure_mock(**attrs)"""
639
+ for arg, val in sorted(kwargs.items(),
640
+ # we sort on the number of dots so that
641
+ # attributes are set before we set attributes on
642
+ # attributes
643
+ key=lambda entry: entry[0].count('.')):
644
+ args = arg.split('.')
645
+ final = args.pop()
646
+ obj = self
647
+ for entry in args:
648
+ obj = getattr(obj, entry)
649
+ setattr(obj, final, val)
650
+
651
+
652
+ def __getattr__(self, name):
653
+ if name == '_mock_methods':
654
+ raise AttributeError(name)
655
+ elif self._mock_methods is not None:
656
+ if name not in self._mock_methods or name in _all_magics:
657
+ raise AttributeError("Mock object has no attribute %r" % name)
658
+ elif _is_magic(name):
659
+ raise AttributeError(name)
660
+
661
+ result = self._mock_children.get(name)
662
+ if result is _deleted:
663
+ raise AttributeError(name)
664
+ elif result is None:
665
+ wraps = None
666
+ if self._mock_wraps is not None:
667
+ # XXXX should we get the attribute without triggering code
668
+ # execution?
669
+ wraps = getattr(self._mock_wraps, name)
670
+
671
+ result = self._get_child_mock(
672
+ parent=self, name=name, wraps=wraps, _new_name=name,
673
+ _new_parent=self
674
+ )
675
+ self._mock_children[name] = result
676
+
677
+ elif isinstance(result, _SpecState):
678
+ result = create_autospec(
679
+ result.spec, result.spec_set, result.instance,
680
+ result.parent, result.name
681
+ )
682
+ self._mock_children[name] = result
683
+
684
+ return result
685
+
686
+
687
+ def __repr__(self):
688
+ _name_list = [self._mock_new_name]
689
+ _parent = self._mock_new_parent
690
+ last = self
691
+
692
+ dot = '.'
693
+ if _name_list == ['()']:
694
+ dot = ''
695
+ seen = set()
696
+ while _parent is not None:
697
+ last = _parent
698
+
699
+ _name_list.append(_parent._mock_new_name + dot)
700
+ dot = '.'
701
+ if _parent._mock_new_name == '()':
702
+ dot = ''
703
+
704
+ _parent = _parent._mock_new_parent
705
+
706
+ # use ids here so as not to call __hash__ on the mocks
707
+ if id(_parent) in seen:
708
+ break
709
+ seen.add(id(_parent))
710
+
711
+ _name_list = list(reversed(_name_list))
712
+ _first = last._mock_name or 'mock'
713
+ if len(_name_list) > 1:
714
+ if _name_list[1] not in ('()', '().'):
715
+ _first += '.'
716
+ _name_list[0] = _first
717
+ name = ''.join(_name_list)
718
+
719
+ name_string = ''
720
+ if name not in ('mock', 'mock.'):
721
+ name_string = ' name=%r' % name
722
+
723
+ spec_string = ''
724
+ if self._spec_class is not None:
725
+ spec_string = ' spec=%r'
726
+ if self._spec_set:
727
+ spec_string = ' spec_set=%r'
728
+ spec_string = spec_string % self._spec_class.__name__
729
+ return "<%s%s%s id='%s'>" % (
730
+ type(self).__name__,
731
+ name_string,
732
+ spec_string,
733
+ id(self)
734
+ )
735
+
736
+
737
+ def __dir__(self):
738
+ """Filter the output of `dir(mock)` to only useful members.
739
+ XXXX
740
+ """
741
+ extras = self._mock_methods or []
742
+ from_type = dir(type(self))
743
+ from_dict = list(self.__dict__)
744
+
745
+ if FILTER_DIR:
746
+ from_type = [e for e in from_type if not e.startswith('_')]
747
+ from_dict = [e for e in from_dict if not e.startswith('_') or
748
+ _is_magic(e)]
749
+ return sorted(set(extras + from_type + from_dict +
750
+ list(self._mock_children)))
751
+
752
+
753
+ def __setattr__(self, name, value):
754
+ if name in _allowed_names:
755
+ # property setters go through here
756
+ return object.__setattr__(self, name, value)
757
+ elif (self._spec_set and self._mock_methods is not None and
758
+ name not in self._mock_methods and
759
+ name not in self.__dict__):
760
+ raise AttributeError("Mock object has no attribute '%s'" % name)
761
+ elif name in _unsupported_magics:
762
+ msg = 'Attempting to set unsupported magic method %r.' % name
763
+ raise AttributeError(msg)
764
+ elif name in _all_magics:
765
+ if self._mock_methods is not None and name not in self._mock_methods:
766
+ raise AttributeError("Mock object has no attribute '%s'" % name)
767
+
768
+ if not _is_instance_mock(value):
769
+ setattr(type(self), name, _get_method(name, value))
770
+ original = value
771
+ value = lambda *args, **kw: original(self, *args, **kw)
772
+ else:
773
+ # only set _new_name and not name so that mock_calls is tracked
774
+ # but not method calls
775
+ _check_and_set_parent(self, value, None, name)
776
+ setattr(type(self), name, value)
777
+ self._mock_children[name] = value
778
+ elif name == '__class__':
779
+ self._spec_class = value
780
+ return
781
+ else:
782
+ if _check_and_set_parent(self, value, name, name):
783
+ self._mock_children[name] = value
784
+ return object.__setattr__(self, name, value)
785
+
786
+
787
+ def __delattr__(self, name):
788
+ if name in _all_magics and name in type(self).__dict__:
789
+ delattr(type(self), name)
790
+ if name not in self.__dict__:
791
+ # for magic methods that are still MagicProxy objects and
792
+ # not set on the instance itself
793
+ return
794
+
795
+ if name in self.__dict__:
796
+ object.__delattr__(self, name)
797
+
798
+ obj = self._mock_children.get(name, _missing)
799
+ if obj is _deleted:
800
+ raise AttributeError(name)
801
+ if obj is not _missing:
802
+ del self._mock_children[name]
803
+ self._mock_children[name] = _deleted
804
+
805
+
806
+
807
+ def _format_mock_call_signature(self, args, kwargs):
808
+ name = self._mock_name or 'mock'
809
+ return _format_call_signature(name, args, kwargs)
810
+
811
+
812
+ def _format_mock_failure_message(self, args, kwargs):
813
+ message = 'Expected call: %s\nActual call: %s'
814
+ expected_string = self._format_mock_call_signature(args, kwargs)
815
+ call_args = self.call_args
816
+ if len(call_args) == 3:
817
+ call_args = call_args[1:]
818
+ actual_string = self._format_mock_call_signature(*call_args)
819
+ return message % (expected_string, actual_string)
820
+
821
+
822
+ def assert_called_with(_mock_self, *args, **kwargs):
823
+ """assert that the mock was called with the specified arguments.
824
+
825
+ Raises an AssertionError if the args and keyword args passed in are
826
+ different to the last call to the mock."""
827
+ self = _mock_self
828
+ if self.call_args is None:
829
+ expected = self._format_mock_call_signature(args, kwargs)
830
+ raise AssertionError('Expected call: %s\nNot called' % (expected,))
831
+
832
+ if self.call_args != (args, kwargs):
833
+ msg = self._format_mock_failure_message(args, kwargs)
834
+ raise AssertionError(msg)
835
+
836
+
837
+ def assert_called_once_with(_mock_self, *args, **kwargs):
838
+ """assert that the mock was called exactly once and with the specified
839
+ arguments."""
840
+ self = _mock_self
841
+ if not self.call_count == 1:
842
+ msg = ("Expected to be called once. Called %s times." %
843
+ self.call_count)
844
+ raise AssertionError(msg)
845
+ return self.assert_called_with(*args, **kwargs)
846
+
847
+
848
+ def assert_has_calls(self, calls, any_order=False):
849
+ """assert the mock has been called with the specified calls.
850
+ The `mock_calls` list is checked for the calls.
851
+
852
+ If `any_order` is False (the default) then the calls must be
853
+ sequential. There can be extra calls before or after the
854
+ specified calls.
855
+
856
+ If `any_order` is True then the calls can be in any order, but
857
+ they must all appear in `mock_calls`."""
858
+ if not any_order:
859
+ if calls not in self.mock_calls:
860
+ raise AssertionError(
861
+ 'Calls not found.\nExpected: %r\n'
862
+ 'Actual: %r' % (calls, self.mock_calls)
863
+ )
864
+ return
865
+
866
+ all_calls = list(self.mock_calls)
867
+
868
+ not_found = []
869
+ for kall in calls:
870
+ try:
871
+ all_calls.remove(kall)
872
+ except ValueError:
873
+ not_found.append(kall)
874
+ if not_found:
875
+ raise AssertionError(
876
+ '%r not all found in call list' % (tuple(not_found),)
877
+ )
878
+
879
+
880
+ def assert_any_call(self, *args, **kwargs):
881
+ """assert the mock has been called with the specified arguments.
882
+
883
+ The assert passes if the mock has *ever* been called, unlike
884
+ `assert_called_with` and `assert_called_once_with` that only pass if
885
+ the call is the most recent one."""
886
+ kall = call(*args, **kwargs)
887
+ if kall not in self.call_args_list:
888
+ expected_string = self._format_mock_call_signature(args, kwargs)
889
+ raise AssertionError(
890
+ '%s call not found' % expected_string
891
+ )
892
+
893
+
894
+ def _get_child_mock(self, **kw):
895
+ """Create the child mocks for attributes and return value.
896
+ By default child mocks will be the same type as the parent.
897
+ Subclasses of Mock may want to override this to customize the way
898
+ child mocks are made.
899
+
900
+ For non-callable mocks the callable variant will be used (rather than
901
+ any custom subclass)."""
902
+ _type = type(self)
903
+ if not issubclass(_type, CallableMixin):
904
+ if issubclass(_type, NonCallableMagicMock):
905
+ klass = MagicMock
906
+ elif issubclass(_type, NonCallableMock) :
907
+ klass = Mock
908
+ else:
909
+ klass = _type.__mro__[1]
910
+ return klass(**kw)
911
+
912
+
913
+
914
+ def _try_iter(obj):
915
+ if obj is None:
916
+ return obj
917
+ if _is_exception(obj):
918
+ return obj
919
+ if _callable(obj):
920
+ return obj
921
+ try:
922
+ return iter(obj)
923
+ except TypeError:
924
+ # XXXX backwards compatibility
925
+ # but this will blow up on first call - so maybe we should fail early?
926
+ return obj
927
+
928
+
929
+
930
+ class CallableMixin(Base):
931
+
932
+ def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
933
+ wraps=None, name=None, spec_set=None, parent=None,
934
+ _spec_state=None, _new_name='', _new_parent=None, **kwargs):
935
+ self.__dict__['_mock_return_value'] = return_value
936
+
937
+ _super(CallableMixin, self).__init__(
938
+ spec, wraps, name, spec_set, parent,
939
+ _spec_state, _new_name, _new_parent, **kwargs
940
+ )
941
+
942
+ self.side_effect = side_effect
943
+
944
+
945
+ def _mock_check_sig(self, *args, **kwargs):
946
+ # stub method that can be replaced with one with a specific signature
947
+ pass
948
+
949
+
950
+ def __call__(_mock_self, *args, **kwargs):
951
+ # can't use self in-case a function / method we are mocking uses self
952
+ # in the signature
953
+ _mock_self._mock_check_sig(*args, **kwargs)
954
+ return _mock_self._mock_call(*args, **kwargs)
955
+
956
+
957
+ def _mock_call(_mock_self, *args, **kwargs):
958
+ self = _mock_self
959
+ self.called = True
960
+ self.call_count += 1
961
+ self.call_args = _Call((args, kwargs), two=True)
962
+ self.call_args_list.append(_Call((args, kwargs), two=True))
963
+
964
+ _new_name = self._mock_new_name
965
+ _new_parent = self._mock_new_parent
966
+ self.mock_calls.append(_Call(('', args, kwargs)))
967
+
968
+ seen = set()
969
+ skip_next_dot = _new_name == '()'
970
+ do_method_calls = self._mock_parent is not None
971
+ name = self._mock_name
972
+ while _new_parent is not None:
973
+ this_mock_call = _Call((_new_name, args, kwargs))
974
+ if _new_parent._mock_new_name:
975
+ dot = '.'
976
+ if skip_next_dot:
977
+ dot = ''
978
+
979
+ skip_next_dot = False
980
+ if _new_parent._mock_new_name == '()':
981
+ skip_next_dot = True
982
+
983
+ _new_name = _new_parent._mock_new_name + dot + _new_name
984
+
985
+ if do_method_calls:
986
+ if _new_name == name:
987
+ this_method_call = this_mock_call
988
+ else:
989
+ this_method_call = _Call((name, args, kwargs))
990
+ _new_parent.method_calls.append(this_method_call)
991
+
992
+ do_method_calls = _new_parent._mock_parent is not None
993
+ if do_method_calls:
994
+ name = _new_parent._mock_name + '.' + name
995
+
996
+ _new_parent.mock_calls.append(this_mock_call)
997
+ _new_parent = _new_parent._mock_new_parent
998
+
999
+ # use ids here so as not to call __hash__ on the mocks
1000
+ _new_parent_id = id(_new_parent)
1001
+ if _new_parent_id in seen:
1002
+ break
1003
+ seen.add(_new_parent_id)
1004
+
1005
+ ret_val = DEFAULT
1006
+ effect = self.side_effect
1007
+ if effect is not None:
1008
+ if _is_exception(effect):
1009
+ raise effect
1010
+
1011
+ if not _callable(effect):
1012
+ result = next(effect)
1013
+ if _is_exception(result):
1014
+ raise result
1015
+ return result
1016
+
1017
+ ret_val = effect(*args, **kwargs)
1018
+ if ret_val is DEFAULT:
1019
+ ret_val = self.return_value
1020
+
1021
+ if (self._mock_wraps is not None and
1022
+ self._mock_return_value is DEFAULT):
1023
+ return self._mock_wraps(*args, **kwargs)
1024
+ if ret_val is DEFAULT:
1025
+ ret_val = self.return_value
1026
+ return ret_val
1027
+
1028
+
1029
+
1030
+ class Mock(CallableMixin, NonCallableMock):
1031
+ """
1032
+ Create a new `Mock` object. `Mock` takes several optional arguments
1033
+ that specify the behaviour of the Mock object:
1034
+
1035
+ * `spec`: This can be either a list of strings or an existing object (a
1036
+ class or instance) that acts as the specification for the mock object. If
1037
+ you pass in an object then a list of strings is formed by calling dir on
1038
+ the object (excluding unsupported magic attributes and methods). Accessing
1039
+ any attribute not in this list will raise an `AttributeError`.
1040
+
1041
+ If `spec` is an object (rather than a list of strings) then
1042
+ `mock.__class__` returns the class of the spec object. This allows mocks
1043
+ to pass `isinstance` tests.
1044
+
1045
+ * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1046
+ or get an attribute on the mock that isn't on the object passed as
1047
+ `spec_set` will raise an `AttributeError`.
1048
+
1049
+ * `side_effect`: A function to be called whenever the Mock is called. See
1050
+ the `side_effect` attribute. Useful for raising exceptions or
1051
+ dynamically changing return values. The function is called with the same
1052
+ arguments as the mock, and unless it returns `DEFAULT`, the return
1053
+ value of this function is used as the return value.
1054
+
1055
+ Alternatively `side_effect` can be an exception class or instance. In
1056
+ this case the exception will be raised when the mock is called.
1057
+
1058
+ If `side_effect` is an iterable then each call to the mock will return
1059
+ the next value from the iterable. If any of the members of the iterable
1060
+ are exceptions they will be raised instead of returned.
1061
+
1062
+ * `return_value`: The value returned when the mock is called. By default
1063
+ this is a new Mock (created on first access). See the
1064
+ `return_value` attribute.
1065
+
1066
+ * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1067
+ calling the Mock will pass the call through to the wrapped object
1068
+ (returning the real result). Attribute access on the mock will return a
1069
+ Mock object that wraps the corresponding attribute of the wrapped object
1070
+ (so attempting to access an attribute that doesn't exist will raise an
1071
+ `AttributeError`).
1072
+
1073
+ If the mock has an explicit `return_value` set then calls are not passed
1074
+ to the wrapped object and the `return_value` is returned instead.
1075
+
1076
+ * `name`: If the mock has a name then it will be used in the repr of the
1077
+ mock. This can be useful for debugging. The name is propagated to child
1078
+ mocks.
1079
+
1080
+ Mocks can also be called with arbitrary keyword arguments. These will be
1081
+ used to set attributes on the mock after it is created.
1082
+ """
1083
+
1084
+
1085
+
1086
+ def _dot_lookup(thing, comp, import_path):
1087
+ try:
1088
+ return getattr(thing, comp)
1089
+ except AttributeError:
1090
+ __import__(import_path)
1091
+ return getattr(thing, comp)
1092
+
1093
+
1094
+ def _importer(target):
1095
+ components = target.split('.')
1096
+ import_path = components.pop(0)
1097
+ thing = __import__(import_path)
1098
+
1099
+ for comp in components:
1100
+ import_path += ".%s" % comp
1101
+ thing = _dot_lookup(thing, comp, import_path)
1102
+ return thing
1103
+
1104
+
1105
+ def _is_started(patcher):
1106
+ # XXXX horrible
1107
+ return hasattr(patcher, 'is_local')
1108
+
1109
+
1110
+ class _patch(object):
1111
+
1112
+ attribute_name = None
1113
+ _active_patches = set()
1114
+
1115
+ def __init__(
1116
+ self, getter, attribute, new, spec, create,
1117
+ spec_set, autospec, new_callable, kwargs
1118
+ ):
1119
+ if new_callable is not None:
1120
+ if new is not DEFAULT:
1121
+ raise ValueError(
1122
+ "Cannot use 'new' and 'new_callable' together"
1123
+ )
1124
+ if autospec is not None:
1125
+ raise ValueError(
1126
+ "Cannot use 'autospec' and 'new_callable' together"
1127
+ )
1128
+
1129
+ self.getter = getter
1130
+ self.attribute = attribute
1131
+ self.new = new
1132
+ self.new_callable = new_callable
1133
+ self.spec = spec
1134
+ self.create = create
1135
+ self.has_local = False
1136
+ self.spec_set = spec_set
1137
+ self.autospec = autospec
1138
+ self.kwargs = kwargs
1139
+ self.additional_patchers = []
1140
+
1141
+
1142
+ def copy(self):
1143
+ patcher = _patch(
1144
+ self.getter, self.attribute, self.new, self.spec,
1145
+ self.create, self.spec_set,
1146
+ self.autospec, self.new_callable, self.kwargs
1147
+ )
1148
+ patcher.attribute_name = self.attribute_name
1149
+ patcher.additional_patchers = [
1150
+ p.copy() for p in self.additional_patchers
1151
+ ]
1152
+ return patcher
1153
+
1154
+
1155
+ def __call__(self, func):
1156
+ if isinstance(func, ClassTypes):
1157
+ return self.decorate_class(func)
1158
+ return self.decorate_callable(func)
1159
+
1160
+
1161
+ def decorate_class(self, klass):
1162
+ for attr in dir(klass):
1163
+ if not attr.startswith(patch.TEST_PREFIX):
1164
+ continue
1165
+
1166
+ attr_value = getattr(klass, attr)
1167
+ if not hasattr(attr_value, "__call__"):
1168
+ continue
1169
+
1170
+ patcher = self.copy()
1171
+ setattr(klass, attr, patcher(attr_value))
1172
+ return klass
1173
+
1174
+
1175
+ def decorate_callable(self, func):
1176
+ if hasattr(func, 'patchings'):
1177
+ func.patchings.append(self)
1178
+ return func
1179
+
1180
+ @wraps(func)
1181
+ def patched(*args, **keywargs):
1182
+ # don't use a with here (backwards compatability with Python 2.4)
1183
+ extra_args = []
1184
+ entered_patchers = []
1185
+
1186
+ # can't use try...except...finally because of Python 2.4
1187
+ # compatibility
1188
+ exc_info = tuple()
1189
+ try:
1190
+ try:
1191
+ for patching in patched.patchings:
1192
+ arg = patching.__enter__()
1193
+ entered_patchers.append(patching)
1194
+ if patching.attribute_name is not None:
1195
+ keywargs.update(arg)
1196
+ elif patching.new is DEFAULT:
1197
+ extra_args.append(arg)
1198
+
1199
+ args += tuple(extra_args)
1200
+ return func(*args, **keywargs)
1201
+ except:
1202
+ if (patching not in entered_patchers and
1203
+ _is_started(patching)):
1204
+ # the patcher may have been started, but an exception
1205
+ # raised whilst entering one of its additional_patchers
1206
+ entered_patchers.append(patching)
1207
+ # Pass the exception to __exit__
1208
+ exc_info = sys.exc_info()
1209
+ # re-raise the exception
1210
+ raise
1211
+ finally:
1212
+ for patching in reversed(entered_patchers):
1213
+ patching.__exit__(*exc_info)
1214
+
1215
+ patched.patchings = [self]
1216
+ if hasattr(func, 'func_code'):
1217
+ # not in Python 3
1218
+ patched.compat_co_firstlineno = getattr(
1219
+ func, "compat_co_firstlineno",
1220
+ func.func_code.co_firstlineno
1221
+ )
1222
+ return patched
1223
+
1224
+
1225
+ def get_original(self):
1226
+ target = self.getter()
1227
+ name = self.attribute
1228
+
1229
+ original = DEFAULT
1230
+ local = False
1231
+
1232
+ try:
1233
+ original = target.__dict__[name]
1234
+ except (AttributeError, KeyError):
1235
+ original = getattr(target, name, DEFAULT)
1236
+ else:
1237
+ local = True
1238
+
1239
+ if not self.create and original is DEFAULT:
1240
+ raise AttributeError(
1241
+ "%s does not have the attribute %r" % (target, name)
1242
+ )
1243
+ return original, local
1244
+
1245
+
1246
+ def __enter__(self):
1247
+ """Perform the patch."""
1248
+ new, spec, spec_set = self.new, self.spec, self.spec_set
1249
+ autospec, kwargs = self.autospec, self.kwargs
1250
+ new_callable = self.new_callable
1251
+ self.target = self.getter()
1252
+
1253
+ # normalise False to None
1254
+ if spec is False:
1255
+ spec = None
1256
+ if spec_set is False:
1257
+ spec_set = None
1258
+ if autospec is False:
1259
+ autospec = None
1260
+
1261
+ if spec is not None and autospec is not None:
1262
+ raise TypeError("Can't specify spec and autospec")
1263
+ if ((spec is not None or autospec is not None) and
1264
+ spec_set not in (True, None)):
1265
+ raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1266
+
1267
+ original, local = self.get_original()
1268
+
1269
+ if new is DEFAULT and autospec is None:
1270
+ inherit = False
1271
+ if spec is True:
1272
+ # set spec to the object we are replacing
1273
+ spec = original
1274
+ if spec_set is True:
1275
+ spec_set = original
1276
+ spec = None
1277
+ elif spec is not None:
1278
+ if spec_set is True:
1279
+ spec_set = spec
1280
+ spec = None
1281
+ elif spec_set is True:
1282
+ spec_set = original
1283
+
1284
+ if spec is not None or spec_set is not None:
1285
+ if original is DEFAULT:
1286
+ raise TypeError("Can't use 'spec' with create=True")
1287
+ if isinstance(original, ClassTypes):
1288
+ # If we're patching out a class and there is a spec
1289
+ inherit = True
1290
+
1291
+ Klass = MagicMock
1292
+ _kwargs = {}
1293
+ if new_callable is not None:
1294
+ Klass = new_callable
1295
+ elif spec is not None or spec_set is not None:
1296
+ this_spec = spec
1297
+ if spec_set is not None:
1298
+ this_spec = spec_set
1299
+ if _is_list(this_spec):
1300
+ not_callable = '__call__' not in this_spec
1301
+ else:
1302
+ not_callable = not _callable(this_spec)
1303
+ if not_callable:
1304
+ Klass = NonCallableMagicMock
1305
+
1306
+ if spec is not None:
1307
+ _kwargs['spec'] = spec
1308
+ if spec_set is not None:
1309
+ _kwargs['spec_set'] = spec_set
1310
+
1311
+ # add a name to mocks
1312
+ if (isinstance(Klass, type) and
1313
+ issubclass(Klass, NonCallableMock) and self.attribute):
1314
+ _kwargs['name'] = self.attribute
1315
+
1316
+ _kwargs.update(kwargs)
1317
+ new = Klass(**_kwargs)
1318
+
1319
+ if inherit and _is_instance_mock(new):
1320
+ # we can only tell if the instance should be callable if the
1321
+ # spec is not a list
1322
+ this_spec = spec
1323
+ if spec_set is not None:
1324
+ this_spec = spec_set
1325
+ if (not _is_list(this_spec) and not
1326
+ _instance_callable(this_spec)):
1327
+ Klass = NonCallableMagicMock
1328
+
1329
+ _kwargs.pop('name')
1330
+ new.return_value = Klass(_new_parent=new, _new_name='()',
1331
+ **_kwargs)
1332
+ elif autospec is not None:
1333
+ # spec is ignored, new *must* be default, spec_set is treated
1334
+ # as a boolean. Should we check spec is not None and that spec_set
1335
+ # is a bool?
1336
+ if new is not DEFAULT:
1337
+ raise TypeError(
1338
+ "autospec creates the mock for you. Can't specify "
1339
+ "autospec and new."
1340
+ )
1341
+ if original is DEFAULT:
1342
+ raise TypeError("Can't use 'autospec' with create=True")
1343
+ spec_set = bool(spec_set)
1344
+ if autospec is True:
1345
+ autospec = original
1346
+
1347
+ new = create_autospec(autospec, spec_set=spec_set,
1348
+ _name=self.attribute, **kwargs)
1349
+ elif kwargs:
1350
+ # can't set keyword args when we aren't creating the mock
1351
+ # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1352
+ raise TypeError("Can't pass kwargs to a mock we aren't creating")
1353
+
1354
+ new_attr = new
1355
+
1356
+ self.temp_original = original
1357
+ self.is_local = local
1358
+ setattr(self.target, self.attribute, new_attr)
1359
+ if self.attribute_name is not None:
1360
+ extra_args = {}
1361
+ if self.new is DEFAULT:
1362
+ extra_args[self.attribute_name] = new
1363
+ for patching in self.additional_patchers:
1364
+ arg = patching.__enter__()
1365
+ if patching.new is DEFAULT:
1366
+ extra_args.update(arg)
1367
+ return extra_args
1368
+
1369
+ return new
1370
+
1371
+
1372
+ def __exit__(self, *exc_info):
1373
+ """Undo the patch."""
1374
+ if not _is_started(self):
1375
+ raise RuntimeError('stop called on unstarted patcher')
1376
+
1377
+ if self.is_local and self.temp_original is not DEFAULT:
1378
+ setattr(self.target, self.attribute, self.temp_original)
1379
+ else:
1380
+ delattr(self.target, self.attribute)
1381
+ if not self.create and not hasattr(self.target, self.attribute):
1382
+ # needed for proxy objects like django settings
1383
+ setattr(self.target, self.attribute, self.temp_original)
1384
+
1385
+ del self.temp_original
1386
+ del self.is_local
1387
+ del self.target
1388
+ for patcher in reversed(self.additional_patchers):
1389
+ if _is_started(patcher):
1390
+ patcher.__exit__(*exc_info)
1391
+
1392
+
1393
+ def start(self):
1394
+ """Activate a patch, returning any created mock."""
1395
+ result = self.__enter__()
1396
+ self._active_patches.add(self)
1397
+ return result
1398
+
1399
+
1400
+ def stop(self):
1401
+ """Stop an active patch."""
1402
+ self._active_patches.discard(self)
1403
+ return self.__exit__()
1404
+
1405
+
1406
+
1407
+ def _get_target(target):
1408
+ try:
1409
+ target, attribute = target.rsplit('.', 1)
1410
+ except (TypeError, ValueError):
1411
+ raise TypeError("Need a valid target to patch. You supplied: %r" %
1412
+ (target,))
1413
+ getter = lambda: _importer(target)
1414
+ return getter, attribute
1415
+
1416
+
1417
+ def _patch_object(
1418
+ target, attribute, new=DEFAULT, spec=None,
1419
+ create=False, spec_set=None, autospec=None,
1420
+ new_callable=None, **kwargs
1421
+ ):
1422
+ """
1423
+ patch.object(target, attribute, new=DEFAULT, spec=None, create=False,
1424
+ spec_set=None, autospec=None, new_callable=None, **kwargs)
1425
+
1426
+ patch the named member (`attribute`) on an object (`target`) with a mock
1427
+ object.
1428
+
1429
+ `patch.object` can be used as a decorator, class decorator or a context
1430
+ manager. Arguments `new`, `spec`, `create`, `spec_set`,
1431
+ `autospec` and `new_callable` have the same meaning as for `patch`. Like
1432
+ `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1433
+ the mock object it creates.
1434
+
1435
+ When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1436
+ for choosing which methods to wrap.
1437
+ """
1438
+ getter = lambda: target
1439
+ return _patch(
1440
+ getter, attribute, new, spec, create,
1441
+ spec_set, autospec, new_callable, kwargs
1442
+ )
1443
+
1444
+
1445
+ def _patch_multiple(target, spec=None, create=False, spec_set=None,
1446
+ autospec=None, new_callable=None, **kwargs):
1447
+ """Perform multiple patches in a single call. It takes the object to be
1448
+ patched (either as an object or a string to fetch the object by importing)
1449
+ and keyword arguments for the patches::
1450
+
1451
+ with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1452
+ ...
1453
+
1454
+ Use `DEFAULT` as the value if you want `patch.multiple` to create
1455
+ mocks for you. In this case the created mocks are passed into a decorated
1456
+ function by keyword, and a dictionary is returned when `patch.multiple` is
1457
+ used as a context manager.
1458
+
1459
+ `patch.multiple` can be used as a decorator, class decorator or a context
1460
+ manager. The arguments `spec`, `spec_set`, `create`,
1461
+ `autospec` and `new_callable` have the same meaning as for `patch`. These
1462
+ arguments will be applied to *all* patches done by `patch.multiple`.
1463
+
1464
+ When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1465
+ for choosing which methods to wrap.
1466
+ """
1467
+ if type(target) in (unicode, str):
1468
+ getter = lambda: _importer(target)
1469
+ else:
1470
+ getter = lambda: target
1471
+
1472
+ if not kwargs:
1473
+ raise ValueError(
1474
+ 'Must supply at least one keyword argument with patch.multiple'
1475
+ )
1476
+ # need to wrap in a list for python 3, where items is a view
1477
+ items = list(kwargs.items())
1478
+ attribute, new = items[0]
1479
+ patcher = _patch(
1480
+ getter, attribute, new, spec, create, spec_set,
1481
+ autospec, new_callable, {}
1482
+ )
1483
+ patcher.attribute_name = attribute
1484
+ for attribute, new in items[1:]:
1485
+ this_patcher = _patch(
1486
+ getter, attribute, new, spec, create, spec_set,
1487
+ autospec, new_callable, {}
1488
+ )
1489
+ this_patcher.attribute_name = attribute
1490
+ patcher.additional_patchers.append(this_patcher)
1491
+ return patcher
1492
+
1493
+
1494
+ def patch(
1495
+ target, new=DEFAULT, spec=None, create=False,
1496
+ spec_set=None, autospec=None, new_callable=None, **kwargs
1497
+ ):
1498
+ """
1499
+ `patch` acts as a function decorator, class decorator or a context
1500
+ manager. Inside the body of the function or with statement, the `target`
1501
+ is patched with a `new` object. When the function/with statement exits
1502
+ the patch is undone.
1503
+
1504
+ If `new` is omitted, then the target is replaced with a
1505
+ `MagicMock`. If `patch` is used as a decorator and `new` is
1506
+ omitted, the created mock is passed in as an extra argument to the
1507
+ decorated function. If `patch` is used as a context manager the created
1508
+ mock is returned by the context manager.
1509
+
1510
+ `target` should be a string in the form `'package.module.ClassName'`. The
1511
+ `target` is imported and the specified object replaced with the `new`
1512
+ object, so the `target` must be importable from the environment you are
1513
+ calling `patch` from. The target is imported when the decorated function
1514
+ is executed, not at decoration time.
1515
+
1516
+ The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1517
+ if patch is creating one for you.
1518
+
1519
+ In addition you can pass `spec=True` or `spec_set=True`, which causes
1520
+ patch to pass in the object being mocked as the spec/spec_set object.
1521
+
1522
+ `new_callable` allows you to specify a different class, or callable object,
1523
+ that will be called to create the `new` object. By default `MagicMock` is
1524
+ used.
1525
+
1526
+ A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1527
+ then the mock with be created with a spec from the object being replaced.
1528
+ All attributes of the mock will also have the spec of the corresponding
1529
+ attribute of the object being replaced. Methods and functions being
1530
+ mocked will have their arguments checked and will raise a `TypeError` if
1531
+ they are called with the wrong signature. For mocks replacing a class,
1532
+ their return value (the 'instance') will have the same spec as the class.
1533
+
1534
+ Instead of `autospec=True` you can pass `autospec=some_object` to use an
1535
+ arbitrary object as the spec instead of the one being replaced.
1536
+
1537
+ By default `patch` will fail to replace attributes that don't exist. If
1538
+ you pass in `create=True`, and the attribute doesn't exist, patch will
1539
+ create the attribute for you when the patched function is called, and
1540
+ delete it again afterwards. This is useful for writing tests against
1541
+ attributes that your production code creates at runtime. It is off by by
1542
+ default because it can be dangerous. With it switched on you can write
1543
+ passing tests against APIs that don't actually exist!
1544
+
1545
+ Patch can be used as a `TestCase` class decorator. It works by
1546
+ decorating each test method in the class. This reduces the boilerplate
1547
+ code when your test methods share a common patchings set. `patch` finds
1548
+ tests by looking for method names that start with `patch.TEST_PREFIX`.
1549
+ By default this is `test`, which matches the way `unittest` finds tests.
1550
+ You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1551
+
1552
+ Patch can be used as a context manager, with the with statement. Here the
1553
+ patching applies to the indented block after the with statement. If you
1554
+ use "as" then the patched object will be bound to the name after the
1555
+ "as"; very useful if `patch` is creating a mock object for you.
1556
+
1557
+ `patch` takes arbitrary keyword arguments. These will be passed to
1558
+ the `Mock` (or `new_callable`) on construction.
1559
+
1560
+ `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1561
+ available for alternate use-cases.
1562
+ """
1563
+ getter, attribute = _get_target(target)
1564
+ return _patch(
1565
+ getter, attribute, new, spec, create,
1566
+ spec_set, autospec, new_callable, kwargs
1567
+ )
1568
+
1569
+
1570
+ class _patch_dict(object):
1571
+ """
1572
+ Patch a dictionary, or dictionary like object, and restore the dictionary
1573
+ to its original state after the test.
1574
+
1575
+ `in_dict` can be a dictionary or a mapping like container. If it is a
1576
+ mapping then it must at least support getting, setting and deleting items
1577
+ plus iterating over keys.
1578
+
1579
+ `in_dict` can also be a string specifying the name of the dictionary, which
1580
+ will then be fetched by importing it.
1581
+
1582
+ `values` can be a dictionary of values to set in the dictionary. `values`
1583
+ can also be an iterable of `(key, value)` pairs.
1584
+
1585
+ If `clear` is True then the dictionary will be cleared before the new
1586
+ values are set.
1587
+
1588
+ `patch.dict` can also be called with arbitrary keyword arguments to set
1589
+ values in the dictionary::
1590
+
1591
+ with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1592
+ ...
1593
+
1594
+ `patch.dict` can be used as a context manager, decorator or class
1595
+ decorator. When used as a class decorator `patch.dict` honours
1596
+ `patch.TEST_PREFIX` for choosing which methods to wrap.
1597
+ """
1598
+
1599
+ def __init__(self, in_dict, values=(), clear=False, **kwargs):
1600
+ if isinstance(in_dict, basestring):
1601
+ in_dict = _importer(in_dict)
1602
+ self.in_dict = in_dict
1603
+ # support any argument supported by dict(...) constructor
1604
+ self.values = dict(values)
1605
+ self.values.update(kwargs)
1606
+ self.clear = clear
1607
+ self._original = None
1608
+
1609
+
1610
+ def __call__(self, f):
1611
+ if isinstance(f, ClassTypes):
1612
+ return self.decorate_class(f)
1613
+ @wraps(f)
1614
+ def _inner(*args, **kw):
1615
+ self._patch_dict()
1616
+ try:
1617
+ return f(*args, **kw)
1618
+ finally:
1619
+ self._unpatch_dict()
1620
+
1621
+ return _inner
1622
+
1623
+
1624
+ def decorate_class(self, klass):
1625
+ for attr in dir(klass):
1626
+ attr_value = getattr(klass, attr)
1627
+ if (attr.startswith(patch.TEST_PREFIX) and
1628
+ hasattr(attr_value, "__call__")):
1629
+ decorator = _patch_dict(self.in_dict, self.values, self.clear)
1630
+ decorated = decorator(attr_value)
1631
+ setattr(klass, attr, decorated)
1632
+ return klass
1633
+
1634
+
1635
+ def __enter__(self):
1636
+ """Patch the dict."""
1637
+ self._patch_dict()
1638
+
1639
+
1640
+ def _patch_dict(self):
1641
+ values = self.values
1642
+ in_dict = self.in_dict
1643
+ clear = self.clear
1644
+
1645
+ try:
1646
+ original = in_dict.copy()
1647
+ except AttributeError:
1648
+ # dict like object with no copy method
1649
+ # must support iteration over keys
1650
+ original = {}
1651
+ for key in in_dict:
1652
+ original[key] = in_dict[key]
1653
+ self._original = original
1654
+
1655
+ if clear:
1656
+ _clear_dict(in_dict)
1657
+
1658
+ try:
1659
+ in_dict.update(values)
1660
+ except AttributeError:
1661
+ # dict like object with no update method
1662
+ for key in values:
1663
+ in_dict[key] = values[key]
1664
+
1665
+
1666
+ def _unpatch_dict(self):
1667
+ in_dict = self.in_dict
1668
+ original = self._original
1669
+
1670
+ _clear_dict(in_dict)
1671
+
1672
+ try:
1673
+ in_dict.update(original)
1674
+ except AttributeError:
1675
+ for key in original:
1676
+ in_dict[key] = original[key]
1677
+
1678
+
1679
+ def __exit__(self, *args):
1680
+ """Unpatch the dict."""
1681
+ self._unpatch_dict()
1682
+ return False
1683
+
1684
+ start = __enter__
1685
+ stop = __exit__
1686
+
1687
+
1688
+ def _clear_dict(in_dict):
1689
+ try:
1690
+ in_dict.clear()
1691
+ except AttributeError:
1692
+ keys = list(in_dict)
1693
+ for key in keys:
1694
+ del in_dict[key]
1695
+
1696
+
1697
+ def _patch_stopall():
1698
+ """Stop all active patches."""
1699
+ for patch in list(_patch._active_patches):
1700
+ patch.stop()
1701
+
1702
+
1703
+ patch.object = _patch_object
1704
+ patch.dict = _patch_dict
1705
+ patch.multiple = _patch_multiple
1706
+ patch.stopall = _patch_stopall
1707
+ patch.TEST_PREFIX = 'test'
1708
+
1709
+ magic_methods = (
1710
+ "lt le gt ge eq ne "
1711
+ "getitem setitem delitem "
1712
+ "len contains iter "
1713
+ "hash str sizeof "
1714
+ "enter exit "
1715
+ "divmod neg pos abs invert "
1716
+ "complex int float index "
1717
+ "trunc floor ceil "
1718
+ )
1719
+
1720
+ numerics = "add sub mul div floordiv mod lshift rshift and xor or pow "
1721
+ inplace = ' '.join('i%s' % n for n in numerics.split())
1722
+ right = ' '.join('r%s' % n for n in numerics.split())
1723
+ extra = ''
1724
+ if inPy3k:
1725
+ extra = 'bool next '
1726
+ else:
1727
+ extra = 'unicode long nonzero oct hex truediv rtruediv '
1728
+
1729
+ # not including __prepare__, __instancecheck__, __subclasscheck__
1730
+ # (as they are metaclass methods)
1731
+ # __del__ is not supported at all as it causes problems if it exists
1732
+
1733
+ _non_defaults = set('__%s__' % method for method in [
1734
+ 'cmp', 'getslice', 'setslice', 'coerce', 'subclasses',
1735
+ 'format', 'get', 'set', 'delete', 'reversed',
1736
+ 'missing', 'reduce', 'reduce_ex', 'getinitargs',
1737
+ 'getnewargs', 'getstate', 'setstate', 'getformat',
1738
+ 'setformat', 'repr', 'dir'
1739
+ ])
1740
+
1741
+
1742
+ def _get_method(name, func):
1743
+ "Turns a callable object (like a mock) into a real function"
1744
+ def method(self, *args, **kw):
1745
+ return func(self, *args, **kw)
1746
+ method.__name__ = name
1747
+ return method
1748
+
1749
+
1750
+ _magics = set(
1751
+ '__%s__' % method for method in
1752
+ ' '.join([magic_methods, numerics, inplace, right, extra]).split()
1753
+ )
1754
+
1755
+ _all_magics = _magics | _non_defaults
1756
+
1757
+ _unsupported_magics = set([
1758
+ '__getattr__', '__setattr__',
1759
+ '__init__', '__new__', '__prepare__'
1760
+ '__instancecheck__', '__subclasscheck__',
1761
+ '__del__'
1762
+ ])
1763
+
1764
+ _calculate_return_value = {
1765
+ '__hash__': lambda self: object.__hash__(self),
1766
+ '__str__': lambda self: object.__str__(self),
1767
+ '__sizeof__': lambda self: object.__sizeof__(self),
1768
+ '__unicode__': lambda self: unicode(object.__str__(self)),
1769
+ }
1770
+
1771
+ _return_values = {
1772
+ '__lt__': NotImplemented,
1773
+ '__gt__': NotImplemented,
1774
+ '__le__': NotImplemented,
1775
+ '__ge__': NotImplemented,
1776
+ '__int__': 1,
1777
+ '__contains__': False,
1778
+ '__len__': 0,
1779
+ '__exit__': False,
1780
+ '__complex__': 1j,
1781
+ '__float__': 1.0,
1782
+ '__bool__': True,
1783
+ '__nonzero__': True,
1784
+ '__oct__': '1',
1785
+ '__hex__': '0x1',
1786
+ '__long__': long(1),
1787
+ '__index__': 1,
1788
+ }
1789
+
1790
+
1791
+ def _get_eq(self):
1792
+ def __eq__(other):
1793
+ ret_val = self.__eq__._mock_return_value
1794
+ if ret_val is not DEFAULT:
1795
+ return ret_val
1796
+ return self is other
1797
+ return __eq__
1798
+
1799
+ def _get_ne(self):
1800
+ def __ne__(other):
1801
+ if self.__ne__._mock_return_value is not DEFAULT:
1802
+ return DEFAULT
1803
+ return self is not other
1804
+ return __ne__
1805
+
1806
+ def _get_iter(self):
1807
+ def __iter__():
1808
+ ret_val = self.__iter__._mock_return_value
1809
+ if ret_val is DEFAULT:
1810
+ return iter([])
1811
+ # if ret_val was already an iterator, then calling iter on it should
1812
+ # return the iterator unchanged
1813
+ return iter(ret_val)
1814
+ return __iter__
1815
+
1816
+ _side_effect_methods = {
1817
+ '__eq__': _get_eq,
1818
+ '__ne__': _get_ne,
1819
+ '__iter__': _get_iter,
1820
+ }
1821
+
1822
+
1823
+
1824
+ def _set_return_value(mock, method, name):
1825
+ fixed = _return_values.get(name, DEFAULT)
1826
+ if fixed is not DEFAULT:
1827
+ method.return_value = fixed
1828
+ return
1829
+
1830
+ return_calulator = _calculate_return_value.get(name)
1831
+ if return_calulator is not None:
1832
+ try:
1833
+ return_value = return_calulator(mock)
1834
+ except AttributeError:
1835
+ # XXXX why do we return AttributeError here?
1836
+ # set it as a side_effect instead?
1837
+ return_value = AttributeError(name)
1838
+ method.return_value = return_value
1839
+ return
1840
+
1841
+ side_effector = _side_effect_methods.get(name)
1842
+ if side_effector is not None:
1843
+ method.side_effect = side_effector(mock)
1844
+
1845
+
1846
+
1847
+ class MagicMixin(object):
1848
+ def __init__(self, *args, **kw):
1849
+ _super(MagicMixin, self).__init__(*args, **kw)
1850
+ self._mock_set_magics()
1851
+
1852
+
1853
+ def _mock_set_magics(self):
1854
+ these_magics = _magics
1855
+
1856
+ if self._mock_methods is not None:
1857
+ these_magics = _magics.intersection(self._mock_methods)
1858
+
1859
+ remove_magics = set()
1860
+ remove_magics = _magics - these_magics
1861
+
1862
+ for entry in remove_magics:
1863
+ if entry in type(self).__dict__:
1864
+ # remove unneeded magic methods
1865
+ delattr(self, entry)
1866
+
1867
+ # don't overwrite existing attributes if called a second time
1868
+ these_magics = these_magics - set(type(self).__dict__)
1869
+
1870
+ _type = type(self)
1871
+ for entry in these_magics:
1872
+ setattr(_type, entry, MagicProxy(entry, self))
1873
+
1874
+
1875
+
1876
+ class NonCallableMagicMock(MagicMixin, NonCallableMock):
1877
+ """A version of `MagicMock` that isn't callable."""
1878
+ def mock_add_spec(self, spec, spec_set=False):
1879
+ """Add a spec to a mock. `spec` can either be an object or a
1880
+ list of strings. Only attributes on the `spec` can be fetched as
1881
+ attributes from the mock.
1882
+
1883
+ If `spec_set` is True then only attributes on the spec can be set."""
1884
+ self._mock_add_spec(spec, spec_set)
1885
+ self._mock_set_magics()
1886
+
1887
+
1888
+
1889
+ class MagicMock(MagicMixin, Mock):
1890
+ """
1891
+ MagicMock is a subclass of Mock with default implementations
1892
+ of most of the magic methods. You can use MagicMock without having to
1893
+ configure the magic methods yourself.
1894
+
1895
+ If you use the `spec` or `spec_set` arguments then *only* magic
1896
+ methods that exist in the spec will be created.
1897
+
1898
+ Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1899
+ """
1900
+ def mock_add_spec(self, spec, spec_set=False):
1901
+ """Add a spec to a mock. `spec` can either be an object or a
1902
+ list of strings. Only attributes on the `spec` can be fetched as
1903
+ attributes from the mock.
1904
+
1905
+ If `spec_set` is True then only attributes on the spec can be set."""
1906
+ self._mock_add_spec(spec, spec_set)
1907
+ self._mock_set_magics()
1908
+
1909
+
1910
+
1911
+ class MagicProxy(object):
1912
+ def __init__(self, name, parent):
1913
+ self.name = name
1914
+ self.parent = parent
1915
+
1916
+ def __call__(self, *args, **kwargs):
1917
+ m = self.create_mock()
1918
+ return m(*args, **kwargs)
1919
+
1920
+ def create_mock(self):
1921
+ entry = self.name
1922
+ parent = self.parent
1923
+ m = parent._get_child_mock(name=entry, _new_name=entry,
1924
+ _new_parent=parent)
1925
+ setattr(parent, entry, m)
1926
+ _set_return_value(parent, m, entry)
1927
+ return m
1928
+
1929
+ def __get__(self, obj, _type=None):
1930
+ return self.create_mock()
1931
+
1932
+
1933
+
1934
+ class _ANY(object):
1935
+ "A helper object that compares equal to everything."
1936
+
1937
+ def __eq__(self, other):
1938
+ return True
1939
+
1940
+ def __ne__(self, other):
1941
+ return False
1942
+
1943
+ def __repr__(self):
1944
+ return '<ANY>'
1945
+
1946
+ ANY = _ANY()
1947
+
1948
+
1949
+
1950
+ def _format_call_signature(name, args, kwargs):
1951
+ message = '%s(%%s)' % name
1952
+ formatted_args = ''
1953
+ args_string = ', '.join([repr(arg) for arg in args])
1954
+ kwargs_string = ', '.join([
1955
+ '%s=%r' % (key, value) for key, value in kwargs.items()
1956
+ ])
1957
+ if args_string:
1958
+ formatted_args = args_string
1959
+ if kwargs_string:
1960
+ if formatted_args:
1961
+ formatted_args += ', '
1962
+ formatted_args += kwargs_string
1963
+
1964
+ return message % formatted_args
1965
+
1966
+
1967
+
1968
+ class _Call(tuple):
1969
+ """
1970
+ A tuple for holding the results of a call to a mock, either in the form
1971
+ `(args, kwargs)` or `(name, args, kwargs)`.
1972
+
1973
+ If args or kwargs are empty then a call tuple will compare equal to
1974
+ a tuple without those values. This makes comparisons less verbose::
1975
+
1976
+ _Call(('name', (), {})) == ('name',)
1977
+ _Call(('name', (1,), {})) == ('name', (1,))
1978
+ _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1979
+
1980
+ The `_Call` object provides a useful shortcut for comparing with call::
1981
+
1982
+ _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1983
+ _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1984
+
1985
+ If the _Call has no name then it will match any name.
1986
+ """
1987
+ def __new__(cls, value=(), name=None, parent=None, two=False,
1988
+ from_kall=True):
1989
+ name = ''
1990
+ args = ()
1991
+ kwargs = {}
1992
+ _len = len(value)
1993
+ if _len == 3:
1994
+ name, args, kwargs = value
1995
+ elif _len == 2:
1996
+ first, second = value
1997
+ if isinstance(first, basestring):
1998
+ name = first
1999
+ if isinstance(second, tuple):
2000
+ args = second
2001
+ else:
2002
+ kwargs = second
2003
+ else:
2004
+ args, kwargs = first, second
2005
+ elif _len == 1:
2006
+ value, = value
2007
+ if isinstance(value, basestring):
2008
+ name = value
2009
+ elif isinstance(value, tuple):
2010
+ args = value
2011
+ else:
2012
+ kwargs = value
2013
+
2014
+ if two:
2015
+ return tuple.__new__(cls, (args, kwargs))
2016
+
2017
+ return tuple.__new__(cls, (name, args, kwargs))
2018
+
2019
+
2020
+ def __init__(self, value=(), name=None, parent=None, two=False,
2021
+ from_kall=True):
2022
+ self.name = name
2023
+ self.parent = parent
2024
+ self.from_kall = from_kall
2025
+
2026
+
2027
+ def __eq__(self, other):
2028
+ if other is ANY:
2029
+ return True
2030
+ try:
2031
+ len_other = len(other)
2032
+ except TypeError:
2033
+ return False
2034
+
2035
+ self_name = ''
2036
+ if len(self) == 2:
2037
+ self_args, self_kwargs = self
2038
+ else:
2039
+ self_name, self_args, self_kwargs = self
2040
+
2041
+ other_name = ''
2042
+ if len_other == 0:
2043
+ other_args, other_kwargs = (), {}
2044
+ elif len_other == 3:
2045
+ other_name, other_args, other_kwargs = other
2046
+ elif len_other == 1:
2047
+ value, = other
2048
+ if isinstance(value, tuple):
2049
+ other_args = value
2050
+ other_kwargs = {}
2051
+ elif isinstance(value, basestring):
2052
+ other_name = value
2053
+ other_args, other_kwargs = (), {}
2054
+ else:
2055
+ other_args = ()
2056
+ other_kwargs = value
2057
+ else:
2058
+ # len 2
2059
+ # could be (name, args) or (name, kwargs) or (args, kwargs)
2060
+ first, second = other
2061
+ if isinstance(first, basestring):
2062
+ other_name = first
2063
+ if isinstance(second, tuple):
2064
+ other_args, other_kwargs = second, {}
2065
+ else:
2066
+ other_args, other_kwargs = (), second
2067
+ else:
2068
+ other_args, other_kwargs = first, second
2069
+
2070
+ if self_name and other_name != self_name:
2071
+ return False
2072
+
2073
+ # this order is important for ANY to work!
2074
+ return (other_args, other_kwargs) == (self_args, self_kwargs)
2075
+
2076
+
2077
+ def __ne__(self, other):
2078
+ return not self.__eq__(other)
2079
+
2080
+
2081
+ def __call__(self, *args, **kwargs):
2082
+ if self.name is None:
2083
+ return _Call(('', args, kwargs), name='()')
2084
+
2085
+ name = self.name + '()'
2086
+ return _Call((self.name, args, kwargs), name=name, parent=self)
2087
+
2088
+
2089
+ def __getattr__(self, attr):
2090
+ if self.name is None:
2091
+ return _Call(name=attr, from_kall=False)
2092
+ name = '%s.%s' % (self.name, attr)
2093
+ return _Call(name=name, parent=self, from_kall=False)
2094
+
2095
+
2096
+ def __repr__(self):
2097
+ if not self.from_kall:
2098
+ name = self.name or 'call'
2099
+ if name.startswith('()'):
2100
+ name = 'call%s' % name
2101
+ return name
2102
+
2103
+ if len(self) == 2:
2104
+ name = 'call'
2105
+ args, kwargs = self
2106
+ else:
2107
+ name, args, kwargs = self
2108
+ if not name:
2109
+ name = 'call'
2110
+ elif not name.startswith('()'):
2111
+ name = 'call.%s' % name
2112
+ else:
2113
+ name = 'call%s' % name
2114
+ return _format_call_signature(name, args, kwargs)
2115
+
2116
+
2117
+ def call_list(self):
2118
+ """For a call object that represents multiple calls, `call_list`
2119
+ returns a list of all the intermediate calls as well as the
2120
+ final call."""
2121
+ vals = []
2122
+ thing = self
2123
+ while thing is not None:
2124
+ if thing.from_kall:
2125
+ vals.append(thing)
2126
+ thing = thing.parent
2127
+ return _CallList(reversed(vals))
2128
+
2129
+
2130
+ call = _Call(from_kall=False)
2131
+
2132
+
2133
+
2134
+ def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2135
+ _name=None, **kwargs):
2136
+ """Create a mock object using another object as a spec. Attributes on the
2137
+ mock will use the corresponding attribute on the `spec` object as their
2138
+ spec.
2139
+
2140
+ Functions or methods being mocked will have their arguments checked
2141
+ to check that they are called with the correct signature.
2142
+
2143
+ If `spec_set` is True then attempting to set attributes that don't exist
2144
+ on the spec object will raise an `AttributeError`.
2145
+
2146
+ If a class is used as a spec then the return value of the mock (the
2147
+ instance of the class) will have the same spec. You can use a class as the
2148
+ spec for an instance object by passing `instance=True`. The returned mock
2149
+ will only be callable if instances of the mock are callable.
2150
+
2151
+ `create_autospec` also takes arbitrary keyword arguments that are passed to
2152
+ the constructor of the created mock."""
2153
+ if _is_list(spec):
2154
+ # can't pass a list instance to the mock constructor as it will be
2155
+ # interpreted as a list of strings
2156
+ spec = type(spec)
2157
+
2158
+ is_type = isinstance(spec, ClassTypes)
2159
+
2160
+ _kwargs = {'spec': spec}
2161
+ if spec_set:
2162
+ _kwargs = {'spec_set': spec}
2163
+ elif spec is None:
2164
+ # None we mock with a normal mock without a spec
2165
+ _kwargs = {}
2166
+
2167
+ _kwargs.update(kwargs)
2168
+
2169
+ Klass = MagicMock
2170
+ if type(spec) in DescriptorTypes:
2171
+ # descriptors don't have a spec
2172
+ # because we don't know what type they return
2173
+ _kwargs = {}
2174
+ elif not _callable(spec):
2175
+ Klass = NonCallableMagicMock
2176
+ elif is_type and instance and not _instance_callable(spec):
2177
+ Klass = NonCallableMagicMock
2178
+
2179
+ _new_name = _name
2180
+ if _parent is None:
2181
+ # for a top level object no _new_name should be set
2182
+ _new_name = ''
2183
+
2184
+ mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2185
+ name=_name, **_kwargs)
2186
+
2187
+ if isinstance(spec, FunctionTypes):
2188
+ # should only happen at the top level because we don't
2189
+ # recurse for functions
2190
+ mock = _set_signature(mock, spec)
2191
+ else:
2192
+ _check_signature(spec, mock, is_type, instance)
2193
+
2194
+ if _parent is not None and not instance:
2195
+ _parent._mock_children[_name] = mock
2196
+
2197
+ if is_type and not instance and 'return_value' not in kwargs:
2198
+ mock.return_value = create_autospec(spec, spec_set, instance=True,
2199
+ _name='()', _parent=mock)
2200
+
2201
+ for entry in dir(spec):
2202
+ if _is_magic(entry):
2203
+ # MagicMock already does the useful magic methods for us
2204
+ continue
2205
+
2206
+ if isinstance(spec, FunctionTypes) and entry in FunctionAttributes:
2207
+ # allow a mock to actually be a function
2208
+ continue
2209
+
2210
+ # XXXX do we need a better way of getting attributes without
2211
+ # triggering code execution (?) Probably not - we need the actual
2212
+ # object to mock it so we would rather trigger a property than mock
2213
+ # the property descriptor. Likewise we want to mock out dynamically
2214
+ # provided attributes.
2215
+ # XXXX what about attributes that raise exceptions other than
2216
+ # AttributeError on being fetched?
2217
+ # we could be resilient against it, or catch and propagate the
2218
+ # exception when the attribute is fetched from the mock
2219
+ try:
2220
+ original = getattr(spec, entry)
2221
+ except AttributeError:
2222
+ continue
2223
+
2224
+ kwargs = {'spec': original}
2225
+ if spec_set:
2226
+ kwargs = {'spec_set': original}
2227
+
2228
+ if not isinstance(original, FunctionTypes):
2229
+ new = _SpecState(original, spec_set, mock, entry, instance)
2230
+ mock._mock_children[entry] = new
2231
+ else:
2232
+ parent = mock
2233
+ if isinstance(spec, FunctionTypes):
2234
+ parent = mock.mock
2235
+
2236
+ new = MagicMock(parent=parent, name=entry, _new_name=entry,
2237
+ _new_parent=parent, **kwargs)
2238
+ mock._mock_children[entry] = new
2239
+ skipfirst = _must_skip(spec, entry, is_type)
2240
+ _check_signature(original, new, skipfirst=skipfirst)
2241
+
2242
+ # so functions created with _set_signature become instance attributes,
2243
+ # *plus* their underlying mock exists in _mock_children of the parent
2244
+ # mock. Adding to _mock_children may be unnecessary where we are also
2245
+ # setting as an instance attribute?
2246
+ if isinstance(new, FunctionTypes):
2247
+ setattr(mock, entry, new)
2248
+
2249
+ return mock
2250
+
2251
+
2252
+ def _must_skip(spec, entry, is_type):
2253
+ if not isinstance(spec, ClassTypes):
2254
+ if entry in getattr(spec, '__dict__', {}):
2255
+ # instance attribute - shouldn't skip
2256
+ return False
2257
+ spec = spec.__class__
2258
+ if not hasattr(spec, '__mro__'):
2259
+ # old style class: can't have descriptors anyway
2260
+ return is_type
2261
+
2262
+ for klass in spec.__mro__:
2263
+ result = klass.__dict__.get(entry, DEFAULT)
2264
+ if result is DEFAULT:
2265
+ continue
2266
+ if isinstance(result, (staticmethod, classmethod)):
2267
+ return False
2268
+ return is_type
2269
+
2270
+ # shouldn't get here unless function is a dynamically provided attribute
2271
+ # XXXX untested behaviour
2272
+ return is_type
2273
+
2274
+
2275
+ def _get_class(obj):
2276
+ try:
2277
+ return obj.__class__
2278
+ except AttributeError:
2279
+ # in Python 2, _sre.SRE_Pattern objects have no __class__
2280
+ return type(obj)
2281
+
2282
+
2283
+ class _SpecState(object):
2284
+
2285
+ def __init__(self, spec, spec_set=False, parent=None,
2286
+ name=None, ids=None, instance=False):
2287
+ self.spec = spec
2288
+ self.ids = ids
2289
+ self.spec_set = spec_set
2290
+ self.parent = parent
2291
+ self.instance = instance
2292
+ self.name = name
2293
+
2294
+
2295
+ FunctionTypes = (
2296
+ # python function
2297
+ type(create_autospec),
2298
+ # instance method
2299
+ type(ANY.__eq__),
2300
+ # unbound method
2301
+ type(_ANY.__eq__),
2302
+ )
2303
+
2304
+ FunctionAttributes = set([
2305
+ 'func_closure',
2306
+ 'func_code',
2307
+ 'func_defaults',
2308
+ 'func_dict',
2309
+ 'func_doc',
2310
+ 'func_globals',
2311
+ 'func_name',
2312
+ ])
2313
+
2314
+
2315
+ file_spec = None
2316
+
2317
+
2318
+ def mock_open(mock=None, read_data=''):
2319
+ """
2320
+ A helper function to create a mock to replace the use of `open`. It works
2321
+ for `open` called directly or used as a context manager.
2322
+
2323
+ The `mock` argument is the mock object to configure. If `None` (the
2324
+ default) then a `MagicMock` will be created for you, with the API limited
2325
+ to methods or attributes available on standard file handles.
2326
+
2327
+ `read_data` is a string for the `read` method of the file handle to return.
2328
+ This is an empty string by default.
2329
+ """
2330
+ global file_spec
2331
+ if file_spec is None:
2332
+ # set on first use
2333
+ if inPy3k:
2334
+ import _io
2335
+ file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2336
+ else:
2337
+ file_spec = file
2338
+
2339
+ if mock is None:
2340
+ mock = MagicMock(name='open', spec=open)
2341
+
2342
+ handle = MagicMock(spec=file_spec)
2343
+ handle.write.return_value = None
2344
+ handle.__enter__.return_value = handle
2345
+ handle.read.return_value = read_data
2346
+
2347
+ mock.return_value = handle
2348
+ return mock
2349
+
2350
+
2351
+ class PropertyMock(Mock):
2352
+ """
2353
+ A mock intended to be used as a property, or other descriptor, on a class.
2354
+ `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2355
+ a return value when it is fetched.
2356
+
2357
+ Fetching a `PropertyMock` instance from an object calls the mock, with
2358
+ no args. Setting it calls the mock with the value being set.
2359
+ """
2360
+ def _get_child_mock(self, **kwargs):
2361
+ return MagicMock(**kwargs)
2362
+
2363
+ def __get__(self, obj, obj_type):
2364
+ return self()
2365
+ def __set__(self, obj, val):
2366
+ self(val)