Commit Graph

153 Commits

Author SHA1 Message Date
Christian Clauss 745c9d9dfc
Fix typos in the Lib directory (GH-28775)
Fix typos in the Lib directory as identified by codespell.

Co-authored-by: Terry Jan Reedy <tjreedy@udel.edu>
2021-10-06 16:13:48 -07:00
Nikita Sobolev 7f60c9e1c6
bpo-45156: Fixes inifite loop on unittest.mock.seal() (GH-28300)
Fixes infinite loop on unittest.mock.seal() of mocks created by
unittest.create_autospec().

Co-authored-by: Dong-hee Na <donghee.na92@gmail.com>
2021-09-14 12:20:40 +02:00
Dong-hee Na 698e9a8211
bpo-44017: Update test_contextlib_async not to emit DeprecationWarn (GH-25918) 2021-05-06 23:10:52 +09:00
Matthew Suozzo dccdc500f9
bpo-43478: Restrict use of Mock objects as specs (GH-25326)
* Restrict using Mock objects as specs as this is always a test bug where the resulting mock is misleadingly useless.
* Skip a broken test that exposes a bug elsewhere in mock (noted in the original issue).
2021-04-09 20:45:50 -07:00
vabr-g fdb9efce6a
bpo-41877: Check for misspelled speccing arguments (GH-23737)
patch, patch.object and create_autospec silently ignore misspelled
arguments such as autospect, auto_spec and set_spec. This can lead
to tests failing to check what they are supposed to check.

This change adds a check causing a RuntimeError if the above
functions get any of the above misspellings as arguments. It also
adds a new argument, "unsafe", which can be set to True to disable
this check.

Also add "!r" to format specifiers in added error messages.
2020-12-14 10:30:09 -08:00
vabr-g 9fc571359a
bpo-41877: Improve docs for assert misspellings check in mock (GH-23729)
This is a follow-up to
4662fa9bfe.
That original commit expanded guards against misspelling assertions on
mocks. This follow-up updates the documentation and improves the error
message by pointing out the potential cause and solution.

Automerge-Triggered-By: GH:gpshead
2020-12-10 10:35:28 -08:00
idanw206 c598a04dd2
bpo-42532: Check if NonCallableMock's spec_arg is not None instead of call its __bool__ function (GH23613)
Check if NonCallableMock's spec_arg is not None instead of call its __bool__ function
2020-12-06 09:59:36 +00:00
vabr-g 4662fa9bfe
bpo-41877 Check for asert, aseert, assrt in mocks (GH-23165)
Currently, a Mock object which is not unsafe will raise an
AttributeError if an attribute with the prefix assert or assret is
accessed on it. This protects against misspellings of real assert
method calls, which lead to tests passing silently even if the tested
code does not satisfy the intended assertion.

Recently a check was done in a large code base (Google) and three
more frequent ways of misspelling assert were found causing harm:
asert, aseert, assrt. These are now added to the existing check.
2020-11-05 09:04:38 -08:00
Karthikeyan Singaravelan 521c8d6806
bpo-39966: Revert "bpo-25597: Ensure wraps' return value is used for magic methods in MagicMock" (GH-19734)
* Revert "bpo-25597: Ensure wraps' return value is used for magic methods in MagicMock (#16029)"

This reverts commit 72b1004657.
2020-04-28 20:22:31 +01:00
Serhiy Storchaka 4b222c9491
bpo-40126: Fix reverting multiple patches in unittest.mock. (GH-19351)
Patcher's __exit__() is now never called if its __enter__() is failed.
Returning true from __exit__() silences now the exception.
2020-04-11 10:59:24 +03:00
Karthikeyan Singaravelan e553f204bf
bpo-39915: Ensure await_args_list is updated according to the order in which coroutines were awaited (GH-18924)
Create call objects with awaited arguments instead of using call_args which has only last call value.
2020-03-11 15:06:12 +00:00
Chris Withers db5e86adbc
Get mock coverage back to 100% (GH-18228)
* use the `: pass` and `: yield` patterns for code that isn't expected to ever be executed.

* The _Call items passed to _AnyComparer are only ever of length two, so assert instead of if/else

* fix typo

* Fix bug, where stop-without-start patching dict blows up with `TypeError: 'NoneType' object is not iterable`, highlighted by lack of coverage of an except branch.

* The fix for bpo-37972 means _Call.count and _Call.index are no longer needed.

