Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
b582c923
Commit
b582c923
authored
Apr 21, 2012
by
Brett Cannon
Browse files
Options
Browse Files
Download
Plain Diff
merge
parents
a64faf07
9cf5c9d8
Changes
6
Hide whitespace changes
Inline
Side-by-side
Showing
6 changed files
with
61 additions
and
61 deletions
+61
-61
Doc/library/inspect.rst
Doc/library/inspect.rst
+9
-4
Doc/library/unittest.mock-examples.rst
Doc/library/unittest.mock-examples.rst
+0
-50
Doc/library/unittest.mock.rst
Doc/library/unittest.mock.rst
+14
-0
Lib/unittest/mock.py
Lib/unittest/mock.py
+14
-6
Lib/unittest/test/testmock/testhelpers.py
Lib/unittest/test/testmock/testhelpers.py
+14
-1
Lib/unittest/test/testmock/testmock.py
Lib/unittest/test/testmock/testmock.py
+10
-0
No files found.
Doc/library/inspect.rst
View file @
b582c923
...
@@ -440,11 +440,16 @@ Classes and functions
...
@@ -440,11 +440,16 @@ Classes and functions
locals dictionary of the given frame.
locals dictionary of the given frame.
.. function:: formatargspec(args[, varargs, varkw, defaults,
formatarg, formatvarargs, formatvarkw, formatvalue
])
.. function:: formatargspec(args[, varargs, varkw, defaults,
kwonlyargs, kwonlydefaults, annotations, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations
])
Format a pretty argument spec from the four values returned by
Format a pretty argument spec from the values returned by
:func:`getargspec`. The format\* arguments are the corresponding optional
:func:`getargspec` or :func:`getfullargspec`.
formatting functions that are called to turn names and values into strings.
The first seven arguments are (``args``, ``varargs``, ``varkw``,
``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``). The
other five arguments are the corresponding optional formatting functions
that are called to turn names and values into strings. The last argument
is an optional function to format the sequence of arguments.
.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
...
...
Doc/library/unittest.mock-examples.rst
View file @
b582c923
...
@@ -838,56 +838,6 @@ and the `return_value` will use your subclass automatically. That means all
...
@@ -838,56 +838,6 @@ and the `return_value` will use your subclass automatically. That means all
children of a `CopyingMock` will also have the type `CopyingMock`.
children of a `CopyingMock` will also have the type `CopyingMock`.
Multiple calls with different effects
-------------------------------------
Handling code that needs to behave differently on subsequent calls during the
test can be tricky. For example you may have a function that needs to raise
an exception the first time it is called but returns a response on the second
call (testing retry behaviour).
One approach is to use a :attr:`side_effect` function that replaces itself. The
first time it is called the `side_effect` sets a new `side_effect` that will
be used for the second call. It then raises an exception:
>>> def side_effect(*args):
... def second_call(*args):
... return 'response'
... mock.side_effect = second_call
... raise Exception('boom')
...
>>> mock = Mock(side_effect=side_effect)
>>> mock('first')
Traceback (most recent call last):
...
Exception: boom
>>> mock('second')
'response'
>>> mock.assert_called_with('second')
Another perfectly valid way would be to pop return values from a list. If the
return value is an exception, raise it instead of returning it:
>>> returns = [Exception('boom'), 'response']
>>> def side_effect(*args):
... result = returns.pop(0)
... if isinstance(result, Exception):
... raise result
... return result
...
>>> mock = Mock(side_effect=side_effect)
>>> mock('first')
Traceback (most recent call last):
...
Exception: boom
>>> mock('second')
'response'
>>> mock.assert_called_with('second')
Which approach you prefer is a matter of taste. The first approach is actually
a line shorter but maybe the second approach is more readable.
Nesting Patches
Nesting Patches
---------------
---------------
...
...
Doc/library/unittest.mock.rst
View file @
b582c923
...
@@ -823,6 +823,20 @@ a `StopIteration` is raised):
...
@@ -823,6 +823,20 @@ a `StopIteration` is raised):
...
...
StopIteration
StopIteration
If any members of the iterable are exceptions they will be raised instead of
returned::
>>> iterable = (33, ValueError, 66)
>>> m = MagicMock(side_effect=iterable)
>>> m()
33
>>> m()
Traceback (most recent call last):
...
ValueError
>>> m()
66
.. _deleting-attributes:
.. _deleting-attributes:
...
...
Lib/unittest/mock.py
View file @
b582c923
...
@@ -78,11 +78,14 @@ def _getsignature(func, skipfirst, instance=False):
...
@@ -78,11 +78,14 @@ def _getsignature(func, skipfirst, instance=False):
return
return
try
:
try
:
regargs
,
varargs
,
varkwargs
,
defaults
=
inspect
.
get
argspec
(
func
)
argspec
=
inspect
.
getfull
argspec
(
func
)
except
TypeError
:
except
TypeError
:
# C function / method, possibly inherited object().__init__
# C function / method, possibly inherited object().__init__
return
return
regargs
,
varargs
,
varkw
,
defaults
,
kwonly
,
kwonlydef
,
ann
=
argspec
# instance methods and classmethods need to lose the self argument
# instance methods and classmethods need to lose the self argument
if
getattr
(
func
,
'__self__'
,
None
)
is
not
None
:
if
getattr
(
func
,
'__self__'
,
None
)
is
not
None
:
regargs
=
regargs
[
1
:]
regargs
=
regargs
[
1
:]
...
@@ -90,8 +93,9 @@ def _getsignature(func, skipfirst, instance=False):
...
@@ -90,8 +93,9 @@ def _getsignature(func, skipfirst, instance=False):
# this condition and the above one are never both True - why?
# this condition and the above one are never both True - why?
regargs
=
regargs
[
1
:]
regargs
=
regargs
[
1
:]
signature
=
inspect
.
formatargspec
(
regargs
,
varargs
,
varkwargs
,
defaults
,
signature
=
inspect
.
formatargspec
(
formatvalue
=
lambda
value
:
""
)
regargs
,
varargs
,
varkw
,
defaults
,
kwonly
,
kwonlydef
,
ann
,
formatvalue
=
lambda
value
:
""
)
return
signature
[
1
:
-
1
],
func
return
signature
[
1
:
-
1
],
func
...
@@ -891,7 +895,10 @@ class CallableMixin(Base):
...
@@ -891,7 +895,10 @@ class CallableMixin(Base):
raise
effect
raise
effect
if
not
_callable
(
effect
):
if
not
_callable
(
effect
):
return
next
(
effect
)
result
=
next
(
effect
)
if
_is_exception
(
result
):
raise
result
return
result
ret_val
=
effect
(
*
args
,
**
kwargs
)
ret_val
=
effect
(
*
args
,
**
kwargs
)
if
ret_val
is
DEFAULT
:
if
ret_val
is
DEFAULT
:
...
@@ -931,8 +938,9 @@ class Mock(CallableMixin, NonCallableMock):
...
@@ -931,8 +938,9 @@ class Mock(CallableMixin, NonCallableMock):
arguments as the mock, and unless it returns `DEFAULT`, the return
arguments as the mock, and unless it returns `DEFAULT`, the return
value of this function is used as the return value.
value of this function is used as the return value.
Alternatively `side_effect` can be an exception class or instance. In
If `side_effect` is an iterable then each call to the mock will return
this case the exception will be raised when the mock is called.
the next value from the iterable. If any of the members of the iterable
are exceptions they will be raised instead of returned.
If `side_effect` is an iterable then each call to the mock will return
If `side_effect` is an iterable then each call to the mock will return
the next value from the iterable.
the next value from the iterable.
...
...
Lib/unittest/test/testmock/testhelpers.py
View file @
b582c923
...
@@ -367,7 +367,7 @@ class SpecSignatureTest(unittest.TestCase):
...
@@ -367,7 +367,7 @@ class SpecSignatureTest(unittest.TestCase):
def
test_create_autospec_unbound_methods
(
self
):
def
test_create_autospec_unbound_methods
(
self
):
# see issue 128
# see
mock
issue 128
# this is expected to fail until the issue is fixed
# this is expected to fail until the issue is fixed
return
return
class
Foo
(
object
):
class
Foo
(
object
):
...
@@ -391,6 +391,19 @@ class SpecSignatureTest(unittest.TestCase):
...
@@ -391,6 +391,19 @@ class SpecSignatureTest(unittest.TestCase):
self
.
assertEqual
(
m
.
a
,
'3'
)
self
.
assertEqual
(
m
.
a
,
'3'
)
def
test_create_autospec_keyword_only_arguments
(
self
):
def
foo
(
a
,
*
,
b
=
None
):
pass
m
=
create_autospec
(
foo
)
m
(
1
)
m
.
assert_called_with
(
1
)
self
.
assertRaises
(
TypeError
,
m
,
1
,
2
)
m
(
2
,
b
=
3
)
m
.
assert_called_with
(
2
,
b
=
3
)
def
test_function_as_instance_attribute
(
self
):
def
test_function_as_instance_attribute
(
self
):
obj
=
SomeClass
()
obj
=
SomeClass
()
def
f
(
a
):
def
f
(
a
):
...
...
Lib/unittest/test/testmock/testmock.py
View file @
b582c923
...
@@ -868,6 +868,16 @@ class MockTest(unittest.TestCase):
...
@@ -868,6 +868,16 @@ class MockTest(unittest.TestCase):
self
.
assertRaises
(
StopIteration
,
mock
)
self
.
assertRaises
(
StopIteration
,
mock
)
def
test_side_effect_iterator_exceptions
(
self
):
for
Klass
in
Mock
,
MagicMock
:
iterable
=
(
ValueError
,
3
,
KeyError
,
6
)
m
=
Klass
(
side_effect
=
iterable
)
self
.
assertRaises
(
ValueError
,
m
)
self
.
assertEqual
(
m
(),
3
)
self
.
assertRaises
(
KeyError
,
m
)
self
.
assertEqual
(
m
(),
6
)
def
test_side_effect_setting_iterator
(
self
):
def
test_side_effect_setting_iterator
(
self
):
mock
=
Mock
()
mock
=
Mock
()
mock
.
side_effect
=
iter
([
1
,
2
,
3
])
mock
.
side_effect
=
iter
([
1
,
2
,
3
])
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment