chunk_id stringlengths 36 36 | source stringclasses 35
values | source_url stringlengths 0 290 | upstream_license stringclasses 1
value | document_id stringlengths 36 36 | chunk_index int64 0 324k | retrieved_at stringclasses 2
values | chunker_version stringclasses 4
values | content_hash stringlengths 15 64 | content stringlengths 50 44.7k | namespace stringclasses 9
values | source_name stringclasses 35
values | raw_text stringlengths 50 44.7k | cleaned_text stringlengths 50 44.7k | tags stringclasses 49
values | collection_name stringclasses 11
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d7c5e825-dd15-4f85-a37f-363dde3c294f | CPython Docs | file://datasets/cpython/Doc/library/bisect.rst | unknown | b800042e-7086-4e80-9b2b-8b0b152283a5 | 26,358 | supabase-export-v2 | 7bfbe67e7149c591 | :py:func:`~bisect.bisect_right` to locate an insertion point. Next, it runs the :meth:`~sequence.insert` method on *a* to insert *x* at the appropriate position to maintain sort order.
To support inserting records in a table, the *key* function (if any) is
applied to *x* for the search step but not for the insertion s... | trusted_official_docs | CPython Docs | :py:func:`~bisect.bisect_right` to locate an insertion point. Next, it runs the :meth:`~sequence.insert` method on *a* to insert *x* at the appropriate position to maintain sort order.
To support inserting records in a table, the *key* function (if any) is
applied to *x* for the search step but not for the insertion s... | :py:func:`~bisect.bisect_right` to locate an insertion point. Next, it runs the :meth:`~sequence.insert` method on *a* to insert *x* at the appropriate position to maintain sort order.
To support inserting records in a table, the *key* function (if any) is
applied to *x* for the search step but not for the insertion s... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
e0e12f9c-8afc-4ed3-bb9d-9c657aa73f8b | CPython Docs | file://datasets/cpython/Doc/library/bisect.rst | unknown | b800042e-7086-4e80-9b2b-8b0b152283a5 | 26,334 | supabase-export-v2 | 18a0c9b72b5340b6 | the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over linear searches or frequent resorting.
The module is called :mod:`!bisect` because it uses a basic bisection
algorithm to do its work. Unlike other bisection tools that search for a
specific valu... | trusted_official_docs | CPython Docs | the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over linear searches or frequent resorting.
The module is called :mod:`!bisect` because it uses a basic bisection
algorithm to do its work. Unlike other bisection tools that search for a
specific valu... | the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over linear searches or frequent resorting.
The module is called :mod:`!bisect` because it uses a basic bisection
algorithm to do its work. Unlike other bisection tools that search for a
specific valu... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
e2fcd1ab-0285-4a03-ae96-3686c9f5d58c | CPython Docs | file://datasets/cpython/Doc/library/bisect.rst | unknown | b800042e-7086-4e80-9b2b-8b0b152283a5 | 26,372 | supabase-export-v2 | f214410626d8d395 | x): 'Locate the leftmost value exactly equal to x' i = bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError
def find_lt(a, x):
'Find rightmost value less than x'
i = bisect_left(a, x)
if i:
return a[i-1]
raise ValueError | trusted_official_docs | CPython Docs | x): 'Locate the leftmost value exactly equal to x' i = bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError
def find_lt(a, x):
'Find rightmost value less than x'
i = bisect_left(a, x)
if i:
return a[i-1]
raise ValueError | x): 'Locate the leftmost value exactly equal to x' i = bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError
def find_lt(a, x):
'Find rightmost value less than x'
i = bisect_left(a, x)
if i:
return a[i-1]
raise ValueError | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
eae42801-0a9c-44a6-8639-0af28dbda5ce | CPython Docs | file://datasets/cpython/Doc/library/bisect.rst | unknown | b800042e-7086-4e80-9b2b-8b0b152283a5 | 26,351 | supabase-export-v2 | 4fbd420dc7eb0cfd | Insert *x* in *a* in sorted order.
This function first runs :py:func:`~bisect.bisect_left` to locate an insertion point. Next, it runs the :meth:`~sequence.insert` method on *a* to insert *x* at the
appropriate position to maintain sort order. | trusted_official_docs | CPython Docs | Insert *x* in *a* in sorted order.
This function first runs :py:func:`~bisect.bisect_left` to locate an insertion point. Next, it runs the :meth:`~sequence.insert` method on *a* to insert *x* at the
appropriate position to maintain sort order. | Insert *x* in *a* in sorted order.
This function first runs :py:func:`~bisect.bisect_left` to locate an insertion point. Next, it runs the :meth:`~sequence.insert` method on *a* to insert *x* at the
appropriate position to maintain sort order. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
f700971b-fb21-4655-999c-04dd716c313e | CPython Docs | file://datasets/cpython/Doc/library/bisect.rst | unknown | b800042e-7086-4e80-9b2b-8b0b152283a5 | 26,333 | supabase-export-v2 | aef85d7d27a00979 | --------------
This module provides support for maintaining a list in sorted order without
having to sort the list after each insertion. For long lists of items with
expensive comparison operations, this can be an improvement over
linear searches or frequent resorting. | trusted_official_docs | CPython Docs | --------------
This module provides support for maintaining a list in sorted order without
having to sort the list after each insertion. For long lists of items with
expensive comparison operations, this can be an improvement over
linear searches or frequent resorting. | --------------
This module provides support for maintaining a list in sorted order without
having to sort the list after each insertion. For long lists of items with
expensive comparison operations, this can be an improvement over
linear searches or frequent resorting. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
092f0a62-b706-4bbd-90a3-4598f2f111b3 | CPython Docs | file://datasets/cpython/Doc/library/fnmatch.rst | unknown | 04dbc6ab-ee20-4f1d-8910-e62fd162afbd | 26,399 | supabase-export-v2 | 253e35179e5cafaa | or ``ISO-8859-1`` encoded :class:`bytes` objects. Note that the functions documented below do not allow to mix a :class:`!bytes` pattern with a :class:`!str` filename, and vice-versa.
Finally, note that :func:`functools.lru_cache` with a *maxsize* of 32768
is used to cache the (typed) compiled regex patterns in the fol... | trusted_official_docs | CPython Docs | or ``ISO-8859-1`` encoded :class:`bytes` objects. Note that the functions documented below do not allow to mix a :class:`!bytes` pattern with a :class:`!str` filename, and vice-versa.
Finally, note that :func:`functools.lru_cache` with a *maxsize* of 32768
is used to cache the (typed) compiled regex patterns in the fol... | or ``ISO-8859-1`` encoded :class:`bytes` objects. Note that the functions documented below do not allow to mix a :class:`!bytes` pattern with a :class:`!str` filename, and vice-versa.
Finally, note that :func:`functools.lru_cache` with a *maxsize* of 32768
is used to cache the (typed) compiled regex patterns in the fol... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1060a2db-5528-4af2-b8e2-bdfee8c48d2b | CPython Docs | file://datasets/cpython/Doc/library/fnmatch.rst | unknown | 04dbc6ab-ee20-4f1d-8910-e62fd162afbd | 26,408 | supabase-export-v2 | 43e2217120807bdd | .. function:: filter(names, pat)
Construct a list from those elements of the :term:`iterable` of filename
strings *names* that match the pattern string *pat*. It is the same as ``[n for n in names if fnmatch(n, pat)]``,
but implemented more efficiently. | trusted_official_docs | CPython Docs | .. function:: filter(names, pat)
Construct a list from those elements of the :term:`iterable` of filename
strings *names* that match the pattern string *pat*. It is the same as ``[n for n in names if fnmatch(n, pat)]``,
but implemented more efficiently. | .. function:: filter(names, pat)
Construct a list from those elements of the :term:`iterable` of filename
strings *names* that match the pattern string *pat*. It is the same as ``[n for n in names if fnmatch(n, pat)]``,
but implemented more efficiently. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2e39f0ed-befd-4767-ace7-05aab2c9bde1 | CPython Docs | file://datasets/cpython/Doc/library/fnmatch.rst | unknown | 04dbc6ab-ee20-4f1d-8910-e62fd162afbd | 26,397 | supabase-export-v2 | 9d3c4948e0327471 | .. index:: pair: module; glob
Note that the filename separator (``'/'`` on Unix) is *not* special to this
module. See module :mod:`glob` for pathname expansion (:mod:`glob` uses
:func:`.filter` to match pathname segments). Similarly, filenames starting with
a period are not special for this module, and are matched by t... | trusted_official_docs | CPython Docs | .. index:: pair: module; glob
Note that the filename separator (``'/'`` on Unix) is *not* special to this
module. See module :mod:`glob` for pathname expansion (:mod:`glob` uses
:func:`.filter` to match pathname segments). Similarly, filenames starting with
a period are not special for this module, and are matched by t... | .. index:: pair: module; glob
Note that the filename separator (``'/'`` on Unix) is *not* special to this
module. See module :mod:`glob` for pathname expansion (:mod:`glob` uses
:func:`.filter` to match pathname segments). Similarly, filenames starting with
a period are not special for this module, and are matched by t... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
3224ad5d-8bd0-4afb-a486-0e48df428c75 | CPython Docs | file://datasets/cpython/Doc/library/fnmatch.rst | unknown | 04dbc6ab-ee20-4f1d-8910-e62fd162afbd | 26,393 | supabase-export-v2 | 7b84c33e13411754 | shell-style wildcards, which are *not* the same as regular expressions (which are documented in the :mod:`re` module). The special characters used in shell-style wildcards are:
.. index::
single: * (asterisk); in glob-style wildcards
single: ? (question mark); in glob-style wildcards
single: [] (square brackets); in... | trusted_official_docs | CPython Docs | shell-style wildcards, which are *not* the same as regular expressions (which are documented in the :mod:`re` module). The special characters used in shell-style wildcards are:
.. index::
single: * (asterisk); in glob-style wildcards
single: ? (question mark); in glob-style wildcards
single: [] (square brackets); in... | shell-style wildcards, which are *not* the same as regular expressions (which are documented in the :mod:`re` module). The special characters used in shell-style wildcards are:
.. index::
single: * (asterisk); in glob-style wildcards
single: ? (question mark); in glob-style wildcards
single: [] (square brackets); in... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
355d4723-608e-47a2-b1ea-3dfcc7e2df18 | CPython Docs | file://datasets/cpython/Doc/library/fnmatch.rst | unknown | 04dbc6ab-ee20-4f1d-8910-e62fd162afbd | 26,394 | supabase-export-v2 | 8df753c1c9fd4465 | ? (question mark); in glob-style wildcards single: [] (square brackets); in glob-style wildcards single: ! (exclamation); in glob-style wildcards single: - (minus); in glob-style wildcards
+------------+------------------------------------+
| Pattern | Meaning |
+============+====================================+
| ``*... | trusted_official_docs | CPython Docs | ? (question mark); in glob-style wildcards single: [] (square brackets); in glob-style wildcards single: ! (exclamation); in glob-style wildcards single: - (minus); in glob-style wildcards
+------------+------------------------------------+
| Pattern | Meaning |
+============+====================================+
| ``*... | ? (question mark); in glob-style wildcards single: [] (square brackets); in glob-style wildcards single: ! (exclamation); in glob-style wildcards single: - (minus); in glob-style wildcards
+------------+------------------------------------+
| Pattern | Meaning |
+============+====================================+
| ``*... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
36a71822-06d5-4f95-bc66-214daf797dec | CPython Docs | file://datasets/cpython/Doc/library/fnmatch.rst | unknown | 04dbc6ab-ee20-4f1d-8910-e62fd162afbd | 26,398 | supabase-export-v2 | 5bd828c9ebce0ca2 | to match pathname segments). Similarly, filenames starting with a period are not special for this module, and are matched by the ``*`` and ``?`` patterns.
Unless stated otherwise, "filename string" and "pattern string" either refer to
:class:`str` or ``ISO-8859-1`` encoded :class:`bytes` objects. Note that the
function... | trusted_official_docs | CPython Docs | to match pathname segments). Similarly, filenames starting with a period are not special for this module, and are matched by the ``*`` and ``?`` patterns.
Unless stated otherwise, "filename string" and "pattern string" either refer to
:class:`str` or ``ISO-8859-1`` encoded :class:`bytes` objects. Note that the
function... | to match pathname segments). Similarly, filenames starting with a period are not special for this module, and are matched by the ``*`` and ``?`` patterns.
Unless stated otherwise, "filename string" and "pattern string" either refer to
:class:`str` or ``ISO-8859-1`` encoded :class:`bytes` objects. Note that the
function... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
3883020e-c471-42db-9858-ad4dcc4f9bb9 | CPython Docs | file://datasets/cpython/Doc/library/fnmatch.rst | unknown | 04dbc6ab-ee20-4f1d-8910-e62fd162afbd | 26,410 | supabase-export-v2 | aa1597837812b56a | .. function:: filterfalse(names, pat)
Construct a list from those elements of the :term:`iterable` of filename
strings *names* that do not match the pattern string *pat*. It is the same as ``[n for n in names if not fnmatch(n, pat)]``,
but implemented more efficiently. | trusted_official_docs | CPython Docs | .. function:: filterfalse(names, pat)
Construct a list from those elements of the :term:`iterable` of filename
strings *names* that do not match the pattern string *pat*. It is the same as ``[n for n in names if not fnmatch(n, pat)]``,
but implemented more efficiently. | .. function:: filterfalse(names, pat)
Construct a list from those elements of the :term:`iterable` of filename
strings *names* that do not match the pattern string *pat*. It is the same as ``[n for n in names if not fnmatch(n, pat)]``,
but implemented more efficiently. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
494f9e69-591d-4adf-b6eb-1c0b46083622 | CPython Docs | file://datasets/cpython/Doc/library/fnmatch.rst | unknown | 04dbc6ab-ee20-4f1d-8910-e62fd162afbd | 26,402 | supabase-export-v2 | ff95dc6f0b96ffa9 | ``False``. Both parameters are case-normalized using :func:`os.path.normcase`. :func:`fnmatchcase` can be used to perform a case-sensitive comparison, regardless of whether that's standard for the operating system.
This example will print all file names in the current directory with the
extension ``.txt``:: | trusted_official_docs | CPython Docs | ``False``. Both parameters are case-normalized using :func:`os.path.normcase`. :func:`fnmatchcase` can be used to perform a case-sensitive comparison, regardless of whether that's standard for the operating system.
This example will print all file names in the current directory with the
extension ``.txt``:: | ``False``. Both parameters are case-normalized using :func:`os.path.normcase`. :func:`fnmatchcase` can be used to perform a case-sensitive comparison, regardless of whether that's standard for the operating system.
This example will print all file names in the current directory with the
extension ``.txt``:: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
50acf82a-264b-4019-8e4d-3376b0e03621 | CPython Docs | file://datasets/cpython/Doc/library/fnmatch.rst | unknown | 04dbc6ab-ee20-4f1d-8910-e62fd162afbd | 26,395 | supabase-export-v2 | 735cd136a67aeaba | single character | +------------+------------------------------------+ | ``[seq]`` | matches any character in *seq* | +------------+------------------------------------+ | ``[!seq]`` | matches any character not in *seq* | +------------+------------------------------------+
For a literal match, wrap the meta-characters ... | trusted_official_docs | CPython Docs | single character | +------------+------------------------------------+ | ``[seq]`` | matches any character in *seq* | +------------+------------------------------------+ | ``[!seq]`` | matches any character not in *seq* | +------------+------------------------------------+
For a literal match, wrap the meta-characters ... | single character | +------------+------------------------------------+ | ``[seq]`` | matches any character in *seq* | +------------+------------------------------------+ | ``[!seq]`` | matches any character not in *seq* | +------------+------------------------------------+
For a literal match, wrap the meta-characters ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
b1c9d635-e624-44b1-92a9-3603369bc217 | CPython Docs | file://datasets/cpython/Doc/library/fnmatch.rst | unknown | 04dbc6ab-ee20-4f1d-8910-e62fd162afbd | 26,392 | supabase-export-v2 | c1fb87cf3674b574 | --------------
This module provides support for Unix shell-style wildcards, which are *not* the
same as regular expressions (which are documented in the :mod:`re` module). The
special characters used in shell-style wildcards are: | trusted_official_docs | CPython Docs | --------------
This module provides support for Unix shell-style wildcards, which are *not* the
same as regular expressions (which are documented in the :mod:`re` module). The
special characters used in shell-style wildcards are: | --------------
This module provides support for Unix shell-style wildcards, which are *not* the
same as regular expressions (which are documented in the :mod:`re` module). The
special characters used in shell-style wildcards are: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
ea45ab3d-ebc3-44af-b305-6f57207e52f5 | CPython Docs | file://datasets/cpython/Doc/library/fnmatch.rst | unknown | 04dbc6ab-ee20-4f1d-8910-e62fd162afbd | 26,401 | supabase-export-v2 | dcdb1100f65e69cd | .. function:: fnmatch(name, pat)
Test whether the filename string *name* matches the pattern string *pat*,
returning ``True`` or ``False``. Both parameters are case-normalized
using :func:`os.path.normcase`. :func:`fnmatchcase` can be used to perform a
case-sensitive comparison, regardless of whether that's standard... | trusted_official_docs | CPython Docs | .. function:: fnmatch(name, pat)
Test whether the filename string *name* matches the pattern string *pat*,
returning ``True`` or ``False``. Both parameters are case-normalized
using :func:`os.path.normcase`. :func:`fnmatchcase` can be used to perform a
case-sensitive comparison, regardless of whether that's standard... | .. function:: fnmatch(name, pat)
Test whether the filename string *name* matches the pattern string *pat*,
returning ``True`` or ``False``. Both parameters are case-normalized
using :func:`os.path.normcase`. :func:`fnmatchcase` can be used to perform a
case-sensitive comparison, regardless of whether that's standard... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0177ba15-62cb-4d72-b02e-f9da1046ccf7 | CPython Docs | file://datasets/cpython/Doc/library/security_warnings.rst | unknown | f0f3715c-91aa-45b0-8a85-a17d6b28ba08 | 26,421 | supabase-export-v2 | 29a1cdfdf2d0e11a | The following modules have specific security considerations:
* :mod:`base64`: :ref:`base64 security considerations <base64-security>` in
:rfc:`4648`
* :mod:`hashlib`: :ref:`all constructors take a "usedforsecurity" keyword-only
argument disabling known insecure and blocked algorithms
<hashlib-usedforsecurity>`
* :mo... | trusted_official_docs | CPython Docs | The following modules have specific security considerations:
* :mod:`base64`: :ref:`base64 security considerations <base64-security>` in
:rfc:`4648`
* :mod:`hashlib`: :ref:`all constructors take a "usedforsecurity" keyword-only
argument disabling known insecure and blocked algorithms
<hashlib-usedforsecurity>`
* :mo... | The following modules have specific security considerations:
* :mod:`base64`: :ref:`base64 security considerations <base64-security>` in
:rfc:`4648`
* :mod:`hashlib`: :ref:`all constructors take a "usedforsecurity" keyword-only
argument disabling known insecure and blocked algorithms
<hashlib-usedforsecurity>`
* :mo... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
07626f8e-a5bd-4459-85c1-b015de3e0076 | CPython Docs | file://datasets/cpython/Doc/library/security_warnings.rst | unknown | f0f3715c-91aa-45b0-8a85-a17d6b28ba08 | 26,423 | supabase-export-v2 | 2fd55f7829bad56b | deprecated due to vulnerability to race conditions <tempfile-mktemp-deprecated>` * :mod:`xml`: :ref:`XML security <xml-security>` * :mod:`zipfile`: :ref:`maliciously prepared .zip files can cause disk volume exhaustion <zipfile-resources-limitations>`
The :option:`-I` command line option can be used to run Python in is... | trusted_official_docs | CPython Docs | deprecated due to vulnerability to race conditions <tempfile-mktemp-deprecated>` * :mod:`xml`: :ref:`XML security <xml-security>` * :mod:`zipfile`: :ref:`maliciously prepared .zip files can cause disk volume exhaustion <zipfile-resources-limitations>`
The :option:`-I` command line option can be used to run Python in is... | deprecated due to vulnerability to race conditions <tempfile-mktemp-deprecated>` * :mod:`xml`: :ref:`XML security <xml-security>` * :mod:`zipfile`: :ref:`maliciously prepared .zip files can cause disk volume exhaustion <zipfile-resources-limitations>`
The :option:`-I` command line option can be used to run Python in is... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
9107a5c7-707a-4de7-bb96-bb280cb1a6db | CPython Docs | file://datasets/cpython/Doc/library/security_warnings.rst | unknown | f0f3715c-91aa-45b0-8a85-a17d6b28ba08 | 26,422 | supabase-export-v2 | 2a5d30dbd89d31f7 | disabling known insecure and blocked algorithms <hashlib-usedforsecurity>` * :mod:`http.server` is not suitable for production use, only implementing basic security checks. See the :ref:`security considerations <http.server-security>`.
* :mod:`logging`: :ref:`Logging configuration uses eval()
<logging-eval-security>`
... | trusted_official_docs | CPython Docs | disabling known insecure and blocked algorithms <hashlib-usedforsecurity>` * :mod:`http.server` is not suitable for production use, only implementing basic security checks. See the :ref:`security considerations <http.server-security>`.
* :mod:`logging`: :ref:`Logging configuration uses eval()
<logging-eval-security>`
... | disabling known insecure and blocked algorithms <hashlib-usedforsecurity>` * :mod:`http.server` is not suitable for production use, only implementing basic security checks. See the :ref:`security considerations <http.server-security>`.
* :mod:`logging`: :ref:`Logging configuration uses eval()
<logging-eval-security>`
... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
004ae15b-2182-4a52-8efa-b1fd443a59be | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,868 | supabase-export-v2 | c5037b77a79fed16 | The magic methods are setup with :class:`MagicMock` objects, so you can configure them and use them in the usual way:
>>> mock = MagicMock()
>>> mock[3] = 'fish'
>>> mock.__setitem__.assert_called_with(3, 'fish')
>>> mock.__getitem__.return_value = 'result'
>>> mock[2]
'result' | trusted_official_docs | CPython Docs | The magic methods are setup with :class:`MagicMock` objects, so you can configure them and use them in the usual way:
>>> mock = MagicMock()
>>> mock[3] = 'fish'
>>> mock.__setitem__.assert_called_with(3, 'fish')
>>> mock.__getitem__.return_value = 'result'
>>> mock[2]
'result' | The magic methods are setup with :class:`MagicMock` objects, so you can configure them and use them in the usual way:
>>> mock = MagicMock()
>>> mock[3] = 'fish'
>>> mock.__setitem__.assert_called_with(3, 'fish')
>>> mock.__getitem__.return_value = 'result'
>>> mock[2]
'result' | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0090775e-becc-41d4-9800-a8c6548d635d | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,991 | supabase-export-v2 | 94d62d7db5a7f80a | .. function:: seal(mock)
Seal will disable the automatic creation of mocks when accessing an attribute of
the mock being sealed or any of its attributes that are already mocks recursively. | trusted_official_docs | CPython Docs | .. function:: seal(mock)
Seal will disable the automatic creation of mocks when accessing an attribute of
the mock being sealed or any of its attributes that are already mocks recursively. | .. function:: seal(mock)
Seal will disable the automatic creation of mocks when accessing an attribute of
the mock being sealed or any of its attributes that are already mocks recursively. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
010174a5-88aa-4c46-a925-eccadf0b237c | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,817 | supabase-export-v2 | 70ca47e81c8e9fcb | TEST_PREFIX ~~~~~~~~~~~
All of the patchers can be used as class decorators. When used in this way
they wrap every test method on the class. The patchers recognise methods that
start with ``'test'`` as being test methods. This is the same way that the
:class:`unittest.TestLoader` finds test methods by default. | trusted_official_docs | CPython Docs | TEST_PREFIX ~~~~~~~~~~~
All of the patchers can be used as class decorators. When used in this way
they wrap every test method on the class. The patchers recognise methods that
start with ``'test'`` as being test methods. This is the same way that the
:class:`unittest.TestLoader` finds test methods by default. | TEST_PREFIX ~~~~~~~~~~~
All of the patchers can be used as class decorators. When used in this way
they wrap every test method on the class. The patchers recognise methods that
start with ``'test'`` as being test methods. This is the same way that the
:class:`unittest.TestLoader` finds test methods by default. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
03e6de28-463d-4066-bcb4-e579bfc727c5 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,735 | supabase-export-v2 | 5b92b257c32e6813 | instantiated multiple times you could use :attr:`~Mock.side_effect` to return a new mock each time. Alternatively you can set the *return_value* to be anything you want.
To configure return values on methods of *instances* on the patched class
you must do this on the :attr:`~Mock.return_value`. For example:: | trusted_official_docs | CPython Docs | instantiated multiple times you could use :attr:`~Mock.side_effect` to return a new mock each time. Alternatively you can set the *return_value* to be anything you want.
To configure return values on methods of *instances* on the patched class
you must do this on the :attr:`~Mock.return_value`. For example:: | instantiated multiple times you could use :attr:`~Mock.side_effect` to return a new mock each time. Alternatively you can set the *return_value* to be anything you want.
To configure return values on methods of *instances* on the patched class
you must do this on the :attr:`~Mock.return_value`. For example:: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0454e430-b7dd-4d0b-af03-6611df651229 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,699 | supabase-export-v2 | b2381296ad2818f7 | Mock names and the name attribute ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Since "name" is an argument to the :class:`Mock` constructor, if you want your
mock object to have a "name" attribute you can't just pass it in at creation
time. There are two alternatives. One option is to use
:meth:`~Mock.configure_mock`:: | trusted_official_docs | CPython Docs | Mock names and the name attribute ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Since "name" is an argument to the :class:`Mock` constructor, if you want your
mock object to have a "name" attribute you can't just pass it in at creation
time. There are two alternatives. One option is to use
:meth:`~Mock.configure_mock`:: | Mock names and the name attribute ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Since "name" is an argument to the :class:`Mock` constructor, if you want your
mock object to have a "name" attribute you can't just pass it in at creation
time. There are two alternatives. One option is to use
:meth:`~Mock.configure_mock`:: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
05a956e0-88ce-451f-bea8-e898e3ec9c7f | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 27,012 | supabase-export-v2 | 09ea931779c6a2ea | to it, this will not be ignored as it is an explicit assignment. So, the order of precedence will not move to the wrapped object.
>>> order_mock.get_value.return_value = None
>>> order_mock.get_value() is None
True | trusted_official_docs | CPython Docs | to it, this will not be ignored as it is an explicit assignment. So, the order of precedence will not move to the wrapped object.
>>> order_mock.get_value.return_value = None
>>> order_mock.get_value() is None
True | to it, this will not be ignored as it is an explicit assignment. So, the order of precedence will not move to the wrapped object.
>>> order_mock.get_value.return_value = None
>>> order_mock.get_value() is None
True | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
06b60c78-8b0b-45bd-beea-5923eb41e560 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,874 | supabase-export-v2 | 75f787648ff532bf | >>> mock = MagicMock() >>> int(mock) 1 >>> len(mock) 0 >>> list(mock) [] >>> object() in mock False
The two equality methods, :meth:`!__eq__` and :meth:`!__ne__`, are special. They do the default equality comparison on identity, using the
:attr:`~Mock.side_effect` attribute, unless you change their return value to
retu... | trusted_official_docs | CPython Docs | >>> mock = MagicMock() >>> int(mock) 1 >>> len(mock) 0 >>> list(mock) [] >>> object() in mock False
The two equality methods, :meth:`!__eq__` and :meth:`!__ne__`, are special. They do the default equality comparison on identity, using the
:attr:`~Mock.side_effect` attribute, unless you change their return value to
retu... | >>> mock = MagicMock() >>> int(mock) 1 >>> len(mock) 0 >>> list(mock) [] >>> object() in mock False
The two equality methods, :meth:`!__eq__` and :meth:`!__ne__`, are special. They do the default equality comparison on identity, using the
:attr:`~Mock.side_effect` attribute, unless you change their return value to
retu... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
06e9a0c0-4a46-416d-b899-ff4741f88709 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 27,003 | supabase-export-v2 | 56f2968a23b97859 | value being returned by :attr:`~Mock.side_effect` is :data:`DEFAULT`, it is ignored and the order of precedence moves to the successor to obtain the value to return.
>>> from unittest.mock import DEFAULT
>>> order_mock.get_value.side_effect = [DEFAULT]
>>> order_mock.get_value()
'second' | trusted_official_docs | CPython Docs | value being returned by :attr:`~Mock.side_effect` is :data:`DEFAULT`, it is ignored and the order of precedence moves to the successor to obtain the value to return.
>>> from unittest.mock import DEFAULT
>>> order_mock.get_value.side_effect = [DEFAULT]
>>> order_mock.get_value()
'second' | value being returned by :attr:`~Mock.side_effect` is :data:`DEFAULT`, it is ignored and the order of precedence moves to the successor to obtain the value to return.
>>> from unittest.mock import DEFAULT
>>> order_mock.get_value.side_effect = [DEFAULT]
>>> order_mock.get_value()
'second' | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0752e0dc-ace0-4349-81ef-0aed4e4304a6 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 27,015 | supabase-export-v2 | a14cd7c8ce0df148 | **{"get_value.side_effect": ["first"], ... "get_value.return_value": "second"} ... ) ... >>> order_mock.get_value() 'first' >>> order_mock.get_value.side_effect = None >>> order_mock.get_value() 'second' >>> order_mock.get_value.return_value = DEFAULT >>> order_mock.get_value() 'third'
If :attr:`~Mock.side_effect` is e... | trusted_official_docs | CPython Docs | **{"get_value.side_effect": ["first"], ... "get_value.return_value": "second"} ... ) ... >>> order_mock.get_value() 'first' >>> order_mock.get_value.side_effect = None >>> order_mock.get_value() 'second' >>> order_mock.get_value.return_value = DEFAULT >>> order_mock.get_value() 'third'
If :attr:`~Mock.side_effect` is e... | **{"get_value.side_effect": ["first"], ... "get_value.return_value": "second"} ... ) ... >>> order_mock.get_value() 'first' >>> order_mock.get_value.side_effect = None >>> order_mock.get_value() 'second' >>> order_mock.get_value.return_value = DEFAULT >>> order_mock.get_value() 'third'
If :attr:`~Mock.side_effect` is e... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
07f81e52-ba48-4aa3-aed3-66e2aba18163 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,877 | supabase-export-v2 | 0008d3aba2dc5f34 | The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't required to be an iterator:
>>> mock = MagicMock()
>>> mock.__iter__.return_value = ['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c'] | trusted_official_docs | CPython Docs | The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't required to be an iterator:
>>> mock = MagicMock()
>>> mock.__iter__.return_value = ['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c'] | The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't required to be an iterator:
>>> mock = MagicMock()
>>> mock.__iter__.return_value = ['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c'] | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
09779e00-c1b8-44ec-a20f-03e9560ddb21 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,732 | supabase-export-v2 | 3633d414fdf3a6b7 | :func:`patch` as function decorator, creating the mock for you and passing it into the decorated function::
>>> @patch('__main__.SomeClass')
... def function(normal_argument, mock_class):
... print(mock_class is SomeClass)
... >>> function(None)
True | trusted_official_docs | CPython Docs | :func:`patch` as function decorator, creating the mock for you and passing it into the decorated function::
>>> @patch('__main__.SomeClass')
... def function(normal_argument, mock_class):
... print(mock_class is SomeClass)
... >>> function(None)
True | :func:`patch` as function decorator, creating the mock for you and passing it into the decorated function::
>>> @patch('__main__.SomeClass')
... def function(normal_argument, mock_class):
... print(mock_class is SomeClass)
... >>> function(None)
True | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0aff994a-aa43-4f59-8da0-7da7f0762918 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,536 | supabase-export-v2 | f82e5ea902d2c0be | = {'method.return_value': 3, 'other.side_effect': KeyError} >>> mock = Mock(some_attribute='eggs', **attrs) >>> mock.some_attribute 'eggs' >>> mock.method() 3 >>> mock.other() Traceback (most recent call last): ... KeyError
:meth:`configure_mock` exists to make it easier to do configuration
after the mock has been cre... | trusted_official_docs | CPython Docs | = {'method.return_value': 3, 'other.side_effect': KeyError} >>> mock = Mock(some_attribute='eggs', **attrs) >>> mock.some_attribute 'eggs' >>> mock.method() 3 >>> mock.other() Traceback (most recent call last): ... KeyError
:meth:`configure_mock` exists to make it easier to do configuration
after the mock has been cre... | = {'method.return_value': 3, 'other.side_effect': KeyError} >>> mock = Mock(some_attribute='eggs', **attrs) >>> mock.some_attribute 'eggs' >>> mock.method() 3 >>> mock.other() Traceback (most recent call last): ... KeyError
:meth:`configure_mock` exists to make it easier to do configuration
after the mock has been cre... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0c2ac9ed-2aea-4b1d-80a6-74587acce045 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,620 | supabase-export-v2 | 3bef86a95956e521 | of :class:`MagicMock`. The :class:`AsyncMock` object will behave so the object is recognized as an async function, and the result of a call is an awaitable.
>>> mock = AsyncMock()
>>> inspect.iscoroutinefunction(mock)
True
>>> inspect.isawaitable(mock()) # doctest: +SKIP
True | trusted_official_docs | CPython Docs | of :class:`MagicMock`. The :class:`AsyncMock` object will behave so the object is recognized as an async function, and the result of a call is an awaitable.
>>> mock = AsyncMock()
>>> inspect.iscoroutinefunction(mock)
True
>>> inspect.isawaitable(mock()) # doctest: +SKIP
True | of :class:`MagicMock`. The :class:`AsyncMock` object will behave so the object is recognized as an async function, and the result of a call is an awaitable.
>>> mock = AsyncMock()
>>> inspect.iscoroutinefunction(mock)
True
>>> inspect.isawaitable(mock()) # doctest: +SKIP
True | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0c5a1672-9554-4b99-a1e7-c9a807775566 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,689 | supabase-export-v2 | 0cd5a07aedd86404 | be any iterable object. Repeated calls to the mock will return values from the iterable (until the iterable is exhausted and a :exc:`StopIteration` is raised):
>>> m = MagicMock(side_effect=[1, 2, 3])
>>> m()
1
>>> m()
2
>>> m()
3
>>> m()
Traceback (most recent call last):
... StopIteration | trusted_official_docs | CPython Docs | be any iterable object. Repeated calls to the mock will return values from the iterable (until the iterable is exhausted and a :exc:`StopIteration` is raised):
>>> m = MagicMock(side_effect=[1, 2, 3])
>>> m()
1
>>> m()
2
>>> m()
3
>>> m()
Traceback (most recent call last):
... StopIteration | be any iterable object. Repeated calls to the mock will return values from the iterable (until the iterable is exhausted and a :exc:`StopIteration` is raised):
>>> m = MagicMock(side_effect=[1, 2, 3])
>>> m()
1
>>> m()
2
>>> m()
3
>>> m()
Traceback (most recent call last):
... StopIteration | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0c7b5c8e-2a68-433a-9012-5f4f60b3d30e | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,452 | supabase-export-v2 | 172c00018ccc349d | >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method: ... thing = ProductionClass() ... thing.method(1, 2, 3) ... >>> mock_method.assert_called_once_with(1, 2, 3)
There is also :func:`patch.dict` for setting values in a dictionary just
during a scope and restoring the dictionary to its ori... | trusted_official_docs | CPython Docs | >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method: ... thing = ProductionClass() ... thing.method(1, 2, 3) ... >>> mock_method.assert_called_once_with(1, 2, 3)
There is also :func:`patch.dict` for setting values in a dictionary just
during a scope and restoring the dictionary to its ori... | >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method: ... thing = ProductionClass() ... thing.method(1, 2, 3) ... >>> mock_method.assert_called_once_with(1, 2, 3)
There is also :func:`patch.dict` for setting values in a dictionary just
during a scope and restoring the dictionary to its ori... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0db7639d-16a9-439c-892e-d1d055c2ce85 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,831 | supabase-export-v2 | 9f60f6ecbaf38053 | b.py -> from a import SomeClass -> some_function instantiates SomeClass
Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
:func:`patch`. The problem is that when we import module b, which we will have to
do when it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
... | trusted_official_docs | CPython Docs | b.py -> from a import SomeClass -> some_function instantiates SomeClass
Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
:func:`patch`. The problem is that when we import module b, which we will have to
do when it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
... | b.py -> from a import SomeClass -> some_function instantiates SomeClass
Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
:func:`patch`. The problem is that when we import module b, which we will have to
do when it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0e9d007a-e68a-4669-9a0d-5f285ef7660e | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,844 | supabase-export-v2 | 8f8e2dd78e3d4955 | interested in to a function or a mock instance. If you are using a function then it *must* take ``self`` as the first argument [#]_.
>>> def __str__(self):
... return 'fooble'
... >>> mock = Mock()
>>> mock.__str__ = __str__
>>> str(mock)
'fooble' | trusted_official_docs | CPython Docs | interested in to a function or a mock instance. If you are using a function then it *must* take ``self`` as the first argument [#]_.
>>> def __str__(self):
... return 'fooble'
... >>> mock = Mock()
>>> mock.__str__ = __str__
>>> str(mock)
'fooble' | interested in to a function or a mock instance. If you are using a function then it *must* take ``self`` as the first argument [#]_.
>>> def __str__(self):
... return 'fooble'
... >>> mock = Mock()
>>> mock.__str__ = __str__
>>> str(mock)
'fooble' | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0f486ead-9768-48a5-a5f2-14c1751776b2 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 27,017 | supabase-export-v2 | a6dfb5db794cb6da | >>> order_mock = Mock(spec=Order, wraps=Order) >>> order_mock.get_value.side_effect = ["first side effect value", ... "another side effect value"] >>> order_mock.get_value.return_value = "second"
>>> order_mock.get_value()
'first side effect value'
>>> order_mock.get_value()
'another side effect value' | trusted_official_docs | CPython Docs | >>> order_mock = Mock(spec=Order, wraps=Order) >>> order_mock.get_value.side_effect = ["first side effect value", ... "another side effect value"] >>> order_mock.get_value.return_value = "second"
>>> order_mock.get_value()
'first side effect value'
>>> order_mock.get_value()
'another side effect value' | >>> order_mock = Mock(spec=Order, wraps=Order) >>> order_mock.get_value.side_effect = ["first side effect value", ... "another side effect value"] >>> order_mock.get_value.return_value = "second"
>>> order_mock.get_value()
'first side effect value'
>>> order_mock.get_value()
'another side effect value' | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
10e4919e-5e44-4dad-b639-1929845d2f53 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,705 | supabase-export-v2 | 7bd511e8c89d3aae | attaching mocks to a parent that records all calls to the children and allows you to make assertions about the order of calls between mocks:
>>> parent = MagicMock()
>>> child1 = MagicMock(return_value=None)
>>> child2 = MagicMock(return_value=None)
>>> parent.child1 = child1
>>> parent.child2 = child2
>>> child1(... | trusted_official_docs | CPython Docs | attaching mocks to a parent that records all calls to the children and allows you to make assertions about the order of calls between mocks:
>>> parent = MagicMock()
>>> child1 = MagicMock(return_value=None)
>>> child2 = MagicMock(return_value=None)
>>> parent.child1 = child1
>>> parent.child2 = child2
>>> child1(... | attaching mocks to a parent that records all calls to the children and allows you to make assertions about the order of calls between mocks:
>>> parent = MagicMock()
>>> child1 = MagicMock(return_value=None)
>>> child2 = MagicMock(return_value=None)
>>> parent.child1 = child1
>>> parent.child2 = child2
>>> child1(... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1274bfdb-d584-4eca-b564-592e6d709113 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,621 | supabase-export-v2 | 34216b35732ea235 | >>> mock = AsyncMock() >>> inspect.iscoroutinefunction(mock) True >>> inspect.isawaitable(mock()) # doctest: +SKIP True
The result of ``mock()`` is an async function which will have the outcome
of ``side_effect`` or ``return_value`` after it has been awaited: | trusted_official_docs | CPython Docs | >>> mock = AsyncMock() >>> inspect.iscoroutinefunction(mock) True >>> inspect.isawaitable(mock()) # doctest: +SKIP True
The result of ``mock()`` is an async function which will have the outcome
of ``side_effect`` or ``return_value`` after it has been awaited: | >>> mock = AsyncMock() >>> inspect.iscoroutinefunction(mock) True >>> inspect.isawaitable(mock()) # doctest: +SKIP True
The result of ``mock()`` is an async function which will have the outcome
of ``side_effect`` or ``return_value`` after it has been awaited: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
12b07e64-f6fb-4ed4-a55b-96458b068787 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,718 | supabase-export-v2 | 2eab90ca6ae94459 | as an extra argument to the decorated function. If :func:`patch` is used as a context manager the created mock is returned by the context manager.
*target* should be a string in the form ``'package.module.ClassName'``. The
*target* is imported and the specified object replaced with the *new*
object, so the *target* m... | trusted_official_docs | CPython Docs | as an extra argument to the decorated function. If :func:`patch` is used as a context manager the created mock is returned by the context manager.
*target* should be a string in the form ``'package.module.ClassName'``. The
*target* is imported and the specified object replaced with the *new*
object, so the *target* m... | as an extra argument to the decorated function. If :func:`patch` is used as a context manager the created mock is returned by the context manager.
*target* should be a string in the form ``'package.module.ClassName'``. The
*target* is imported and the specified object replaced with the *new*
object, so the *target* m... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
14032ca7-60c0-4605-8d38-e5e0b604fc37 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,878 | supabase-export-v2 | f877361482567405 | >>> mock = MagicMock() >>> mock.__iter__.return_value = ['a', 'b', 'c'] >>> list(mock) ['a', 'b', 'c'] >>> list(mock) ['a', 'b', 'c']
If the return value *is* an iterator, then iterating over it once will consume
it and subsequent iterations will result in an empty list: | trusted_official_docs | CPython Docs | >>> mock = MagicMock() >>> mock.__iter__.return_value = ['a', 'b', 'c'] >>> list(mock) ['a', 'b', 'c'] >>> list(mock) ['a', 'b', 'c']
If the return value *is* an iterator, then iterating over it once will consume
it and subsequent iterations will result in an empty list: | >>> mock = MagicMock() >>> mock.__iter__.return_value = ['a', 'b', 'c'] >>> list(mock) ['a', 'b', 'c'] >>> list(mock) ['a', 'b', 'c']
If the return value *is* an iterator, then iterating over it once will consume
it and subsequent iterations will result in an empty list: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
141b9814-a837-4086-bee6-9b30d2480b16 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,509 | supabase-export-v2 | 2793cee99b4e286b | Assert the mock was never called.
>>> m = Mock()
>>> m.hello.assert_not_called()
>>> obj = m.hello()
>>> m.hello.assert_not_called()
Traceback (most recent call last):
... AssertionError: Expected 'hello' to not have been called. Called 1 times. Calls: [call()]. | trusted_official_docs | CPython Docs | Assert the mock was never called.
>>> m = Mock()
>>> m.hello.assert_not_called()
>>> obj = m.hello()
>>> m.hello.assert_not_called()
Traceback (most recent call last):
... AssertionError: Expected 'hello' to not have been called. Called 1 times. Calls: [call()]. | Assert the mock was never called.
>>> m = Mock()
>>> m.hello.assert_not_called()
>>> obj = m.hello()
>>> m.hello.assert_not_called()
Traceback (most recent call last):
... AssertionError: Expected 'hello' to not have been called. Called 1 times. Calls: [call()]. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1490450c-cb3c-410b-a1d7-6545e357daa3 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,957 | supabase-export-v2 | 150daf15c34c43e8 | dandy, but if you don't test how your units are "wired together" there is still lots of room for bugs that tests might have caught.
:mod:`!unittest.mock` already provides a feature to help with this, called speccing. If you
use a class or instance as the :attr:`!spec` for a mock then you can only access
attributes on t... | trusted_official_docs | CPython Docs | dandy, but if you don't test how your units are "wired together" there is still lots of room for bugs that tests might have caught.
:mod:`!unittest.mock` already provides a feature to help with this, called speccing. If you
use a class or instance as the :attr:`!spec` for a mock then you can only access
attributes on t... | dandy, but if you don't test how your units are "wired together" there is still lots of room for bugs that tests might have caught.
:mod:`!unittest.mock` already provides a feature to help with this, called speccing. If you
use a class or instance as the :attr:`!spec` for a mock then you can only access
attributes on t... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
149ad9e0-e92e-46ea-ab67-321fb28864f3 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,992 | supabase-export-v2 | 0c4a78ea8bc40bcd | disable the automatic creation of mocks when accessing an attribute of the mock being sealed or any of its attributes that are already mocks recursively.
If a mock instance with a name or a spec is assigned to an attribute
it won't be considered in the sealing chain. This allows one to prevent seal from
fixing part o... | trusted_official_docs | CPython Docs | disable the automatic creation of mocks when accessing an attribute of the mock being sealed or any of its attributes that are already mocks recursively.
If a mock instance with a name or a spec is assigned to an attribute
it won't be considered in the sealing chain. This allows one to prevent seal from
fixing part o... | disable the automatic creation of mocks when accessing an attribute of the mock being sealed or any of its attributes that are already mocks recursively.
If a mock instance with a name or a spec is assigned to an attribute
it won't be considered in the sealing chain. This allows one to prevent seal from
fixing part o... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
15918505-4614-42d8-8705-525d7bd8f510 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,909 | supabase-export-v2 | b926a813a906d02b | .. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
Create a mock object using another object as a spec. Attributes on the
mock will use the corresponding attribute on the *spec* object as their
spec. | trusted_official_docs | CPython Docs | .. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
Create a mock object using another object as a spec. Attributes on the
mock will use the corresponding attribute on the *spec* object as their
spec. | .. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
Create a mock object using another object as a spec. Attributes on the
mock will use the corresponding attribute on the *spec* object as their
spec. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
174b4ba3-543a-418f-bf99-f65a4fc74c79 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,869 | supabase-export-v2 | e24d536c911d3733 | >>> mock = MagicMock() >>> mock[3] = 'fish' >>> mock.__setitem__.assert_called_with(3, 'fish') >>> mock.__getitem__.return_value = 'result' >>> mock[2] 'result'
By default many of the protocol methods are required to return objects of a
specific type. These methods are preconfigured with a default return value, so
that... | trusted_official_docs | CPython Docs | >>> mock = MagicMock() >>> mock[3] = 'fish' >>> mock.__setitem__.assert_called_with(3, 'fish') >>> mock.__getitem__.return_value = 'result' >>> mock[2] 'result'
By default many of the protocol methods are required to return objects of a
specific type. These methods are preconfigured with a default return value, so
that... | >>> mock = MagicMock() >>> mock[3] = 'fish' >>> mock.__setitem__.assert_called_with(3, 'fish') >>> mock.__getitem__.return_value = 'result' >>> mock[2] 'result'
By default many of the protocol methods are required to return objects of a
specific type. These methods are preconfigured with a default return value, so
that... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
17688260-da38-4890-939d-d32c33c5e7c9 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,757 | supabase-export-v2 | 0a6bd82fa9c191e9 | *spec_set*, *autospec* and *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`, :func:`patch.object` takes arbitrary keyword arguments for configuring the mock object it creates.
When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
for choosing which methods to wr... | trusted_official_docs | CPython Docs | *spec_set*, *autospec* and *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`, :func:`patch.object` takes arbitrary keyword arguments for configuring the mock object it creates.
When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
for choosing which methods to wr... | *spec_set*, *autospec* and *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`, :func:`patch.object` takes arbitrary keyword arguments for configuring the mock object it creates.
When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
for choosing which methods to wr... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
177b4f1c-7543-4d2a-81f5-35bf62d4f297 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,542 | supabase-export-v2 | 5ee0897ce58f8a27 | mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made.
For non-callable mocks the callable variant will be used (rather than
any custom subclass). | trusted_official_docs | CPython Docs | mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made.
For non-callable mocks the callable variant will be used (rather than
any custom subclass). | mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made.
For non-callable mocks the callable variant will be used (rather than
any custom subclass). | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1832bee4-6694-4ac6-83c8-c18d3c26a91b | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,604 | supabase-export-v2 | a18fdf5d23a31405 | = {'method.return_value': 3, 'other.side_effect': KeyError} >>> mock = Mock(some_attribute='eggs', **attrs) >>> mock.some_attribute 'eggs' >>> mock.method() 3 >>> mock.other() Traceback (most recent call last): ... KeyError
A callable mock which was created with a *spec* (or a *spec_set*) will
introspect the specificat... | trusted_official_docs | CPython Docs | = {'method.return_value': 3, 'other.side_effect': KeyError} >>> mock = Mock(some_attribute='eggs', **attrs) >>> mock.some_attribute 'eggs' >>> mock.method() 3 >>> mock.other() Traceback (most recent call last): ... KeyError
A callable mock which was created with a *spec* (or a *spec_set*) will
introspect the specificat... | = {'method.return_value': 3, 'other.side_effect': KeyError} >>> mock = Mock(some_attribute='eggs', **attrs) >>> mock.some_attribute 'eggs' >>> mock.method() 3 >>> mock.other() Traceback (most recent call last): ... KeyError
A callable mock which was created with a *spec* (or a *spec_set*) will
introspect the specificat... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
19134564-77dc-48d8-85b5-268bac5d2100 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 27,006 | supabase-export-v2 | 57625cd9bb55c330 | >>> order_mock = Mock(spec=Order, wraps=Order) >>> order_mock.return_value sentinel.DEFAULT >>> order_mock.get_value.return_value sentinel.DEFAULT
The order of precedence will ignore this value and it will move to the last
successor which is the wrapped object. | trusted_official_docs | CPython Docs | >>> order_mock = Mock(spec=Order, wraps=Order) >>> order_mock.return_value sentinel.DEFAULT >>> order_mock.get_value.return_value sentinel.DEFAULT
The order of precedence will ignore this value and it will move to the last
successor which is the wrapped object. | >>> order_mock = Mock(spec=Order, wraps=Order) >>> order_mock.return_value sentinel.DEFAULT >>> order_mock.get_value.return_value sentinel.DEFAULT
The order of precedence will ignore this value and it will move to the last
successor which is the wrapped object. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1952605d-1d10-4fe7-a93b-351837b03ab0 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,594 | supabase-export-v2 | de72b18a1ed5cab3 | :attr:`!__class__` is assignable to, this allows a mock to pass an :func:`isinstance` check without forcing you to use a spec:
>>> mock = Mock()
>>> mock.__class__ = dict
>>> isinstance(mock, dict)
True | trusted_official_docs | CPython Docs | :attr:`!__class__` is assignable to, this allows a mock to pass an :func:`isinstance` check without forcing you to use a spec:
>>> mock = Mock()
>>> mock.__class__ = dict
>>> isinstance(mock, dict)
True | :attr:`!__class__` is assignable to, this allows a mock to pass an :func:`isinstance` check without forcing you to use a spec:
>>> mock = Mock()
>>> mock.__class__ = dict
>>> isinstance(mock, dict)
True | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
197c915c-b0f1-47ab-8700-f08693738dcf | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,661 | supabase-export-v2 | ac40b63466d56f4c | the length of the list is the number of times it has been awaited). Before any awaits have been made it is an empty list.
>>> mock = AsyncMock()
>>> async def main(*args):
... await mock(*args)
... >>> mock.await_args_list
[]
>>> asyncio.run(main('foo'))
>>> mock.await_args_list
[call('foo')]
>>> asyncio.run(ma... | trusted_official_docs | CPython Docs | the length of the list is the number of times it has been awaited). Before any awaits have been made it is an empty list.
>>> mock = AsyncMock()
>>> async def main(*args):
... await mock(*args)
... >>> mock.await_args_list
[]
>>> asyncio.run(main('foo'))
>>> mock.await_args_list
[call('foo')]
>>> asyncio.run(ma... | the length of the list is the number of times it has been awaited). Before any awaits have been made it is an empty list.
>>> mock = AsyncMock()
>>> async def main(*args):
... await mock(*args)
... >>> mock.await_args_list
[]
>>> asyncio.run(main('foo'))
>>> mock.await_args_list
[call('foo')]
>>> asyncio.run(ma... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
198a78e5-9a40-4d7b-8e37-851623628bad | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,576 | supabase-export-v2 | 3ebf634d9f00e440 | .. attribute:: call_args_list
This is a list of all the calls made to the mock object in sequence
(so the length of the list is the number of times it has been
called). Before any calls have been made it is an empty list. The
:data:`call` object can be used for conveniently constructing lists of
calls to compare wi... | trusted_official_docs | CPython Docs | .. attribute:: call_args_list
This is a list of all the calls made to the mock object in sequence
(so the length of the list is the number of times it has been
called). Before any calls have been made it is an empty list. The
:data:`call` object can be used for conveniently constructing lists of
calls to compare wi... | .. attribute:: call_args_list
This is a list of all the calls made to the mock object in sequence
(so the length of the list is the number of times it has been
called). Before any calls have been made it is an empty list. The
:data:`call` object can be used for conveniently constructing lists of
calls to compare wi... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
19a787f7-7494-49a3-b635-f6dfb07f00c2 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,660 | supabase-export-v2 | e44378543b4cefbf | .. attribute:: await_args_list
This is a list of all the awaits made to the mock object in sequence (so the
length of the list is the number of times it has been awaited). Before any
awaits have been made it is an empty list. | trusted_official_docs | CPython Docs | .. attribute:: await_args_list
This is a list of all the awaits made to the mock object in sequence (so the
length of the list is the number of times it has been awaited). Before any
awaits have been made it is an empty list. | .. attribute:: await_args_list
This is a list of all the awaits made to the mock object in sequence (so the
length of the list is the number of times it has been awaited). Before any
awaits have been made it is an empty list. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1a4e156f-2680-4b2d-a0e7-16642d19606f | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,454 | supabase-export-v2 | d69f56821052c2d8 | = {'key': 'value'} >>> original = foo.copy() >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True): ... assert foo == {'newkey': 'newvalue'} ... >>> assert foo == original
Mock supports the mocking of Python :ref:`magic methods <magic-methods>`. The
easiest way of using magic methods is with the :class:`MagicMoc... | trusted_official_docs | CPython Docs | = {'key': 'value'} >>> original = foo.copy() >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True): ... assert foo == {'newkey': 'newvalue'} ... >>> assert foo == original
Mock supports the mocking of Python :ref:`magic methods <magic-methods>`. The
easiest way of using magic methods is with the :class:`MagicMoc... | = {'key': 'value'} >>> original = foo.copy() >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True): ... assert foo == {'newkey': 'newvalue'} ... >>> assert foo == original
Mock supports the mocking of Python :ref:`magic methods <magic-methods>`. The
easiest way of using magic methods is with the :class:`MagicMoc... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1aa1f589-9c11-4ee7-866d-3cb2742e6299 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,739 | supabase-export-v2 | ea24564291e73346 | >>> Original = Class >>> patcher = patch('__main__.Class', spec=True) >>> MockClass = patcher.start() >>> instance = MockClass() >>> assert isinstance(instance, Original) >>> patcher.stop()
The *new_callable* argument is useful where you want to use an alternative
class to the default :class:`MagicMock` for the created... | trusted_official_docs | CPython Docs | >>> Original = Class >>> patcher = patch('__main__.Class', spec=True) >>> MockClass = patcher.start() >>> instance = MockClass() >>> assert isinstance(instance, Original) >>> patcher.stop()
The *new_callable* argument is useful where you want to use an alternative
class to the default :class:`MagicMock` for the created... | >>> Original = Class >>> patcher = patch('__main__.Class', spec=True) >>> MockClass = patcher.start() >>> instance = MockClass() >>> assert isinstance(instance, Original) >>> patcher.stop()
The *new_callable* argument is useful where you want to use an alternative
class to the default :class:`MagicMock` for the created... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1af2f491-70c2-4d67-affc-5e80f6bf820e | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,539 | supabase-export-v2 | 05e941e315010ec0 | :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results. For mocks with a *spec* this includes all the permitted attributes for the mock.
See :data:`FILTER_DIR` for what this filtering does, and how to
switch it off. | trusted_official_docs | CPython Docs | :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results. For mocks with a *spec* this includes all the permitted attributes for the mock.
See :data:`FILTER_DIR` for what this filtering does, and how to
switch it off. | :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results. For mocks with a *spec* this includes all the permitted attributes for the mock.
See :data:`FILTER_DIR` for what this filtering does, and how to
switch it off. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1b323d04-6c57-4c5e-b4cd-d64cd62e75be | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,490 | supabase-export-v2 | 7c3edc7f1a32adc0 | Assert that the mock was called exactly once.
>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
Traceback (most recent call last):
... AssertionError: Expected ... | trusted_official_docs | CPython Docs | Assert that the mock was called exactly once.
>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
Traceback (most recent call last):
... AssertionError: Expected ... | Assert that the mock was called exactly once.
>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
Traceback (most recent call last):
... AssertionError: Expected ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1b5ca995-1f82-49e6-9331-0a1cbf2f5729 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,919 | supabase-export-v2 | 7bf88cb6dceed1e8 | but either not care about some of the arguments or want to pull them individually out of :attr:`~Mock.call_args` and make more complex assertions on them.
To ignore certain arguments you can pass in objects that compare equal to
*everything*. Calls to :meth:`~Mock.assert_called_with` and
:meth:`~Mock.assert_called_once... | trusted_official_docs | CPython Docs | but either not care about some of the arguments or want to pull them individually out of :attr:`~Mock.call_args` and make more complex assertions on them.
To ignore certain arguments you can pass in objects that compare equal to
*everything*. Calls to :meth:`~Mock.assert_called_with` and
:meth:`~Mock.assert_called_once... | but either not care about some of the arguments or want to pull them individually out of :attr:`~Mock.call_args` and make more complex assertions on them.
To ignore certain arguments you can pass in objects that compare equal to
*everything*. Calls to :meth:`~Mock.assert_called_with` and
:meth:`~Mock.assert_called_once... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1c461b54-4d45-4138-b645-1479732d0be4 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,940 | supabase-export-v2 | 47838e7cefe314b6 | customize this mock for yourself. When that is insufficient, one of the in-memory filesystem packages on `PyPI <https://pypi.org>`_ can offer a realistic filesystem for testing.
.. versionchanged:: 3.4
Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support. The mock of :meth:`~io.RawIOBase.read` ch... | trusted_official_docs | CPython Docs | customize this mock for yourself. When that is insufficient, one of the in-memory filesystem packages on `PyPI <https://pypi.org>`_ can offer a realistic filesystem for testing.
.. versionchanged:: 3.4
Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support. The mock of :meth:`~io.RawIOBase.read` ch... | customize this mock for yourself. When that is insufficient, one of the in-memory filesystem packages on `PyPI <https://pypi.org>`_ can offer a realistic filesystem for testing.
.. versionchanged:: 3.4
Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support. The mock of :meth:`~io.RawIOBase.read` ch... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1ca80f16-8de8-4321-825f-d52ae6952df8 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,783 | supabase-export-v2 | e67b32c1fecf3e1c | support item getting, setting, deleting and either iteration or membership test. This corresponds to the magic methods :meth:`~object.__getitem__`, :meth:`~object.__setitem__`, :meth:`~object.__delitem__` and either :meth:`~container.__iter__` or :meth:`~object.__contains__`.
>>> class Container:
... def __init__(self... | trusted_official_docs | CPython Docs | support item getting, setting, deleting and either iteration or membership test. This corresponds to the magic methods :meth:`~object.__getitem__`, :meth:`~object.__setitem__`, :meth:`~object.__delitem__` and either :meth:`~container.__iter__` or :meth:`~object.__contains__`.
>>> class Container:
... def __init__(self... | support item getting, setting, deleting and either iteration or membership test. This corresponds to the magic methods :meth:`~object.__getitem__`, :meth:`~object.__setitem__`, :meth:`~object.__delitem__` and either :meth:`~container.__iter__` or :meth:`~object.__contains__`.
>>> class Container:
... def __init__(self... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1ca83726-e8f0-4aca-8783-06ac262aff21 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,441 | supabase-export-v2 | 6d8fce058c854380 | >>> from unittest.mock import MagicMock >>> thing = ProductionClass() >>> thing.method = MagicMock(return_value=3) >>> thing.method(3, 4, 5, key='value') 3 >>> thing.method.assert_called_with(3, 4, 5, key='value')
:attr:`~Mock.side_effect` allows you to perform side effects, including raising an
exception when a mock i... | trusted_official_docs | CPython Docs | >>> from unittest.mock import MagicMock >>> thing = ProductionClass() >>> thing.method = MagicMock(return_value=3) >>> thing.method(3, 4, 5, key='value') 3 >>> thing.method.assert_called_with(3, 4, 5, key='value')
:attr:`~Mock.side_effect` allows you to perform side effects, including raising an
exception when a mock i... | >>> from unittest.mock import MagicMock >>> thing = ProductionClass() >>> thing.method = MagicMock(return_value=3) >>> thing.method(3, 4, 5, key='value') 3 >>> thing.method.assert_called_with(3, 4, 5, key='value')
:attr:`~Mock.side_effect` allows you to perform side effects, including raising an
exception when a mock i... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1d1456bc-58ab-4d68-bd48-a3d25168bc69 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,497 | supabase-export-v2 | cf8edd6391eb293f | Assert that the mock was called exactly once and that call was with the specified arguments.
>>> mock = Mock(return_value=None)
>>> mock('foo', bar='baz')
>>> mock.assert_called_once_with('foo', bar='baz')
>>> mock('other', bar='values')
>>> mock.assert_called_once_with('other', bar='values')
Traceback (most recen... | trusted_official_docs | CPython Docs | Assert that the mock was called exactly once and that call was with the specified arguments.
>>> mock = Mock(return_value=None)
>>> mock('foo', bar='baz')
>>> mock.assert_called_once_with('foo', bar='baz')
>>> mock('other', bar='values')
>>> mock.assert_called_once_with('other', bar='values')
Traceback (most recen... | Assert that the mock was called exactly once and that call was with the specified arguments.
>>> mock = Mock(return_value=None)
>>> mock('foo', bar='baz')
>>> mock.assert_called_once_with('foo', bar='baz')
>>> mock('other', bar='values')
>>> mock.assert_called_once_with('other', bar='values')
Traceback (most recen... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1d4ff7a4-5830-4d89-8cfc-f4758c27c9b3 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,477 | supabase-export-v2 | 09698a46722d6478 | A *side_effect* can be cleared by setting it to ``None``.
* *return_value*: The value returned when the mock is called. By default
this is a new Mock (created on first access). See the
:attr:`return_value` attribute. | trusted_official_docs | CPython Docs | A *side_effect* can be cleared by setting it to ``None``.
* *return_value*: The value returned when the mock is called. By default
this is a new Mock (created on first access). See the
:attr:`return_value` attribute. | A *side_effect* can be cleared by setting it to ``None``.
* *return_value*: The value returned when the mock is called. By default
this is a new Mock (created on first access). See the
:attr:`return_value` attribute. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1dd2d807-4289-4652-9382-c35dcb4649fb | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,738 | supabase-export-v2 | 90eef2b8d6d002b9 | you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the return value of the created mock will have the same spec. ::
>>> Original = Class
>>> patcher = patch('__main__.Class', spec=True)
>>> MockClass = patcher.start()
>>> instance = MockClass()
>>> assert isinstance(instance, Original)
>>>... | trusted_official_docs | CPython Docs | you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the return value of the created mock will have the same spec. ::
>>> Original = Class
>>> patcher = patch('__main__.Class', spec=True)
>>> MockClass = patcher.start()
>>> instance = MockClass()
>>> assert isinstance(instance, Original)
>>>... | you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the return value of the created mock will have the same spec. ::
>>> Original = Class
>>> patcher = patch('__main__.Class', spec=True)
>>> MockClass = patcher.start()
>>> instance = MockClass()
>>> assert isinstance(instance, Original)
>>>... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1de61fb4-659f-4c01-8e66-305d4e54f1bb | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,792 | supabase-export-v2 | 2d3c1db532ea8332 | use :data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator then the created mocks are passed into the decorated function by keyword. ::
>>> thing = object()
>>> other = object() | trusted_official_docs | CPython Docs | use :data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator then the created mocks are passed into the decorated function by keyword. ::
>>> thing = object()
>>> other = object() | use :data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator then the created mocks are passed into the decorated function by keyword. ::
>>> thing = object()
>>> other = object() | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1ead8e7f-07b2-4e74-9a50-0f0b208a4439 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,972 | supabase-export-v2 | a9285b5c8cb438b8 | you will just be able to add ``autospec=True`` to your existing :func:`patch` calls and then be protected against bugs due to typos and api changes.
As well as using *autospec* through :func:`patch` there is a
:func:`create_autospec` for creating autospecced mocks directly: | trusted_official_docs | CPython Docs | you will just be able to add ``autospec=True`` to your existing :func:`patch` calls and then be protected against bugs due to typos and api changes.
As well as using *autospec* through :func:`patch` there is a
:func:`create_autospec` for creating autospecced mocks directly: | you will just be able to add ``autospec=True`` to your existing :func:`patch` calls and then be protected against bugs due to typos and api changes.
As well as using *autospec* through :func:`patch` there is a
:func:`create_autospec` for creating autospecced mocks directly: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1f95359f-213d-4094-8b53-7153f691a705 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,664 | supabase-export-v2 | 50bd64ac144c0d52 | of :class:`MagicMock` for multithreading tests. The :class:`ThreadingMock` object provides extra methods to wait for a call to be invoked, rather than assert on it immediately.
The default timeout is specified by the ``timeout`` argument, or if unset by the
:attr:`ThreadingMock.DEFAULT_TIMEOUT` attribute, which defaul... | trusted_official_docs | CPython Docs | of :class:`MagicMock` for multithreading tests. The :class:`ThreadingMock` object provides extra methods to wait for a call to be invoked, rather than assert on it immediately.
The default timeout is specified by the ``timeout`` argument, or if unset by the
:attr:`ThreadingMock.DEFAULT_TIMEOUT` attribute, which defaul... | of :class:`MagicMock` for multithreading tests. The :class:`ThreadingMock` object provides extra methods to wait for a call to be invoked, rather than assert on it immediately.
The default timeout is specified by the ``timeout`` argument, or if unset by the
:attr:`ThreadingMock.DEFAULT_TIMEOUT` attribute, which defaul... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1fb07f34-a004-415a-94fe-849bd5280f5c | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,974 | supabase-export-v2 | 312f8f7abd3deca8 | >>> from urllib import request >>> mock_request = create_autospec(request) >>> mock_request.Request('foo', 'bar') <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
This isn't without caveats and limitations however, which is why it is not
the default behaviour. In order to know what attributes are av... | trusted_official_docs | CPython Docs | >>> from urllib import request >>> mock_request = create_autospec(request) >>> mock_request.Request('foo', 'bar') <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
This isn't without caveats and limitations however, which is why it is not
the default behaviour. In order to know what attributes are av... | >>> from urllib import request >>> mock_request = create_autospec(request) >>> mock_request.Request('foo', 'bar') <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
This isn't without caveats and limitations however, which is why it is not
the default behaviour. In order to know what attributes are av... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2041a03b-0bf7-483d-9102-83dc1bc2453e | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,965 | supabase-export-v2 | f37b2d8464f844ee | >>> from urllib import request >>> patcher = patch('__main__.request', autospec=True) >>> mock_request = patcher.start() >>> request is mock_request True >>> mock_request.Request <MagicMock name='request.Request' spec='Request' id='...'>
You can see that :class:`!request.Request` has a spec. :class:`!request.Request` t... | trusted_official_docs | CPython Docs | >>> from urllib import request >>> patcher = patch('__main__.request', autospec=True) >>> mock_request = patcher.start() >>> request is mock_request True >>> mock_request.Request <MagicMock name='request.Request' spec='Request' id='...'>
You can see that :class:`!request.Request` has a spec. :class:`!request.Request` t... | >>> from urllib import request >>> patcher = patch('__main__.request', autospec=True) >>> mock_request = patcher.start() >>> request is mock_request True >>> mock_request.Request <MagicMock name='request.Request' spec='Request' id='...'>
You can see that :class:`!request.Request` has a spec. :class:`!request.Request` t... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
20a1e457-733b-469a-8f8e-ee8f7e4c5214 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,963 | supabase-export-v2 | 6e937803160d0941 | accessed) you can use it with very complex or deeply nested objects (like modules that import modules that import modules) without a big performance hit.
Here's an example of it in use:: | trusted_official_docs | CPython Docs | accessed) you can use it with very complex or deeply nested objects (like modules that import modules that import modules) without a big performance hit.
Here's an example of it in use:: | accessed) you can use it with very complex or deeply nested objects (like modules that import modules that import modules) without a big performance hit.
Here's an example of it in use:: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
20ad1a8e-92c4-46ea-8a5d-6082772131fe | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,774 | supabase-export-v2 | 4a06e48ca1fddc02 | >>> foo = {} >>> @patch.dict(foo, {'newkey': 'newvalue'}) ... def test(): ... assert foo == {'newkey': 'newvalue'} ... >>> test() >>> assert foo == {}
When used as a class decorator :func:`patch.dict` honours
``patch.TEST_PREFIX`` (default to ``'test'``) for choosing which methods to wrap: | trusted_official_docs | CPython Docs | >>> foo = {} >>> @patch.dict(foo, {'newkey': 'newvalue'}) ... def test(): ... assert foo == {'newkey': 'newvalue'} ... >>> test() >>> assert foo == {}
When used as a class decorator :func:`patch.dict` honours
``patch.TEST_PREFIX`` (default to ``'test'``) for choosing which methods to wrap: | >>> foo = {} >>> @patch.dict(foo, {'newkey': 'newvalue'}) ... def test(): ... assert foo == {'newkey': 'newvalue'} ... >>> test() >>> assert foo == {}
When used as a class decorator :func:`patch.dict` honours
``patch.TEST_PREFIX`` (default to ``'test'``) for choosing which methods to wrap: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
22b941f2-db20-4dca-a8ab-eec900712af0 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,887 | supabase-export-v2 | 7ce7ad46e3d7514a | name. Accessing the same attribute will always return the same object. The objects returned have a sensible repr so that test failure messages are readable.
.. versionchanged:: 3.7
The ``sentinel`` attributes now preserve their identity when they are
:mod:`copied <copy>` or :mod:`pickled <pickle>`. | trusted_official_docs | CPython Docs | name. Accessing the same attribute will always return the same object. The objects returned have a sensible repr so that test failure messages are readable.
.. versionchanged:: 3.7
The ``sentinel`` attributes now preserve their identity when they are
:mod:`copied <copy>` or :mod:`pickled <pickle>`. | name. Accessing the same attribute will always return the same object. The objects returned have a sensible repr so that test failure messages are readable.
.. versionchanged:: 3.7
The ``sentinel`` attributes now preserve their identity when they are
:mod:`copied <copy>` or :mod:`pickled <pickle>`. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
22e58395-35d9-46c5-b1e7-40233532744b | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,440 | supabase-export-v2 | ec138cd31faabb8f | used. You can configure them, to specify return values or limit what attributes are available, and then make assertions about how they have been used:
>>> from unittest.mock import MagicMock
>>> thing = ProductionClass()
>>> thing.method = MagicMock(return_value=3)
>>> thing.method(3, 4, 5, key='value')
3
>>> thin... | trusted_official_docs | CPython Docs | used. You can configure them, to specify return values or limit what attributes are available, and then make assertions about how they have been used:
>>> from unittest.mock import MagicMock
>>> thing = ProductionClass()
>>> thing.method = MagicMock(return_value=3)
>>> thing.method(3, 4, 5, key='value')
3
>>> thin... | used. You can configure them, to specify return values or limit what attributes are available, and then make assertions about how they have been used:
>>> from unittest.mock import MagicMock
>>> thing = ProductionClass()
>>> thing.method = MagicMock(return_value=3)
>>> thing.method(3, 4, 5, key='value')
3
>>> thin... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
23218a74-ece9-4de5-b407-377809944f2c | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,931 | supabase-export-v2 | 0d50a480215c0c1b | >>> dir(Mock()) ['assert_any_call', 'assert_called', 'assert_called_once', 'assert_called_once_with', 'assert_called_with', 'assert_has_calls', 'assert_not_called', 'attach_mock', ... >>> from urllib import request >>> dir(Mock(spec=request)) ['AbstractBasicAuthHandler', 'AbstractDigestAuthHandler', 'AbstractHTTPHandle... | trusted_official_docs | CPython Docs | >>> dir(Mock()) ['assert_any_call', 'assert_called', 'assert_called_once', 'assert_called_once_with', 'assert_called_with', 'assert_has_calls', 'assert_not_called', 'attach_mock', ... >>> from urllib import request >>> dir(Mock(spec=request)) ['AbstractBasicAuthHandler', 'AbstractDigestAuthHandler', 'AbstractHTTPHandle... | >>> dir(Mock()) ['assert_any_call', 'assert_called', 'assert_called_once', 'assert_called_once_with', 'assert_called_with', 'assert_has_calls', 'assert_not_called', 'attach_mock', ... >>> from urllib import request >>> dir(Mock(spec=request)) ['AbstractBasicAuthHandler', 'AbstractDigestAuthHandler', 'AbstractHTTPHandle... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
234b32df-07d5-480c-b565-b6e849198ca5 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,697 | supabase-export-v2 | 4c1e54fdeeac0b1c | You "block" attributes by deleting them. Once deleted, accessing an attribute will raise an :exc:`AttributeError`.
>>> mock = MagicMock()
>>> hasattr(mock, 'm')
True
>>> del mock.m
>>> hasattr(mock, 'm')
False
>>> del mock.f
>>> mock.f
Traceback (most recent call last):
... AttributeError: f | trusted_official_docs | CPython Docs | You "block" attributes by deleting them. Once deleted, accessing an attribute will raise an :exc:`AttributeError`.
>>> mock = MagicMock()
>>> hasattr(mock, 'm')
True
>>> del mock.m
>>> hasattr(mock, 'm')
False
>>> del mock.f
>>> mock.f
Traceback (most recent call last):
... AttributeError: f | You "block" attributes by deleting them. Once deleted, accessing an attribute will raise an :exc:`AttributeError`.
>>> mock = MagicMock()
>>> hasattr(mock, 'm')
True
>>> del mock.m
>>> hasattr(mock, 'm')
False
>>> del mock.f
>>> mock.f
Traceback (most recent call last):
... AttributeError: f | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
235d34e6-e227-46cf-959d-4ae6f1aab0b8 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,527 | supabase-export-v2 | 0d7de4fa4fc95f75 | mock. *spec* can either be an object or a list of strings. Only attributes on the *spec* can be fetched as attributes from the mock.
If *spec_set* is true then only attributes on the spec can be set. | trusted_official_docs | CPython Docs | mock. *spec* can either be an object or a list of strings. Only attributes on the *spec* can be fetched as attributes from the mock.
If *spec_set* is true then only attributes on the spec can be set. | mock. *spec* can either be an object or a list of strings. Only attributes on the *spec* can be fetched as attributes from the mock.
If *spec_set* is true then only attributes on the spec can be set. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2641a279-2f47-46e5-9b20-cbbe33e1fd76 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,734 | supabase-export-v2 | 9cc78c8ca864c7b4 | :class:`MagicMock` *instance*. If the class is instantiated in the code under test then it will be the :attr:`~Mock.return_value` of the mock that will be used.
If the class is instantiated multiple times you could use
:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
can set the *return_value... | trusted_official_docs | CPython Docs | :class:`MagicMock` *instance*. If the class is instantiated in the code under test then it will be the :attr:`~Mock.return_value` of the mock that will be used.
If the class is instantiated multiple times you could use
:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
can set the *return_value... | :class:`MagicMock` *instance*. If the class is instantiated in the code under test then it will be the :attr:`~Mock.return_value` of the mock that will be used.
If the class is instantiated multiple times you could use
:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
can set the *return_value... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
266a815e-672e-4db8-9abe-ab9a1407f0b9 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,882 | supabase-export-v2 | ae33558d4a833aa3 | Magic methods that are supported but not setup by default in ``MagicMock`` are:
* ``__subclasses__``
* ``__dir__``
* ``__format__``
* ``__get__``, ``__set__`` and ``__delete__``
* ``__reversed__`` and ``__missing__``
* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
``__getstate__`` and ``_... | trusted_official_docs | CPython Docs | Magic methods that are supported but not setup by default in ``MagicMock`` are:
* ``__subclasses__``
* ``__dir__``
* ``__format__``
* ``__get__``, ``__set__`` and ``__delete__``
* ``__reversed__`` and ``__missing__``
* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
``__getstate__`` and ``_... | Magic methods that are supported but not setup by default in ``MagicMock`` are:
* ``__subclasses__``
* ``__dir__``
* ``__format__``
* ``__get__``, ``__set__`` and ``__delete__``
* ``__reversed__`` and ``__missing__``
* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
``__getstate__`` and ``_... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2886e592-7fdc-4b21-92ae-bbb8093bec15 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,642 | supabase-export-v2 | f3a07a05824b9eeb | Assert the mock has ever been awaited with the specified arguments.
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
... await mock(*args, **kwargs)
... >>> asyncio.run(main('foo', bar='bar'))
>>> asyncio.run(main('hello'))
>>> mock.assert_any_await('foo', bar='bar')
>>> mock.assert_any_await('other')
... | trusted_official_docs | CPython Docs | Assert the mock has ever been awaited with the specified arguments.
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
... await mock(*args, **kwargs)
... >>> asyncio.run(main('foo', bar='bar'))
>>> asyncio.run(main('hello'))
>>> mock.assert_any_await('foo', bar='bar')
>>> mock.assert_any_await('other')
... | Assert the mock has ever been awaited with the specified arguments.
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
... await mock(*args, **kwargs)
... >>> asyncio.run(main('foo', bar='bar'))
>>> asyncio.run(main('hello'))
>>> mock.assert_any_await('foo', bar='bar')
>>> mock.assert_any_await('other')
... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
28c1e03f-2e00-40b7-81e6-e65b4894d36d | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,837 | supabase-export-v2 | ff04f6e1c1cae402 | Patching Descriptors and Proxy Objects ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Both patch_ and patch.object_ correctly patch and restore descriptors: class
methods, static methods and properties. You should patch these on the *class*
rather than an instance. They also work with *some* objects
that proxy attribute access... | trusted_official_docs | CPython Docs | Patching Descriptors and Proxy Objects ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Both patch_ and patch.object_ correctly patch and restore descriptors: class
methods, static methods and properties. You should patch these on the *class*
rather than an instance. They also work with *some* objects
that proxy attribute access... | Patching Descriptors and Proxy Objects ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Both patch_ and patch.object_ correctly patch and restore descriptors: class
methods, static methods and properties. You should patch these on the *class*
rather than an instance. They also work with *some* objects
that proxy attribute access... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
28e09445-4bd7-474d-8701-9b8efffebf43 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,696 | supabase-export-v2 | d214a8ff1050e832 | :exc:`AttributeError` when an attribute is fetched. You can do this by providing an object as a :attr:`!spec` for a mock, but that isn't always convenient.
You "block" attributes by deleting them. Once deleted, accessing an attribute
will raise an :exc:`AttributeError`. | trusted_official_docs | CPython Docs | :exc:`AttributeError` when an attribute is fetched. You can do this by providing an object as a :attr:`!spec` for a mock, but that isn't always convenient.
You "block" attributes by deleting them. Once deleted, accessing an attribute
will raise an :exc:`AttributeError`. | :exc:`AttributeError` when an attribute is fetched. You can do this by providing an object as a :attr:`!spec` for a mock, but that isn't always convenient.
You "block" attributes by deleting them. Once deleted, accessing an attribute
will raise an :exc:`AttributeError`. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
29266ba8-68f4-42f0-85da-8825522400d6 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,473 | supabase-export-v2 | 33a1c177f7387032 | *spec*. If used, attempting to *set* or get an attribute on the mock that isn't on the object passed as *spec_set* will raise an :exc:`AttributeError`.
* *side_effect*: A function to be called whenever the Mock is called. See
the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or
dynamically changi... | trusted_official_docs | CPython Docs | *spec*. If used, attempting to *set* or get an attribute on the mock that isn't on the object passed as *spec_set* will raise an :exc:`AttributeError`.
* *side_effect*: A function to be called whenever the Mock is called. See
the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or
dynamically changi... | *spec*. If used, attempting to *set* or get an attribute on the mock that isn't on the object passed as *spec_set* will raise an :exc:`AttributeError`.
* *side_effect*: A function to be called whenever the Mock is called. See
the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or
dynamically changi... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
29900235-a718-415c-8a8f-cd4f307ca466 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,744 | supabase-export-v2 | 0094669699f553c1 | be done in the call to patch. Any arbitrary keywords you pass into the call will be used to set attributes on the created mock::
>>> patcher = patch('__main__.thing', first='one', second='two')
>>> mock_thing = patcher.start()
>>> mock_thing.first
'one'
>>> mock_thing.second
'two' | trusted_official_docs | CPython Docs | be done in the call to patch. Any arbitrary keywords you pass into the call will be used to set attributes on the created mock::
>>> patcher = patch('__main__.thing', first='one', second='two')
>>> mock_thing = patcher.start()
>>> mock_thing.first
'one'
>>> mock_thing.second
'two' | be done in the call to patch. Any arbitrary keywords you pass into the call will be used to set attributes on the created mock::
>>> patcher = patch('__main__.thing', first='one', second='two')
>>> mock_thing = patcher.start()
>>> mock_thing.first
'one'
>>> mock_thing.second
'two' | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2a3a1710-9b5e-4b2c-85c8-e47ee06fc814 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,826 | supabase-export-v2 | 40008d2922e2edb0 | Where to patch ~~~~~~~~~~~~~~
:func:`patch` works by (temporarily) changing the object that a *name* points to with
another one. There can be many names pointing to any individual object, so
for patching to work you must ensure that you patch the name used by the system
under test. | trusted_official_docs | CPython Docs | Where to patch ~~~~~~~~~~~~~~
:func:`patch` works by (temporarily) changing the object that a *name* points to with
another one. There can be many names pointing to any individual object, so
for patching to work you must ensure that you patch the name used by the system
under test. | Where to patch ~~~~~~~~~~~~~~
:func:`patch` works by (temporarily) changing the object that a *name* points to with
another one. There can be many names pointing to any individual object, so
for patching to work you must ensure that you patch the name used by the system
under test. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2b6b9232-31d3-41b7-a787-6b10ee474dd3 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,717 | supabase-export-v2 | 624ae4f14afd07df | the body of the function or with statement, the *target* is patched with a *new* object. When the function/with statement exits the patch is undone.
If *new* is omitted, then the target is replaced with an
:class:`AsyncMock` if the patched object is an async function or
a :class:`MagicMock` otherwise. If :func:`patch... | trusted_official_docs | CPython Docs | the body of the function or with statement, the *target* is patched with a *new* object. When the function/with statement exits the patch is undone.
If *new* is omitted, then the target is replaced with an
:class:`AsyncMock` if the patched object is an async function or
a :class:`MagicMock` otherwise. If :func:`patch... | the body of the function or with statement, the *target* is patched with a *new* object. When the function/with statement exits the patch is undone.
If *new* is omitted, then the target is replaced with an
:class:`AsyncMock` if the patched object is an async function or
a :class:`MagicMock` otherwise. If :func:`patch... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2c44242d-fa55-4d54-a6be-72cf9f349693 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,443 | supabase-export-v2 | 0eba961901140a9f | >>> from unittest.mock import Mock >>> mock = Mock(side_effect=KeyError('foo')) >>> mock() Traceback (most recent call last): ... KeyError: 'foo'
>>> values = {'a': 1, 'b': 2, 'c': 3}
>>> def side_effect(arg):
... return values[arg]
... >>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, ... | trusted_official_docs | CPython Docs | >>> from unittest.mock import Mock >>> mock = Mock(side_effect=KeyError('foo')) >>> mock() Traceback (most recent call last): ... KeyError: 'foo'
>>> values = {'a': 1, 'b': 2, 'c': 3}
>>> def side_effect(arg):
... return values[arg]
... >>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, ... | >>> from unittest.mock import Mock >>> mock = Mock(side_effect=KeyError('foo')) >>> mock() Traceback (most recent call last): ... KeyError: 'foo'
>>> values = {'a': 1, 'b': 2, 'c': 3}
>>> def side_effect(arg):
... return values[arg]
... >>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2c745278-16e7-4d6b-aaf7-515baf761e6f | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,928 | supabase-export-v2 | 14aa644639871213 | below, to only show useful members. If you dislike this filtering, or need to switch it off for diagnostic purposes, then set ``mock.FILTER_DIR = False``.
With filtering on, ``dir(some_mock)`` shows only useful attributes and will
include any dynamically created attributes that wouldn't normally be shown. If the mock w... | trusted_official_docs | CPython Docs | below, to only show useful members. If you dislike this filtering, or need to switch it off for diagnostic purposes, then set ``mock.FILTER_DIR = False``.
With filtering on, ``dir(some_mock)`` shows only useful attributes and will
include any dynamically created attributes that wouldn't normally be shown. If the mock w... | below, to only show useful members. If you dislike this filtering, or need to switch it off for diagnostic purposes, then set ``mock.FILTER_DIR = False``.
With filtering on, ``dir(some_mock)`` shows only useful attributes and will
include any dynamically created attributes that wouldn't normally be shown. If the mock w... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2d2b93db-00c9-4d20-9925-b80a9875e323 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,724 | supabase-export-v2 | 3fede25d54e04759 | Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an arbitrary object as the spec instead of the one being replaced.
By default :func:`patch` will fail to replace attributes that don't exist. If you pass in ``create=True``, and the attribute doesn't exist, patch will
create the attribute for yo... | trusted_official_docs | CPython Docs | Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an arbitrary object as the spec instead of the one being replaced.
By default :func:`patch` will fail to replace attributes that don't exist. If you pass in ``create=True``, and the attribute doesn't exist, patch will
create the attribute for yo... | Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an arbitrary object as the spec instead of the one being replaced.
By default :func:`patch` will fail to replace attributes that don't exist. If you pass in ``create=True``, and the attribute doesn't exist, patch will
create the attribute for yo... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2d5a9b40-44e9-4c80-bdff-ce7a04f5d615 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,768 | supabase-export-v2 | 06d03c7ad2295d4b | *values* can be a dictionary of values to set in the dictionary. *values* can also be an iterable of ``(key, value)`` pairs.
If *clear* is true then the dictionary will be cleared before the new
values are set. | trusted_official_docs | CPython Docs | *values* can be a dictionary of values to set in the dictionary. *values* can also be an iterable of ``(key, value)`` pairs.
If *clear* is true then the dictionary will be cleared before the new
values are set. | *values* can be a dictionary of values to set in the dictionary. *values* can also be an iterable of ``(key, value)`` pairs.
If *clear* is true then the dictionary will be cleared before the new
values are set. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2dd55598-bcc4-49fb-872d-874895044375 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,636 | supabase-export-v2 | 68451884150dc7f4 | Assert that the last await was with the specified arguments.
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
... await mock(*args, **kwargs)
... >>> asyncio.run(main('foo', bar='bar'))
>>> mock.assert_awaited_with('foo', bar='bar')
>>> mock.assert_awaited_with('other')
Traceback (most recent call last... | trusted_official_docs | CPython Docs | Assert that the last await was with the specified arguments.
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
... await mock(*args, **kwargs)
... >>> asyncio.run(main('foo', bar='bar'))
>>> mock.assert_awaited_with('foo', bar='bar')
>>> mock.assert_awaited_with('other')
Traceback (most recent call last... | Assert that the last await was with the specified arguments.
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
... await mock(*args, **kwargs)
... >>> asyncio.run(main('foo', bar='bar'))
>>> mock.assert_awaited_with('foo', bar='bar')
>>> mock.assert_awaited_with('other')
Traceback (most recent call last... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2ee35070-a9e4-4177-80dd-15fedc3a8047 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,876 | supabase-export-v2 | c2e73a9b43801d48 | >>> MagicMock() == 3 False >>> MagicMock() != 3 True >>> mock = MagicMock() >>> mock.__eq__.return_value = True >>> mock == 3 True
The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
required to be an iterator: | trusted_official_docs | CPython Docs | >>> MagicMock() == 3 False >>> MagicMock() != 3 True >>> mock = MagicMock() >>> mock.__eq__.return_value = True >>> mock == 3 True
The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
required to be an iterator: | >>> MagicMock() == 3 False >>> MagicMock() != 3 True >>> mock = MagicMock() >>> mock.__eq__.return_value = True >>> mock == 3 True
The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
required to be an iterator: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2f0f038e-808d-4ab5-a9b0-f67dfdf49b8d | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,978 | supabase-export-v2 | d3ed60a17f0c6fe6 | the mock after creation. Just because *autospec* doesn't allow you to fetch attributes that don't exist on the spec it doesn't prevent you setting them::
>>> with patch('__main__.Something', autospec=True):
... thing = Something()
... thing.a = 33
... | trusted_official_docs | CPython Docs | the mock after creation. Just because *autospec* doesn't allow you to fetch attributes that don't exist on the spec it doesn't prevent you setting them::
>>> with patch('__main__.Something', autospec=True):
... thing = Something()
... thing.a = 33
... | the mock after creation. Just because *autospec* doesn't allow you to fetch attributes that don't exist on the spec it doesn't prevent you setting them::
>>> with patch('__main__.Something', autospec=True):
... thing = Something()
... thing.a = 33
... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
30227ff0-eae5-40bc-8001-86e48f7da00a | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,987 | supabase-export-v2 | 75a4096d9025df47 | you to use an alternative object as the spec. Thankfully :func:`patch` supports this - you can simply pass the alternative object as the *autospec* argument::
>>> class Something:
... def __init__(self):
... self.a = 33
... >>> class SomethingForTest(Something):
... a = 33
... >>> p = patch('__main__.Something', a... | trusted_official_docs | CPython Docs | you to use an alternative object as the spec. Thankfully :func:`patch` supports this - you can simply pass the alternative object as the *autospec* argument::
>>> class Something:
... def __init__(self):
... self.a = 33
... >>> class SomethingForTest(Something):
... a = 33
... >>> p = patch('__main__.Something', a... | you to use an alternative object as the spec. Thankfully :func:`patch` supports this - you can simply pass the alternative object as the *autospec* argument::
>>> class Something:
... def __init__(self):
... self.a = 33
... >>> class SomethingForTest(Something):
... a = 33
... >>> p = patch('__main__.Something', a... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
30d0d2a5-acc7-4700-9c54-ed79e038cb19 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,890 | supabase-export-v2 | f67a3665624a2900 | In this example we monkey patch ``method`` to return ``sentinel.some_object``:
>>> real = ProductionClass()
>>> real.method = Mock(name="method")
>>> real.method.return_value = sentinel.some_object
>>> result = real.method()
>>> assert result is sentinel.some_object
>>> result
sentinel.some_object | trusted_official_docs | CPython Docs | In this example we monkey patch ``method`` to return ``sentinel.some_object``:
>>> real = ProductionClass()
>>> real.method = Mock(name="method")
>>> real.method.return_value = sentinel.some_object
>>> result = real.method()
>>> assert result is sentinel.some_object
>>> result
sentinel.some_object | In this example we monkey patch ``method`` to return ``sentinel.some_object``:
>>> real = ProductionClass()
>>> real.method = Mock(name="method")
>>> real.method.return_value = sentinel.some_object
>>> result = real.method()
>>> assert result is sentinel.some_object
>>> result
sentinel.some_object | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
313ae8c8-42dd-4352-8665-cea38f2c302b | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,986 | supabase-export-v2 | 8f9aba65d5ed3110 | >>> class Something: ... member = None ... >>> mock = create_autospec(Something) >>> mock.member.foo.bar.baz() <MagicMock name='mock.member.foo.bar.baz()' id='...'>
If modifying your production classes to add defaults isn't to your liking
then there are more options. One of these is simply to use an instance as the
spe... | trusted_official_docs | CPython Docs | >>> class Something: ... member = None ... >>> mock = create_autospec(Something) >>> mock.member.foo.bar.baz() <MagicMock name='mock.member.foo.bar.baz()' id='...'>
If modifying your production classes to add defaults isn't to your liking
then there are more options. One of these is simply to use an instance as the
spe... | >>> class Something: ... member = None ... >>> mock = create_autospec(Something) >>> mock.member.foo.bar.baz() <MagicMock name='mock.member.foo.bar.baz()' id='...'>
If modifying your production classes to add defaults isn't to your liking
then there are more options. One of these is simply to use an instance as the
spe... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
32b7ca82-3d51-4e7b-a502-29af3c7f50ef | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,795 | supabase-export-v2 | 74073a680451b168 | :func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments passed by keyword *after* any of the standard arguments created by :func:`patch`::
>>> @patch('sys.exit')
... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
... def test_function(mock_exit, other, thing):
... assert 'o... | trusted_official_docs | CPython Docs | :func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments passed by keyword *after* any of the standard arguments created by :func:`patch`::
>>> @patch('sys.exit')
... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
... def test_function(mock_exit, other, thing):
... assert 'o... | :func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments passed by keyword *after* any of the standard arguments created by :func:`patch`::
>>> @patch('sys.exit')
... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
... def test_function(mock_exit, other, thing):
... assert 'o... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
32be1e90-831a-4061-b4f1-e0e77e90180e | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,741 | supabase-export-v2 | 5dca092b26fb9281 | with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing: ... assert thing is mock_thing ... thing() ... Traceback (most recent call last): ... TypeError: 'NonCallableMock' object is not callable
Another use case might be to replace an object with an :class:`io.StringIO` instance:: | trusted_official_docs | CPython Docs | with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing: ... assert thing is mock_thing ... thing() ... Traceback (most recent call last): ... TypeError: 'NonCallableMock' object is not callable
Another use case might be to replace an object with an :class:`io.StringIO` instance:: | with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing: ... assert thing is mock_thing ... thing() ... Traceback (most recent call last): ... TypeError: 'NonCallableMock' object is not callable
Another use case might be to replace an object with an :class:`io.StringIO` instance:: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
330f3cb0-c55b-444e-81c9-fe86d09b8a24 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,947 | supabase-export-v2 | 80388cd737dcd2f8 | Mocking context managers with a :class:`MagicMock` is common enough and fiddly enough that a helper function is useful. ::
>>> m = mock_open()
>>> with patch('__main__.open', m):
... with open('foo', 'w') as h:
... h.write('some stuff')
... >>> m.mock_calls
[call('foo', 'w'),
call().__enter__(),
call().write('so... | trusted_official_docs | CPython Docs | Mocking context managers with a :class:`MagicMock` is common enough and fiddly enough that a helper function is useful. ::
>>> m = mock_open()
>>> with patch('__main__.open', m):
... with open('foo', 'w') as h:
... h.write('some stuff')
... >>> m.mock_calls
[call('foo', 'w'),
call().__enter__(),
call().write('so... | Mocking context managers with a :class:`MagicMock` is common enough and fiddly enough that a helper function is useful. ::
>>> m = mock_open()
>>> with patch('__main__.open', m):
... with open('foo', 'w') as h:
... h.write('some stuff')
... >>> m.mock_calls
[call('foo', 'w'),
call().__enter__(),
call().write('so... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
33896aa0-d52d-4459-bb5f-6353e222d52b | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock.rst | unknown | bce24593-a692-4bea-816a-2b489f4af17b | 26,959 | supabase-export-v2 | 5ccb07ed05f42aab | urllib import request >>> mock = Mock(spec=request.Request) >>> mock.assret_called_with # Intentional typo! Traceback (most recent call last): ... AttributeError: Mock object has no attribute 'assret_called_with'
The spec only applies to the mock itself, so we still have the same issue
with any methods on the mock: | trusted_official_docs | CPython Docs | urllib import request >>> mock = Mock(spec=request.Request) >>> mock.assret_called_with # Intentional typo! Traceback (most recent call last): ... AttributeError: Mock object has no attribute 'assret_called_with'
The spec only applies to the mock itself, so we still have the same issue
with any methods on the mock: | urllib import request >>> mock = Mock(spec=request.Request) >>> mock.assret_called_with # Intentional typo! Traceback (most recent call last): ... AttributeError: Mock object has no attribute 'assret_called_with'
The spec only applies to the mock itself, so we still have the same issue
with any methods on the mock: | python, official-docs, cpython, P0 | Local_Trusted_Corpus |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.