* add coverage for calling next() on a mock_open with readline.return_value set.

* __aiter__ is defined on the Mock so the one on _AsyncIterator is never called.
2020-01-29 16:24:54 +00:00
Chris Withers a46575a8f2
Clarify and fix assertions that mocks have not been awaited (GH-18196)
- The gc.collect is needed for other implementations, such as pypy
- Using context managers over multiple lines will only catch the warning from the first line in the context!
- remove a skip for a test that no longer fails on pypy
2020-01-27 14:55:56 +00:00
Chris Withers c7dd3c7d87
Use relative imports in mock and its tests to help backporting (GH-18197)
* asyncio.run only available in 3.8+

* iscoroutinefunction has important bungfixes in 3.8

* IsolatedAsyncioTestCase only available in 3.8+
2020-01-27 14:11:19 +00:00
Karthikeyan Singaravelan 72b1004657 bpo-25597: Ensure wraps' return value is used for magic methods in MagicMock (#16029) 2020-01-27 06:48:15 +00:00
Vegard Stikbakke aef7dc8987 bpo-38932: Mock fully resets child objects on reset_mock(). (GH-17409) 2020-01-25 15:44:46 +00:00
Matthew Kokotovich 62865f4532 bpo-39082: Allow AsyncMock to correctly patch static/class methods (GH-18116) 2020-01-25 10:17:47 +00:00
Karthikeyan Singaravelan 66b00a9d3a bpo-38473: Handle autospecced functions and methods used with attach_mock (GH-16784) 2020-01-24 13:14:29 +00:00
Mario Corchero e131c9720d Fix `mock.patch.dict` to be stopped with `mock.patch.stopall` (#17606)
As the function was not registering in the active patches, the mocks
started by `mock.patch.dict` were not being stopped when
`mock.patch.stopall` was being called.
2020-01-24 08:38:32 +00:00
Emmanuel Arias 1d0c5e16ea bpo-24928: Add test case for patch.dict using OrderedDict (GH -11437)
* add test for path.dict using OrderedDict

Co-authored-by: Yu Tomita nekobon@users.noreply.github.com
2020-01-24 08:14:14 +00:00
Karthikeyan Singaravelan 54f743eb31 Improve test coverage for AsyncMock. (GH-17906)
* Add test for nested async decorator patch.
* Add test for side_effect and wraps with a function.
* Add test for side_effect with an exception in the iterable.
2020-01-15 09:49:49 +00:00
Elena Oat cd90a52983 bpo-38669: patch.object now raises a helpful error (GH17034)
This means a clearer message is now shown when patch.object is called with two string arguments, rather than a class and a string argument.
2019-12-08 20:14:38 +00:00
Jason Fried 046442d02b bpo-38857: AsyncMock fix for awaitable values and StopIteration fix [3.8] (GH-17269) 2019-11-20 16:27:51 -08:00
Adam Johnson 892221bfa0 bpo-38839: Fix some unused functions in tests (GH-17189) 2019-11-19 11:45:20 -08:00
Lisa Roach 3667e1ee6c
bpo-38163: Child mocks detect their type as sync or async (GH-16471) 2019-09-29 21:56:47 -07:00
Lisa Roach 25e115ec00
bpo-38161: Removes _AwaitEvent from AsyncMock. (GH-16443) 2019-09-29 21:01:28 -07:00
Lisa Roach 9a7d951950
bpo-38108: Makes mock objects inherit from Base (GH-16060) 2019-09-28 18:42:44 -07:00
Samuel Freilich 2180f6b058 bpo-36871: Avoid duplicated 'Actual:' in assertion message (GH-16361)
Fixes an issue caught after merge of PR 16005.

Tightened test assertions to check the entire assertion message.
2019-09-24 15:04:29 -07:00
Samuel Freilich b5a7a4f0c2 bpo-36871: Handle spec errors in assert_has_calls (GH-16005)
The fix in PR 13261 handled the underlying issue about the spec for specific methods not being applied correctly, but it didn't fix the issue that was causing the misleading error message.

The code currently grabs a list of responses from _call_matcher (which may include exceptions). But it doesn't reach inside the list when checking if the result is an exception. This results in a misleading error message when one of the provided calls does not match the spec.


https://bugs.python.org/issue36871



Automerge-Triggered-By: @gpshead
2019-09-24 12:08:31 -07:00
Lisa Roach ef04851775
bpo-38136: Updates await_count and call_count to be different things (GH-16192) 2019-09-23 20:49:40 -07:00
Lisa Roach 8b03f943c3
bpo-38093: Correctly returns AsyncMock for async subclasses. (GH-15947) 2019-09-19 21:04:18 -07:00
Abraham Toriz Cruz 5f5f11faf9 bpo-37828: Fix default mock_name in unittest.mock.assert_called error (GH-16166)
In the format string for assert_called the evaluation order is incorrect and hence for mock's without name, 'None' is printed whereas it should be 'mock' like for other messages. The error message is ("Expected '%s' to have been called." % self._mock_name or 'mock').
2019-09-17 12:16:08 +01:00
Elizabeth Uselton d6a9d17d8b bpo-37555: Update _CallList.__contains__ to respect ANY (#14700)
* Flip equality to use mock calls' __eq__

* bpo-37555: Regression test demonstrating assert_has_calls not working with ANY and spec_set

Co-authored-by: Neal Finne <neal@nealfinne.com>

* Revert "Flip equality to use mock calls' __eq__"

This reverts commit 94ddf54c5a.

* bpo-37555: Add regression tests for mock ANY ordering issues

Add regression tests for whether __eq__ is order agnostic on _Call and _CallList, which is useful for comparisons involving ANY, especially if the ANY comparison is to a class not defaulting __eq__ to NotImplemented.

Co-authored-by: Neal Finne <neal@nealfinne.com>

* bpo-37555: Fix _CallList and _Call order sensitivity

_Call and _CallList depend on ordering to correctly process that an object being compared to ANY with __eq__ should return True. This fix updates the comparison to check both a == b and b == a and return True if either condition is met, fixing situations from the tests in the previous two commits where assertEqual would not be commutative if checking _Call or _CallList objects. This seems like a reasonable fix considering that the Python data model specifies that if an object doesn't know how to compare itself to another object it should return NotImplemented, and that on getting NotImplemented from a == b, it should try b == a, implying that good behavior for __eq__ is commutative. This also flips the order of comparison in _CallList's __contains__ method, guaranteeing ANY will be on the left and have it's __eq__ called for equality checking, fixing the interaction between assert_has_calls and ANY.

Co-author: Neal Finne <neal@neal.finne.com>

* bpo-37555: Ensure _call_matcher returns _Call object

* Adding ACK and news entry

* bpo-37555: Replacing __eq__ with == to sidestep NotImplemented

bool(NotImplemented) returns True, so it's necessary to use ==
instead of __eq__ in this comparison.

* bpo-37555: cleaning up changes unnecessary to the final product

* bpo-37555: Fixed call on bound arguments to respect args and kwargs

* Revert "bpo-37555: Add regression tests for mock ANY ordering issues"

This reverts commit 49c5310ad4.

* Revert "bpo-37555: cleaning up changes unnecessary to the final product"

This reverts commit 18e964ba01.

* Revert "bpo-37555: Replacing __eq__ with == to sidestep NotImplemented"

This reverts commit f295eaca5b.

* Revert "bpo-37555: Fix _CallList and _Call order sensitivity"

This reverts commit 874fb697b8.

* Updated NEWS.d

* bpo-37555: Add tests checking every function using _call_matcher both with and without spec

* bpo-37555: Ensure all assert methods using _call_matcher are actually passing calls

* Remove AnyCompare and use call objects everywhere.

* Revert "Remove AnyCompare and use call objects everywhere."

This reverts commit 24973c0b32.

* Check for exception in assert_any_await
2019-09-13 16:54:32 +01:00
blhsing 72c359912d bpo-37972: unittest.mock._Call now passes on __getitem__ to the __getattr__ chaining so that call() can be subscriptable (GH-15565)
* bpo-37972: unittest.mock._Call now passes on __getitem__ to the __getattr__ chaining so that call() can be subscriptable

* 📜🤖 Added by blurb_it.

* Update 2019-08-28-21-40-12.bpo-37972.kP-n4L.rst

added name of the contributor

* bpo-37972: made all dunder methods chainable for _Call

* bpo-37972: delegate only attributes of tuple instead to __getattr__
2019-09-11 16:28:06 +02:00
Lisa Roach f1a297acb6
bpo-37251: Removes __code__ check from _is_async_obj. (GH-15830) 2019-09-10 12:18:40 +01:00
Xtreak 9d607061c9 bpo-37212: Preserve keyword argument order in unittest.mock.call and error messages (GH-14310) 2019-09-09 05:55:22 -05:00
Xtreak aa51508274 Fix assertions regarding magic methods function body that was not executed (GH-14154) 2019-09-09 10:04:57 +01:00
Min ho Kim 39d87b5471 Fix typos mostly in comments, docs and test names (GH-15209) 2019-08-30 16:21:19 -04:00
Xtreak c96127821e bpo-36871: Ensure method signature is used when asserting mock calls to a method (GH13261)
* Fix call_matcher for mock when using methods

* Add NEWS entry

* Use None check and convert doctest to unittest

* Use better name for mock in tests. Handle _SpecState when the attribute was not accessed and add tests.

* Use reset_mock instead of reinitialization. Change inner class constructor signature for check

* Reword comment regarding call object lookup logic
2019-08-29 07:09:01 +01:00
Serhiy Storchaka 662db125cd
bpo-37685: Fixed __eq__, __lt__ etc implementations in some classes. (GH-14952)
They now return NotImplemented for unsupported type of the other operand.
2019-08-08 08:42:54 +03:00
Min ho Kim c4cacc8c5e Fix typos in comments, docs and test names (#15018)
* Fix typos in comments, docs and test names

* Update test_pyparse.py

account for change in string length

* Apply suggestion: splitable -> splittable

Co-Authored-By: Terry Jan Reedy <tjreedy@udel.edu>

* Apply suggestion: splitable -> splittable

Co-Authored-By: Terry Jan Reedy <tjreedy@udel.edu>

* Apply suggestion: Dealloccte -> Deallocate

Co-Authored-By: Terry Jan Reedy <tjreedy@udel.edu>

* Update posixmodule checksum.

* Reverse idlelib changes.
2019-07-30 18:16:13 -04:00
Xtreak 7397cda997 bpo-21478: Record calls to parent when autospecced objects are used as child with attach_mock (GH 14688)
* Clear name and parent of mock in autospecced objects used with attach_mock

* Add NEWS entry

* Fix reversed order of comparison

* Test child and standalone function calls

* Use a helper function extracting mock to avoid code duplication and refactor tests.
2019-07-22 08:38:22 +01:00
Xtreak 0ae022c6a4 bpo-37075: Fix string concatenation in assert_has_awaits error message (GH-13616)
* Fix the implicit string concatenation in `assert_has_awaits` error message.
* Use "await" instead of "call" in `assert_awaited_with` error message.



https://bugs.python.org/issue37075
2019-05-29 00:02:25 -07:00
Mario Corchero 04530812e9 bpo-32299: Return patched dict when using patch.dict as a context manager (GH-11062) 2019-05-28 08:53:30 -04:00
Xtreak 436c2b0d67 bpo-36996: Handle async functions when mock.patch is used as a decorator (GH-13562)
Return a coroutine while patching async functions with a decorator. 

Co-authored-by: Andrew Svetlov <andrew.svetlov@gmail.com>


https://bugs.python.org/issue36996
2019-05-28 00:07:38 -07:00
Xtreak ff6b2e66b1 bpo-37047: Refactor AsyncMock setup logic for autospeccing (GH-13574)
Handle late binding and attribute access in unittest.mock.AsyncMock
setup for autospeccing.
2019-05-27 14:56:23 +02:00
Damien Nadé 394119afc6 bpo-37008: make mock_open handle able to honor next() (GH-13492)
I've reported the issue on https://bugs.python.org/issue37008 and now I'm trying to bring a solution to this minor issue.

I think it could be trivially backported to 3.7 branch.


https://bugs.python.org/issue37008
2019-05-23 03:03:25 -07:00
Lisa Roach 77b3b7701a
bpo-26467: Adds AsyncMock for asyncio Mock library support (GH-9296) 2019-05-20 09:19:53 -07:00
Zackery Spytz b9b08cd948 bpo-24758: Improve the error msg for unittest.mock.Mock()'s unsafe mode (#12991)
* bpo-24758: Improve the error msg for unittest.mock.Mock()'s unsafe mode

* Make the requested changes.
2019-05-08 23:02:23 +05:30
Rémi Lapeyre 11a8832c98 bpo-31855: unittest.mock.mock_open() results now respects the argument of read([size]) (GH-11521)
unittest.mock.mock_open() results now respects the argument of read([size])

Co-Authored-By: remilapeyre <remi.lapeyre@henki.fr>
2019-05-07 11:48:36 +01:00