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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9240f648-72e2-4e5d-95de-a4d08593fe38 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,336 | supabase-export-v2 | 8e81cef8c4e2d313 | import http.cookiejar, urllib.request cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/")
This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx
cookies (assumes Unix/Netscape convention for locatio... | trusted_official_docs | CPython Docs | import http.cookiejar, urllib.request cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/")
This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx
cookies (assumes Unix/Netscape convention for locatio... | import http.cookiejar, urllib.request cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/")
This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx
cookies (assumes Unix/Netscape convention for locatio... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
975e5ccc-cd00-4308-abff-b620f2b34d21 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,237 | supabase-export-v2 | 906969984c867e9a | Don't add :mailheader:`Cookie2` header to requests (the presence of this header indicates to the server that we understand :rfc:`2965` cookies).
The most useful way to define a :class:`CookiePolicy` class is by subclassing
from :class:`DefaultCookiePolicy` and overriding some or all of the methods
above. :class:`Cookie... | trusted_official_docs | CPython Docs | Don't add :mailheader:`Cookie2` header to requests (the presence of this header indicates to the server that we understand :rfc:`2965` cookies).
The most useful way to define a :class:`CookiePolicy` class is by subclassing
from :class:`DefaultCookiePolicy` and overriding some or all of the methods
above. :class:`Cookie... | Don't add :mailheader:`Cookie2` header to requests (the presence of this header indicates to the server that we understand :rfc:`2965` cookies).
The most useful way to define a :class:`CookiePolicy` class is by subclassing
from :class:`DefaultCookiePolicy` and overriding some or all of the methods
above. :class:`Cookie... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
9f66f614-26e3-4218-8212-ac115fff1f7b | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,209 | supabase-export-v2 | de42d7b12aa28d9c | .. class:: LWPCookieJar(filename=None, delayload=None, policy=None)
A :class:`FileCookieJar` that can load from and save cookies to disk in format
compatible with the libwww-perl library's ``Set-Cookie3`` file format. This is
convenient if you want to store cookies in a human-readable file. | trusted_official_docs | CPython Docs | .. class:: LWPCookieJar(filename=None, delayload=None, policy=None)
A :class:`FileCookieJar` that can load from and save cookies to disk in format
compatible with the libwww-perl library's ``Set-Cookie3`` file format. This is
convenient if you want to store cookies in a human-readable file. | .. class:: LWPCookieJar(filename=None, delayload=None, policy=None)
A :class:`FileCookieJar` that can load from and save cookies to disk in format
compatible with the libwww-perl library's ``Set-Cookie3`` file format. This is
convenient if you want to store cookies in a human-readable file. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
a1e6faed-fa8a-417b-8330-c763b84ab89a | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,113 | supabase-export-v2 | 04fd0e70d2cb39ad | .. note::
The various named parameters found in :mailheader:`Set-Cookie` and
:mailheader:`Set-Cookie2` headers (eg. ``domain`` and ``expires``) are
conventionally referred to as :dfn:`attributes`. To distinguish them from
Python attributes, the documentation for this module uses the term
:dfn:`cookie-attribute` ins... | trusted_official_docs | CPython Docs | .. note::
The various named parameters found in :mailheader:`Set-Cookie` and
:mailheader:`Set-Cookie2` headers (eg. ``domain`` and ``expires``) are
conventionally referred to as :dfn:`attributes`. To distinguish them from
Python attributes, the documentation for this module uses the term
:dfn:`cookie-attribute` ins... | .. note::
The various named parameters found in :mailheader:`Set-Cookie` and
:mailheader:`Set-Cookie2` headers (eg. ``domain`` and ``expires``) are
conventionally referred to as :dfn:`attributes`. To distinguish them from
Python attributes, the documentation for this module uses the term
:dfn:`cookie-attribute` ins... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
aa58b3c1-70b7-4bd2-931e-fe0854d7b2cd | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,138 | supabase-export-v2 | 44b6f8da36b25be1 | Module :mod:`http.cookies` HTTP cookie classes, principally useful for server-side code. The :mod:`!http.cookiejar` and :mod:`http.cookies` modules do not depend on each other.
https://curl.se/rfc/cookie_spec.html
The specification of the original Netscape cookie protocol. Though this is
still the dominant protocol, ... | trusted_official_docs | CPython Docs | Module :mod:`http.cookies` HTTP cookie classes, principally useful for server-side code. The :mod:`!http.cookiejar` and :mod:`http.cookies` modules do not depend on each other.
https://curl.se/rfc/cookie_spec.html
The specification of the original Netscape cookie protocol. Though this is
still the dominant protocol, ... | Module :mod:`http.cookies` HTTP cookie classes, principally useful for server-side code. The :mod:`!http.cookiejar` and :mod:`http.cookies` modules do not depend on each other.
https://curl.se/rfc/cookie_spec.html
The specification of the original Netscape cookie protocol. Though this is
still the dominant protocol, ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
ace72d5f-1892-4492-b984-b093fedb12f1 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,183 | supabase-export-v2 | 0bae7e96c7a43281 | *ignore_discard*: save even cookies set to be discarded. *ignore_expires*: save even cookies that have expired
The file is overwritten if it already exists, thus wiping all the cookies it
contains. Saved cookies can be restored later using the :meth:`load` or
:meth:`revert` methods. | trusted_official_docs | CPython Docs | *ignore_discard*: save even cookies set to be discarded. *ignore_expires*: save even cookies that have expired
The file is overwritten if it already exists, thus wiping all the cookies it
contains. Saved cookies can be restored later using the :meth:`load` or
:meth:`revert` methods. | *ignore_discard*: save even cookies set to be discarded. *ignore_expires*: save even cookies that have expired
The file is overwritten if it already exists, thus wiping all the cookies it
contains. Saved cookies can be restored later using the :meth:`load` or
:meth:`revert` methods. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
acfb3849-6d68-4474-9d94-4565277d8350 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,246 | supabase-export-v2 | 2449df421f3d0f72 | methods (and the corresponding argument and methods for *allowed_domains*). If you set an allowlist, you can turn it off again by setting it to :const:`None`.
Domains in block or allow lists that do not start with a dot must equal the
cookie domain to be matched. For example, ``"example.com"`` matches a blocklist
entry... | trusted_official_docs | CPython Docs | methods (and the corresponding argument and methods for *allowed_domains*). If you set an allowlist, you can turn it off again by setting it to :const:`None`.
Domains in block or allow lists that do not start with a dot must equal the
cookie domain to be matched. For example, ``"example.com"`` matches a blocklist
entry... | methods (and the corresponding argument and methods for *allowed_domains*). If you set an allowlist, you can turn it off again by setting it to :const:`None`.
Domains in block or allow lists that do not start with a dot must equal the
cookie domain to be matched. For example, ``"example.com"`` matches a blocklist
entry... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
ae832d70-1bc6-497f-a407-ac83aa7a6bfb | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,175 | supabase-export-v2 | 8e3332f77edffe23 | Discard all session cookies.
Discards all contained cookies that have a true :attr:`discard` attribute
(usually because they had either no ``max-age`` or ``expires`` cookie-attribute,
or an explicit ``discard`` cookie-attribute). For interactive browsers, the end
of a session usually corresponds to closing the brows... | trusted_official_docs | CPython Docs | Discard all session cookies.
Discards all contained cookies that have a true :attr:`discard` attribute
(usually because they had either no ``max-age`` or ``expires`` cookie-attribute,
or an explicit ``discard`` cookie-attribute). For interactive browsers, the end
of a session usually corresponds to closing the brows... | Discard all session cookies.
Discards all contained cookies that have a true :attr:`discard` attribute
(usually because they had either no ``max-age`` or ``expires`` cookie-attribute,
or an explicit ``discard`` cookie-attribute). For interactive browsers, the end
of a session usually corresponds to closing the brows... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
b0fcb13f-4bf1-4ba7-8a5b-ba428e667833 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,339 | supabase-export-v2 | 772f90e3dc5a6a6b | on :rfc:`2965` cookies, be more strict about domains when setting and returning Netscape cookies, and block some domains from setting cookies or having them returned::
import urllib.request
from http.cookiejar import CookieJar, DefaultCookiePolicy
policy = DefaultCookiePolicy(
rfc2965=True, strict_ns_domain=Policy.D... | trusted_official_docs | CPython Docs | on :rfc:`2965` cookies, be more strict about domains when setting and returning Netscape cookies, and block some domains from setting cookies or having them returned::
import urllib.request
from http.cookiejar import CookieJar, DefaultCookiePolicy
policy = DefaultCookiePolicy(
rfc2965=True, strict_ns_domain=Policy.D... | on :rfc:`2965` cookies, be more strict about domains when setting and returning Netscape cookies, and block some domains from setting cookies or having them returned::
import urllib.request
from http.cookiejar import CookieJar, DefaultCookiePolicy
policy = DefaultCookiePolicy(
rfc2965=True, strict_ns_domain=Policy.D... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
b671693d-537e-422f-80de-0420f8aa125f | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,184 | supabase-export-v2 | 31a7684286efb8e1 | is overwritten if it already exists, thus wiping all the cookies it contains. Saved cookies can be restored later using the :meth:`load` or :meth:`revert` methods.
.. method:: FileCookieJar.load(filename=None, ignore_discard=False, ignore_expires=False) | trusted_official_docs | CPython Docs | is overwritten if it already exists, thus wiping all the cookies it contains. Saved cookies can be restored later using the :meth:`load` or :meth:`revert` methods.
.. method:: FileCookieJar.load(filename=None, ignore_discard=False, ignore_expires=False) | is overwritten if it already exists, thus wiping all the cookies it contains. Saved cookies can be restored later using the :meth:`load` or :meth:`revert` methods.
.. method:: FileCookieJar.load(filename=None, ignore_discard=False, ignore_expires=False) | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
b69c38e4-a14d-40b5-93e7-fdabb2ce9e28 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,207 | supabase-export-v2 | 7d77e07cef5dc3a7 | loss / corruption would be inconvenient (there are some subtleties which may lead to slight changes in the file over a load / save round-trip).
Also note that cookies saved while Mozilla is running will get clobbered by
Mozilla. | trusted_official_docs | CPython Docs | loss / corruption would be inconvenient (there are some subtleties which may lead to slight changes in the file over a load / save round-trip).
Also note that cookies saved while Mozilla is running will get clobbered by
Mozilla. | loss / corruption would be inconvenient (there are some subtleties which may lead to slight changes in the file over a load / save round-trip).
Also note that cookies saved while Mozilla is running will get clobbered by
Mozilla. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
bb39e651-defe-4f6c-8669-66123bd11ad2 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,131 | supabase-export-v2 | 2012b8e7166a05f3 | .. class:: DefaultCookiePolicy( blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal, strict_ns_set_initial_dollar=Fa... | trusted_official_docs | CPython Docs | .. class:: DefaultCookiePolicy( blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal, strict_ns_set_initial_dollar=Fa... | .. class:: DefaultCookiePolicy( blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal, strict_ns_set_initial_dollar=Fa... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
bedf2f1d-182b-4fd2-9348-e37d6e2dffcc | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,150 | supabase-export-v2 | 71702a794d4a840b | allows (ie. the :attr:`rfc2965` and :attr:`hide_cookie2` attributes of the :class:`CookieJar`'s :class:`CookiePolicy` instance are true and false respectively), the :mailheader:`Cookie2` header is also added when appropriate.
The *request* object (usually a :class:`urllib.request.Request` instance)
must support the me... | trusted_official_docs | CPython Docs | allows (ie. the :attr:`rfc2965` and :attr:`hide_cookie2` attributes of the :class:`CookieJar`'s :class:`CookiePolicy` instance are true and false respectively), the :mailheader:`Cookie2` header is also added when appropriate.
The *request* object (usually a :class:`urllib.request.Request` instance)
must support the me... | allows (ie. the :attr:`rfc2965` and :attr:`hide_cookie2` attributes of the :class:`CookieJar`'s :class:`CookiePolicy` instance are true and false respectively), the :mailheader:`Cookie2` header is also added when appropriate.
The *request* object (usually a :class:`urllib.request.Request` instance)
must support the me... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
bf11707b-9373-4e21-89e0-c7c25d51bb5e | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,338 | supabase-export-v2 | 6b319f3a9cd71bb5 | import os, http.cookiejar, urllib.request cj = http.cookiejar.MozillaCookieJar() cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt")) opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/")
The next example illustrates the use of :class:`... | trusted_official_docs | CPython Docs | import os, http.cookiejar, urllib.request cj = http.cookiejar.MozillaCookieJar() cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt")) opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/")
The next example illustrates the use of :class:`... | import os, http.cookiejar, urllib.request cj = http.cookiejar.MozillaCookieJar() cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt")) opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/")
The next example illustrates the use of :class:`... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
c3fd0506-ecf7-45b4-b25e-e3d32fb13b29 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,189 | supabase-export-v2 | 599f05a01e608b6a | in the format understood by the class, or :exc:`LoadError` will be raised. Also, :exc:`OSError` may be raised, for example if the file does not exist.
.. versionchanged:: 3.3
:exc:`IOError` used to be raised, it is now an alias of :exc:`OSError`. | trusted_official_docs | CPython Docs | in the format understood by the class, or :exc:`LoadError` will be raised. Also, :exc:`OSError` may be raised, for example if the file does not exist.
.. versionchanged:: 3.3
:exc:`IOError` used to be raised, it is now an alias of :exc:`OSError`. | in the format understood by the class, or :exc:`LoadError` will be raised. Also, :exc:`OSError` may be raised, for example if the file does not exist.
.. versionchanged:: 3.3
:exc:`IOError` used to be raised, it is now an alias of :exc:`OSError`. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
cf3f70e3-a8fd-45f6-a0fe-f27aa2191fa0 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,125 | supabase-export-v2 | 6ed3e0d98b66ae19 | are **NOT** loaded from the named file until either the :meth:`load` or :meth:`revert` method is called. Subclasses of this class are documented in section :ref:`file-cookie-jar-classes`.
This should not be initialized directly – use its subclasses below instead. | trusted_official_docs | CPython Docs | are **NOT** loaded from the named file until either the :meth:`load` or :meth:`revert` method is called. Subclasses of this class are documented in section :ref:`file-cookie-jar-classes`.
This should not be initialized directly – use its subclasses below instead. | are **NOT** loaded from the named file until either the :meth:`load` or :meth:`revert` method is called. Subclasses of this class are documented in section :ref:`file-cookie-jar-classes`.
This should not be initialized directly – use its subclasses below instead. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
d1310553-1750-4b95-afe1-e149733adfbc | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,294 | supabase-export-v2 | 67f590f68c423132 | .. attribute:: Cookie.version
Integer or :const:`None`. Netscape cookies have :attr:`version` 0. :rfc:`2965` and
:rfc:`2109` cookies have a ``version`` cookie-attribute of 1. However, note that
:mod:`!http.cookiejar` may 'downgrade' RFC 2109 cookies to Netscape cookies, in which
case :attr:`version` is 0. | trusted_official_docs | CPython Docs | .. attribute:: Cookie.version
Integer or :const:`None`. Netscape cookies have :attr:`version` 0. :rfc:`2965` and
:rfc:`2109` cookies have a ``version`` cookie-attribute of 1. However, note that
:mod:`!http.cookiejar` may 'downgrade' RFC 2109 cookies to Netscape cookies, in which
case :attr:`version` is 0. | .. attribute:: Cookie.version
Integer or :const:`None`. Netscape cookies have :attr:`version` 0. :rfc:`2965` and
:rfc:`2109` cookies have a ``version`` cookie-attribute of 1. However, note that
:mod:`!http.cookiejar` may 'downgrade' RFC 2109 cookies to Netscape cookies, in which
case :attr:`version` is 0. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
d18c1387-8e41-4ad7-9377-019c13619e78 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,230 | supabase-export-v2 | 0d785f86102853ef | See the documentation for :meth:`domain_return_ok`.
In addition to implementing the methods above, implementations of the
:class:`CookiePolicy` interface must also supply the following attributes,
indicating which protocols should be used, and how. All of these attributes may
be assigned to. | trusted_official_docs | CPython Docs | See the documentation for :meth:`domain_return_ok`.
In addition to implementing the methods above, implementations of the
:class:`CookiePolicy` interface must also supply the following attributes,
indicating which protocols should be used, and how. All of these attributes may
be assigned to. | See the documentation for :meth:`domain_return_ok`.
In addition to implementing the methods above, implementations of the
:class:`CookiePolicy` interface must also supply the following attributes,
indicating which protocols should be used, and how. All of these attributes may
be assigned to. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
d2ae43a6-337b-4dfa-a43e-f5fbce86d485 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,157 | supabase-export-v2 | 5e64d7bf1c6fdc7f | The *response* object (usually the result of a call to :meth:`urllib.request.urlopen`, or similar) should support an :meth:`info` method, which returns an :class:`email.message.Message` instance.
The *request* object (usually a :class:`urllib.request.Request` instance)
must support the method :meth:`get_full_url` and ... | trusted_official_docs | CPython Docs | The *response* object (usually the result of a call to :meth:`urllib.request.urlopen`, or similar) should support an :meth:`info` method, which returns an :class:`email.message.Message` instance.
The *request* object (usually a :class:`urllib.request.Request` instance)
must support the method :meth:`get_full_url` and ... | The *response* object (usually the result of a call to :meth:`urllib.request.urlopen`, or similar) should support an :meth:`info` method, which returns an :class:`email.message.Message` instance.
The *request* object (usually a :class:`urllib.request.Request` instance)
must support the method :meth:`get_full_url` and ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
d4784246-df13-41c7-afa5-8c9e07795258 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,117 | supabase-export-v2 | 0b2a41dd8161810c | Instances of :class:`FileCookieJar` raise this exception on failure to load cookies from a file. :exc:`LoadError` is a subclass of :exc:`OSError`.
.. versionchanged:: 3.3
:exc:`LoadError` used to be a subtype of :exc:`IOError`, which is now an
alias of :exc:`OSError`. | trusted_official_docs | CPython Docs | Instances of :class:`FileCookieJar` raise this exception on failure to load cookies from a file. :exc:`LoadError` is a subclass of :exc:`OSError`.
.. versionchanged:: 3.3
:exc:`LoadError` used to be a subtype of :exc:`IOError`, which is now an
alias of :exc:`OSError`. | Instances of :class:`FileCookieJar` raise this exception on failure to load cookies from a file. :exc:`LoadError` is a subclass of :exc:`OSError`.
.. versionchanged:: 3.3
:exc:`LoadError` used to be a subtype of :exc:`IOError`, which is now an
alias of :exc:`OSError`. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
de20d166-edc3-4e65-a9ea-59b370dfdc44 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,188 | supabase-export-v2 | dbeadf4c1e78f496 | Arguments are as for :meth:`save`.
The named file must be in the format understood by the class, or
:exc:`LoadError` will be raised. Also, :exc:`OSError` may be raised, for
example if the file does not exist. | trusted_official_docs | CPython Docs | Arguments are as for :meth:`save`.
The named file must be in the format understood by the class, or
:exc:`LoadError` will be raised. Also, :exc:`OSError` may be raised, for
example if the file does not exist. | Arguments are as for :meth:`save`.
The named file must be in the format understood by the class, or
:exc:`LoadError` will be raised. Also, :exc:`OSError` may be raised, for
example if the file does not exist. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
e4ead44f-a626-432d-93a1-43bfa4d0031c | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,121 | supabase-export-v2 | 47bf0080e9e3eb4c | *policy* is an object implementing the :class:`CookiePolicy` interface.
The :class:`CookieJar` class stores HTTP cookies. It extracts cookies from HTTP
requests, and returns them in HTTP responses. :class:`CookieJar` instances
automatically expire contained cookies when necessary. Subclasses are also
responsible for... | trusted_official_docs | CPython Docs | *policy* is an object implementing the :class:`CookiePolicy` interface.
The :class:`CookieJar` class stores HTTP cookies. It extracts cookies from HTTP
requests, and returns them in HTTP responses. :class:`CookieJar` instances
automatically expire contained cookies when necessary. Subclasses are also
responsible for... | *policy* is an object implementing the :class:`CookiePolicy` interface.
The :class:`CookieJar` class stores HTTP cookies. It extracts cookies from HTTP
requests, and returns them in HTTP responses. :class:`CookieJar` instances
automatically expire contained cookies when necessary. Subclasses are also
responsible for... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
e95414f4-7fde-4c64-b9e8-89e94cef916c | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,171 | supabase-export-v2 | bec95699efa84f61 | Clear some cookies.
If invoked without arguments, clear all cookies. If given a single argument,
only cookies belonging to that *domain* will be removed. If given two arguments,
cookies belonging to the specified *domain* and URL *path* are removed. If
given three arguments, then the cookie with the specified *domai... | trusted_official_docs | CPython Docs | Clear some cookies.
If invoked without arguments, clear all cookies. If given a single argument,
only cookies belonging to that *domain* will be removed. If given two arguments,
cookies belonging to the specified *domain* and URL *path* are removed. If
given three arguments, then the cookie with the specified *domai... | Clear some cookies.
If invoked without arguments, clear all cookies. If given a single argument,
only cookies belonging to that *domain* will be removed. If given two arguments,
cookies belonging to the specified *domain* and URL *path* are removed. If
given three arguments, then the cookie with the specified *domai... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
efe653ed-a6b4-4a30-a312-18dc945301ac | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,282 | supabase-export-v2 | c74072f0cb716be7 | .. attribute:: DefaultCookiePolicy.DomainStrictNonDomain
Cookies that did not explicitly specify a ``domain`` cookie-attribute can only
be returned to a domain equal to the domain that set the cookie (eg. ``spam.example.com`` won't be returned cookies from ``example.com`` that had no
``domain`` cookie-attribute). | trusted_official_docs | CPython Docs | .. attribute:: DefaultCookiePolicy.DomainStrictNonDomain
Cookies that did not explicitly specify a ``domain`` cookie-attribute can only
be returned to a domain equal to the domain that set the cookie (eg. ``spam.example.com`` won't be returned cookies from ``example.com`` that had no
``domain`` cookie-attribute). | .. attribute:: DefaultCookiePolicy.DomainStrictNonDomain
Cookies that did not explicitly specify a ``domain`` cookie-attribute can only
be returned to a domain equal to the domain that set the cookie (eg. ``spam.example.com`` won't be returned cookies from ``example.com`` that had no
``domain`` cookie-attribute). | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
fb7157bb-06de-46cc-8e7c-37b92eba5ab4 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,182 | supabase-export-v2 | 0d54df03bbc13412 | *filename* is not specified, :attr:`self.filename` is used (whose default is the value passed to the constructor, if any); if :attr:`self.filename` is :const:`None`, :exc:`ValueError` is raised.
*ignore_discard*: save even cookies set to be discarded. *ignore_expires*: save
even cookies that have expired | trusted_official_docs | CPython Docs | *filename* is not specified, :attr:`self.filename` is used (whose default is the value passed to the constructor, if any); if :attr:`self.filename` is :const:`None`, :exc:`ValueError` is raised.
*ignore_discard*: save even cookies set to be discarded. *ignore_expires*: save
even cookies that have expired | *filename* is not specified, :attr:`self.filename` is used (whose default is the value passed to the constructor, if any); if :attr:`self.filename` is :const:`None`, :exc:`ValueError` is raised.
*ignore_discard*: save even cookies set to be discarded. *ignore_expires*: save
even cookies that have expired | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
fc91b62e-413b-4be3-8435-edd963130be5 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,140 | supabase-export-v2 | bc15b0558418c467 | :rfc:`2109` - HTTP State Management Mechanism Obsoleted by :rfc:`2965`. Uses :mailheader:`Set-Cookie` with version=1.
:rfc:`2965` - HTTP State Management Mechanism
The Netscape protocol with the bugs fixed. Uses :mailheader:`Set-Cookie2` in
place of :mailheader:`Set-Cookie`. Not widely used. | trusted_official_docs | CPython Docs | :rfc:`2109` - HTTP State Management Mechanism Obsoleted by :rfc:`2965`. Uses :mailheader:`Set-Cookie` with version=1.
:rfc:`2965` - HTTP State Management Mechanism
The Netscape protocol with the bugs fixed. Uses :mailheader:`Set-Cookie2` in
place of :mailheader:`Set-Cookie`. Not widely used. | :rfc:`2109` - HTTP State Management Mechanism Obsoleted by :rfc:`2965`. Uses :mailheader:`Set-Cookie` with version=1.
:rfc:`2965` - HTTP State Management Mechanism
The Netscape protocol with the bugs fixed. Uses :mailheader:`Set-Cookie2` in
place of :mailheader:`Set-Cookie`. Not widely used. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
fccef099-59e7-4421-b134-b4886efa135c | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,226 | supabase-export-v2 | c9a2f093a259e5cd | *request* domain. For example, the function might be called with both ``".example.com"`` and ``"www.example.com"`` if the request domain is ``"www.example.com"``. The same goes for :meth:`path_return_ok`.
The *request* argument is as documented for :meth:`return_ok`. | trusted_official_docs | CPython Docs | *request* domain. For example, the function might be called with both ``".example.com"`` and ``"www.example.com"`` if the request domain is ``"www.example.com"``. The same goes for :meth:`path_return_ok`.
The *request* argument is as documented for :meth:`return_ok`. | *request* domain. For example, the function might be called with both ``".example.com"`` and ``"www.example.com"`` if the request domain is ``"www.example.com"``. The same goes for :meth:`path_return_ok`.
The *request* argument is as documented for :meth:`return_ok`. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
fcdb620d-08d4-476d-9925-5476cec98e6c | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,242 | supabase-export-v2 | 924ba1e99fcfbc12 | Both :rfc:`2965` and Netscape cookies are covered. RFC 2965 handling is switched off by default.
The easiest way to provide your own policy is to override this class and call
its methods in your overridden implementations before adding your own additional
checks:: | trusted_official_docs | CPython Docs | Both :rfc:`2965` and Netscape cookies are covered. RFC 2965 handling is switched off by default.
The easiest way to provide your own policy is to override this class and call
its methods in your overridden implementations before adding your own additional
checks:: | Both :rfc:`2965` and Netscape cookies are covered. RFC 2965 handling is switched off by default.
The easiest way to provide your own policy is to override this class and call
its methods in your overridden implementations before adding your own additional
checks:: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
fd0b3d43-0b76-4f56-af5a-1d19adb63728 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,202 | supabase-export-v2 | 3930464a6f8637ce | .. class:: MozillaCookieJar(filename=None, delayload=None, policy=None)
A :class:`FileCookieJar` that can load from and save cookies to disk in the
Mozilla ``cookies.txt`` file format (which is also used by curl and the Lynx
and Netscape browsers). | trusted_official_docs | CPython Docs | .. class:: MozillaCookieJar(filename=None, delayload=None, policy=None)
A :class:`FileCookieJar` that can load from and save cookies to disk in the
Mozilla ``cookies.txt`` file format (which is also used by curl and the Lynx
and Netscape browsers). | .. class:: MozillaCookieJar(filename=None, delayload=None, policy=None)
A :class:`FileCookieJar` that can load from and save cookies to disk in the
Mozilla ``cookies.txt`` file format (which is also used by curl and the Lynx
and Netscape browsers). | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
fe6b030b-8064-498d-9939-ee153dd2d253 | CPython Docs | file://datasets/cpython/Doc/library/http.cookiejar.rst | unknown | fa37f1c3-70b4-457e-829d-0ad0a30352cf | 14,224 | supabase-export-v2 | e073ba03978795f5 | checking every cookie with a particular domain (which might involve reading many files). Returning true from :meth:`domain_return_ok` and :meth:`path_return_ok` leaves all the work to :meth:`return_ok`.
If :meth:`domain_return_ok` returns true for the cookie domain,
:meth:`path_return_ok` is called for the cookie path... | trusted_official_docs | CPython Docs | checking every cookie with a particular domain (which might involve reading many files). Returning true from :meth:`domain_return_ok` and :meth:`path_return_ok` leaves all the work to :meth:`return_ok`.
If :meth:`domain_return_ok` returns true for the cookie domain,
:meth:`path_return_ok` is called for the cookie path... | checking every cookie with a particular domain (which might involve reading many files). Returning true from :meth:`domain_return_ok` and :meth:`path_return_ok` leaves all the work to :meth:`return_ok`.
If :meth:`domain_return_ok` returns true for the cookie domain,
:meth:`path_return_ok` is called for the cookie path... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
01f99077-401c-4dd0-940c-a2c61cee4165 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,582 | supabase-export-v2 | ca61699c86cba304 | You can see in this example how a 'standard' call to ``assert_called_with`` isn't sufficient:
>>> class Foo:
... def __init__(self, a, b):
... self.a, self.b = a, b
... >>> mock = Mock(return_value=None)
>>> mock(Foo(1, 2))
>>> mock.assert_called_with(Foo(1, 2))
Traceback (most recent call last):
... AssertionEr... | trusted_official_docs | CPython Docs | You can see in this example how a 'standard' call to ``assert_called_with`` isn't sufficient:
>>> class Foo:
... def __init__(self, a, b):
... self.a, self.b = a, b
... >>> mock = Mock(return_value=None)
>>> mock(Foo(1, 2))
>>> mock.assert_called_with(Foo(1, 2))
Traceback (most recent call last):
... AssertionEr... | You can see in this example how a 'standard' call to ``assert_called_with`` isn't sufficient:
>>> class Foo:
... def __init__(self, a, b):
... self.a, self.b = a, b
... >>> mock = Mock(return_value=None)
>>> mock(Foo(1, 2))
>>> mock.assert_called_with(Foo(1, 2))
Traceback (most recent call last):
... AssertionEr... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
02a8cf6b-eaec-4660-bfd4-df386ad6d2f7 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,561 | supabase-export-v2 | 636120f70e300f59 | >>> mock = Mock() >>> with patch.dict('sys.modules', {'fooble': mock}): ... from fooble import blob ... blob.blip() ... <Mock name='mock.blob.blip()' id='...'> >>> mock.blob.blip.assert_called_once_with()
With slightly more work you can also mock package imports: | trusted_official_docs | CPython Docs | >>> mock = Mock() >>> with patch.dict('sys.modules', {'fooble': mock}): ... from fooble import blob ... blob.blip() ... <Mock name='mock.blob.blip()' id='...'> >>> mock.blob.blip.assert_called_once_with()
With slightly more work you can also mock package imports: | >>> mock = Mock() >>> with patch.dict('sys.modules', {'fooble': mock}): ... from fooble import blob ... blob.blip() ... <Mock name='mock.blob.blip()' id='...'> >>> mock.blob.blip.assert_called_once_with()
With slightly more work you can also mock package imports: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
05c388fc-96e2-4801-bf5d-f25c857f8ebf | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,589 | supabase-export-v2 | c0035e1519e2b61f | >>> match_foo = Matcher(compare, Foo(1, 2)) >>> mock.assert_called_with(match_foo)
The ``Matcher`` is instantiated with our compare function and the ``Foo`` object
we want to compare against. In ``assert_called_with`` the ``Matcher`` equality
method will be called, which compares the object the mock was called with
aga... | trusted_official_docs | CPython Docs | >>> match_foo = Matcher(compare, Foo(1, 2)) >>> mock.assert_called_with(match_foo)
The ``Matcher`` is instantiated with our compare function and the ``Foo`` object
we want to compare against. In ``assert_called_with`` the ``Matcher`` equality
method will be called, which compares the object the mock was called with
aga... | >>> match_foo = Matcher(compare, Foo(1, 2)) >>> mock.assert_called_with(match_foo)
The ``Matcher`` is instantiated with our compare function and the ``Foo`` object
we want to compare against. In ``assert_called_with`` the ``Matcher`` equality
method will be called, which compares the object the mock was called with
aga... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
05c42267-93f8-4811-b076-080e8c43893d | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,481 | supabase-export-v2 | a59d8e7a9a5f95cd | How would we mock this class, and in particular its "iter" method?
To configure the values returned from the iteration (implicit in the call to
:class:`list`), we need to configure the object returned by the call to ``foo.iter()``. | trusted_official_docs | CPython Docs | How would we mock this class, and in particular its "iter" method?
To configure the values returned from the iteration (implicit in the call to
:class:`list`), we need to configure the object returned by the call to ``foo.iter()``. | How would we mock this class, and in particular its "iter" method?
To configure the values returned from the iteration (implicit in the call to
:class:`list`), we need to configure the object returned by the call to ``foo.iter()``. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
091374f4-7f21-493b-babe-11cb95a2fb2c | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,511 | supabase-export-v2 | da33df14ab7e16b3 | When we try to test that ``grob`` calls ``frob`` with the correct argument look what happens::
>>> with patch('mymodule.frob') as mock_frob:
... val = {6}
... mymodule.grob(val)
... >>> val
set()
>>> mock_frob.assert_called_with({6})
Traceback (most recent call last):
... AssertionError: Expected: (({6},), {})
... | trusted_official_docs | CPython Docs | When we try to test that ``grob`` calls ``frob`` with the correct argument look what happens::
>>> with patch('mymodule.frob') as mock_frob:
... val = {6}
... mymodule.grob(val)
... >>> val
set()
>>> mock_frob.assert_called_with({6})
Traceback (most recent call last):
... AssertionError: Expected: (({6},), {})
... | When we try to test that ``grob`` calls ``frob`` with the correct argument look what happens::
>>> with patch('mymodule.frob') as mock_frob:
... val = {6}
... mymodule.grob(val)
... >>> val
set()
>>> mock_frob.assert_called_with({6})
Traceback (most recent call last):
... AssertionError: Expected: (({6},), {})
... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0c82c8b1-dfb2-4789-9b22-0a897760b2ba | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,562 | supabase-export-v2 | abe130d31c65ce97 | With slightly more work you can also mock package imports:
>>> mock = Mock()
>>> modules = {'package': mock, 'package.module': mock.module}
>>> with patch.dict('sys.modules', modules):
... from package.module import fooble
... fooble()
... <Mock name='mock.module.fooble()' id='...'>
>>> mock.module.fooble.assert_... | trusted_official_docs | CPython Docs | With slightly more work you can also mock package imports:
>>> mock = Mock()
>>> modules = {'package': mock, 'package.module': mock.module}
>>> with patch.dict('sys.modules', modules):
... from package.module import fooble
... fooble()
... <Mock name='mock.module.fooble()' id='...'>
>>> mock.module.fooble.assert_... | With slightly more work you can also mock package imports:
>>> mock = Mock()
>>> modules = {'package': mock, 'package.module': mock.module}
>>> with patch.dict('sys.modules', modules):
... from package.module import fooble
... fooble()
... <Mock name='mock.module.fooble()' id='...'>
>>> mock.module.fooble.assert_... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0c96a445-8596-4ede-9c44-ca447f4eecb5 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,518 | supabase-export-v2 | 73a98965d3c26520 | once there is an easier way of checking arguments at the point they are called. You can simply do the checking inside a ``side_effect`` function.
>>> def side_effect(arg):
... assert arg == {6}
... >>> mock = Mock(side_effect=side_effect)
>>> mock({6})
>>> mock(set())
Traceback (most recent call last):
... Assert... | trusted_official_docs | CPython Docs | once there is an easier way of checking arguments at the point they are called. You can simply do the checking inside a ``side_effect`` function.
>>> def side_effect(arg):
... assert arg == {6}
... >>> mock = Mock(side_effect=side_effect)
>>> mock({6})
>>> mock(set())
Traceback (most recent call last):
... Assert... | once there is an easier way of checking arguments at the point they are called. You can simply do the checking inside a ``side_effect`` function.
>>> def side_effect(arg):
... assert arg == {6}
... >>> mock = Mock(side_effect=side_effect)
>>> mock({6})
>>> mock(set())
Traceback (most recent call last):
... Assert... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0e0a17f6-7eb1-46e7-9c22-ad633bf2ee2c | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,373 | supabase-export-v2 | be6fa0d6b0a21033 | Tracking all calls ~~~~~~~~~~~~~~~~~~
Often you want to track more than a single call to a method. The
:attr:`~Mock.mock_calls` attribute records all calls
to child attributes of the mock - and also to their children. | trusted_official_docs | CPython Docs | Tracking all calls ~~~~~~~~~~~~~~~~~~
Often you want to track more than a single call to a method. The
:attr:`~Mock.mock_calls` attribute records all calls
to child attributes of the mock - and also to their children. | Tracking all calls ~~~~~~~~~~~~~~~~~~
Often you want to track more than a single call to a method. The
:attr:`~Mock.mock_calls` attribute records all calls
to child attributes of the mock - and also to their children. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0edd90fd-0559-4386-99e7-70520cb55c7e | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,506 | supabase-export-v2 | eaee0446f54c9a9b | Coping with mutable arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Another situation is rare, but can bite you, is when your mock is called with
mutable arguments. ``call_args`` and ``call_args_list`` store *references* to the
arguments. If the arguments are mutated by the code under test then you can no
longer make assertion... | trusted_official_docs | CPython Docs | Coping with mutable arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Another situation is rare, but can bite you, is when your mock is called with
mutable arguments. ``call_args`` and ``call_args_list`` store *references* to the
arguments. If the arguments are mutated by the code under test then you can no
longer make assertion... | Coping with mutable arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Another situation is rare, but can bite you, is when your mock is called with
mutable arguments. ``call_args`` and ``call_args_list`` store *references* to the
arguments. If the arguments are mutated by the code under test then you can no
longer make assertion... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0ef20441-0b90-41f5-8e37-f674c027a5bd | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,591 | supabase-export-v2 | 9a40be49ad4d71c1 | Matcher(compare, Foo(3, 4)) >>> mock.assert_called_with(match_wrong) Traceback (most recent call last): ... AssertionError: Expected: ((<Matcher object at 0x...>,), {}) Called with: ((<Foo object at 0x...>,), {})
With a bit of tweaking you could have the comparison function raise the
:exc:`AssertionError` directly and ... | trusted_official_docs | CPython Docs | Matcher(compare, Foo(3, 4)) >>> mock.assert_called_with(match_wrong) Traceback (most recent call last): ... AssertionError: Expected: ((<Matcher object at 0x...>,), {}) Called with: ((<Foo object at 0x...>,), {})
With a bit of tweaking you could have the comparison function raise the
:exc:`AssertionError` directly and ... | Matcher(compare, Foo(3, 4)) >>> mock.assert_called_with(match_wrong) Traceback (most recent call last): ... AssertionError: Expected: ((<Matcher object at 0x...>,), {}) Called with: ((<Foo object at 0x...>,), {})
With a bit of tweaking you could have the comparison function raise the
:exc:`AssertionError` directly and ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
15d1d801-4a58-4505-a4fa-3f97c54103c6 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,472 | supabase-export-v2 | b2f1d248803a70f9 | Note that we don't patch :class:`datetime.date` globally, we patch ``date`` in the module that *uses* it. See :ref:`where to patch <where-to-patch>`.
When ``date.today()`` is called a known date is returned, but calls to the
``date(...)`` constructor still return normal dates. Without this you can find
yourself having ... | trusted_official_docs | CPython Docs | Note that we don't patch :class:`datetime.date` globally, we patch ``date`` in the module that *uses* it. See :ref:`where to patch <where-to-patch>`.
When ``date.today()`` is called a known date is returned, but calls to the
``date(...)`` constructor still return normal dates. Without this you can find
yourself having ... | Note that we don't patch :class:`datetime.date` globally, we patch ``date`` in the module that *uses* it. See :ref:`where to patch <where-to-patch>`.
When ``date.today()`` is called a known date is returned, but calls to the
``date(...)`` constructor still return normal dates. Without this you can find
yourself having ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1912766d-5cc6-4a49-99bf-be04a944c53d | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,483 | supabase-export-v2 | 463a94fb0a53b91a | >>> mock_foo = MagicMock() >>> mock_foo.iter.return_value = iter([1, 2, 3]) >>> list(mock_foo.iter()) [1, 2, 3]
.. [#] There are also generator expressions and more `advanced uses
<http://www.dabeaz.com/coroutines/index.html>`_ of generators, but we aren't
concerned about them here. A very good introduction to genera... | trusted_official_docs | CPython Docs | >>> mock_foo = MagicMock() >>> mock_foo.iter.return_value = iter([1, 2, 3]) >>> list(mock_foo.iter()) [1, 2, 3]
.. [#] There are also generator expressions and more `advanced uses
<http://www.dabeaz.com/coroutines/index.html>`_ of generators, but we aren't
concerned about them here. A very good introduction to genera... | >>> mock_foo = MagicMock() >>> mock_foo.iter.return_value = iter([1, 2, 3]) >>> list(mock_foo.iter()) [1, 2, 3]
.. [#] There are also generator expressions and more `advanced uses
<http://www.dabeaz.com/coroutines/index.html>`_ of generators, but we aren't
concerned about them here. A very good introduction to genera... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1c568cc5-b572-4c10-a0bf-26fe8f64da70 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,465 | supabase-export-v2 | 6bbb02908a8417bc | in one line of code, so there will be several entries in ``mock_calls``. We can use :meth:`call.call_list` to create this list of calls for us::
>>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
>>> call_list = chained.call_list()
>>> assert mock_backend.mock_calls == call_list | trusted_official_docs | CPython Docs | in one line of code, so there will be several entries in ``mock_calls``. We can use :meth:`call.call_list` to create this list of calls for us::
>>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
>>> call_list = chained.call_list()
>>> assert mock_backend.mock_calls == call_list | in one line of code, so there will be several entries in ``mock_calls``. We can use :meth:`call.call_list` to create this list of calls for us::
>>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
>>> call_list = chained.call_list()
>>> assert mock_backend.mock_calls == call_list | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1d3992df-09e5-4cdd-b305-00bf06c9d993 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,436 | supabase-export-v2 | 358cff0b2f40c884 | :func:`patch` with only one argument (or :func:`patch.object` with two arguments). The mock will be created for you and passed into the test function / method:
>>> class MyTest(unittest.TestCase):
... @patch.object(SomeClass, 'static_method')
... def test_something(self, mock_method):
... SomeClass.static_method()
... | trusted_official_docs | CPython Docs | :func:`patch` with only one argument (or :func:`patch.object` with two arguments). The mock will be created for you and passed into the test function / method:
>>> class MyTest(unittest.TestCase):
... @patch.object(SomeClass, 'static_method')
... def test_something(self, mock_method):
... SomeClass.static_method()
... | :func:`patch` with only one argument (or :func:`patch.object` with two arguments). The mock will be created for you and passed into the test function / method:
>>> class MyTest(unittest.TestCase):
... @patch.object(SomeClass, 'static_method')
... def test_something(self, mock_method):
... SomeClass.static_method()
... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
20bcc2d0-7f14-44c3-852c-1277a1d7924a | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,480 | supabase-export-v2 | 04aae32a95139c17 | class Foo: ... def iter(self): ... for i in [1, 2, 3]: ... yield i ... >>> foo = Foo() >>> list(foo.iter()) [1, 2, 3]
How would we mock this class, and in particular its "iter" method? | trusted_official_docs | CPython Docs | class Foo: ... def iter(self): ... for i in [1, 2, 3]: ... yield i ... >>> foo = Foo() >>> list(foo.iter()) [1, 2, 3]
How would we mock this class, and in particular its "iter" method? | class Foo: ... def iter(self): ... for i in [1, 2, 3]: ... yield i ... >>> foo = Foo() >>> list(foo.iter()) [1, 2, 3]
How would we mock this class, and in particular its "iter" method? | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
217f91d4-ba23-4cee-948e-3b59cb4d76de | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,414 | supabase-export-v2 | f221aad2adcca87f | If you want this smarter matching to also work with method calls on the mock, you can use :ref:`auto-speccing <auto-speccing>`.
If you want a stronger form of specification that prevents the setting
of arbitrary attributes as well as the getting of them then you can use
*spec_set* instead of *spec*. | trusted_official_docs | CPython Docs | If you want this smarter matching to also work with method calls on the mock, you can use :ref:`auto-speccing <auto-speccing>`.
If you want a stronger form of specification that prevents the setting
of arbitrary attributes as well as the getting of them then you can use
*spec_set* instead of *spec*. | If you want this smarter matching to also work with method calls on the mock, you can use :ref:`auto-speccing <auto-speccing>`.
If you want a stronger form of specification that prevents the setting
of arbitrary attributes as well as the getting of them then you can use
*spec_set* instead of *spec*. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
22a349c0-e2d4-4bc5-9858-6e7809d6ea66 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,539 | supabase-export-v2 | 773c2af439cbf04b | will behave like a normal dictionary but recording the access. It even raises a :exc:`KeyError` if you try to access a key that doesn't exist.
>>> mock['a']
1
>>> mock['c']
3
>>> mock['d']
Traceback (most recent call last):
... KeyError: 'd'
>>> mock['b'] = 'fish'
>>> mock['d'] = 'eggs'
>>> mock['b']
'fish'
... | trusted_official_docs | CPython Docs | will behave like a normal dictionary but recording the access. It even raises a :exc:`KeyError` if you try to access a key that doesn't exist.
>>> mock['a']
1
>>> mock['c']
3
>>> mock['d']
Traceback (most recent call last):
... KeyError: 'd'
>>> mock['b'] = 'fish'
>>> mock['d'] = 'eggs'
>>> mock['b']
'fish'
... | will behave like a normal dictionary but recording the access. It even raises a :exc:`KeyError` if you try to access a key that doesn't exist.
>>> mock['a']
1
>>> mock['c']
3
>>> mock['d']
Traceback (most recent call last):
... KeyError: 'd'
>>> mock['b'] = 'fish'
>>> mock['d'] = 'eggs'
>>> mock['b']
'fish'
... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2b9c2da5-86b0-44a8-8e3b-2c81d9d5399a | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,584 | supabase-export-v2 | ed59ec37f5de47e2 | A comparison function for our ``Foo`` class might look something like this:
>>> def compare(self, other):
... if not type(self) == type(other):
... return False
... if self.a != other.a:
... return False
... if self.b != other.b:
... return False
... return True
... | trusted_official_docs | CPython Docs | A comparison function for our ``Foo`` class might look something like this:
>>> def compare(self, other):
... if not type(self) == type(other):
... return False
... if self.a != other.a:
... return False
... if self.b != other.b:
... return False
... return True
... | A comparison function for our ``Foo`` class might look something like this:
>>> def compare(self, other):
... if not type(self) == type(other):
... return False
... if self.a != other.a:
... return False
... if self.b != other.b:
... return False
... return True
... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2cf9be72-bd1e-499e-85d8-25b16940d362 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,468 | supabase-export-v2 | e865086c6f1f81d6 | the code under test from creating new date objects. Unfortunately :class:`datetime.date` is written in C, so you cannot just monkey-patch out the static :meth:`datetime.date.today` method.
Instead, you can effectively wrap the date
class with a mock, while passing through calls to the constructor to the real
class (and... | trusted_official_docs | CPython Docs | the code under test from creating new date objects. Unfortunately :class:`datetime.date` is written in C, so you cannot just monkey-patch out the static :meth:`datetime.date.today` method.
Instead, you can effectively wrap the date
class with a mock, while passing through calls to the constructor to the real
class (and... | the code under test from creating new date objects. Unfortunately :class:`datetime.date` is written in C, so you cannot just monkey-patch out the static :meth:`datetime.date.today` method.
Instead, you can effectively wrap the date
class with a mock, while passing through calls to the constructor to the real
class (and... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2daf4c0c-3677-4f9b-866b-8d5bb20d9ea3 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,397 | supabase-export-v2 | b8840b35e1f903e6 | Side effect functions and iterables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``side_effect`` can also be set to a function or an iterable. The use case for
``side_effect`` as an iterable is where your mock is going to be called several
times, and you want each call to return a different value. When you set
``side_effect`` t... | trusted_official_docs | CPython Docs | Side effect functions and iterables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``side_effect`` can also be set to a function or an iterable. The use case for
``side_effect`` as an iterable is where your mock is going to be called several
times, and you want each call to return a different value. When you set
``side_effect`` t... | Side effect functions and iterables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``side_effect`` can also be set to a function or an iterable. The use case for
``side_effect`` as an iterable is where your mock is going to be called several
times, and you want each call to return a different value. When you set
``side_effect`` t... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2f36162c-3816-448c-8852-46dc93dc05dd | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,378 | supabase-export-v2 | f5e28ac42f01a16c | >>> expected = [call.method(), call.attribute.method(10, x=53)] >>> mock.mock_calls == expected True
However, parameters to calls that return mocks are not recorded, which means it is not
possible to track nested calls where the parameters used to create ancestors are important: | trusted_official_docs | CPython Docs | >>> expected = [call.method(), call.attribute.method(10, x=53)] >>> mock.mock_calls == expected True
However, parameters to calls that return mocks are not recorded, which means it is not
possible to track nested calls where the parameters used to create ancestors are important: | >>> expected = [call.method(), call.attribute.method(10, x=53)] >>> mock.mock_calls == expected True
However, parameters to calls that return mocks are not recorded, which means it is not
possible to track nested calls where the parameters used to create ancestors are important: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
30246930-ac56-435b-b7f2-4c6184e25e51 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,407 | supabase-export-v2 | 1e30fd2ddb34eb64 | MagicMock(AsyncContextManager()) # AsyncMock also works here >>> async def main(): ... async with mock_instance as result: ... pass ... >>> asyncio.run(main()) >>> mock_instance.__aenter__.assert_awaited_once() >>> mock_instance.__aexit__.assert_awaited_once()
Creating a mock from an existing object
~~~~~~~~~~~~~~~~~~~... | trusted_official_docs | CPython Docs | MagicMock(AsyncContextManager()) # AsyncMock also works here >>> async def main(): ... async with mock_instance as result: ... pass ... >>> asyncio.run(main()) >>> mock_instance.__aenter__.assert_awaited_once() >>> mock_instance.__aexit__.assert_awaited_once()
Creating a mock from an existing object
~~~~~~~~~~~~~~~~~~~... | MagicMock(AsyncContextManager()) # AsyncMock also works here >>> async def main(): ... async with mock_instance as result: ... pass ... >>> asyncio.run(main()) >>> mock_instance.__aenter__.assert_awaited_once() >>> mock_instance.__aexit__.assert_awaited_once()
Creating a mock from an existing object
~~~~~~~~~~~~~~~~~~~... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
3202d54f-818b-4b23-ae8e-75f85aeb29d6 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,564 | supabase-export-v2 | 574ba03d0523002f | Tracking order of calls and less verbose call assertions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :class:`Mock` class allows you to track the *order* of method calls on
your mock objects through the :attr:`~Mock.method_calls` attribute. This
doesn't allow you to track the order of calls between sepa... | trusted_official_docs | CPython Docs | Tracking order of calls and less verbose call assertions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :class:`Mock` class allows you to track the *order* of method calls on
your mock objects through the :attr:`~Mock.method_calls` attribute. This
doesn't allow you to track the order of calls between sepa... | Tracking order of calls and less verbose call assertions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :class:`Mock` class allows you to track the *order* of method calls on
your mock objects through the :attr:`~Mock.method_calls` attribute. This
doesn't allow you to track the order of calls between sepa... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
32f757cd-c947-426d-91fb-ce210a013174 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,552 | supabase-export-v2 | 986b73d95747b8ad | Mocking imports with patch.dict ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
One situation where mocking can be hard is where you have a local import inside
a function. These are harder to mock because they aren't using an object from
the module namespace that we can patch out. | trusted_official_docs | CPython Docs | Mocking imports with patch.dict ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
One situation where mocking can be hard is where you have a local import inside
a function. These are harder to mock because they aren't using an object from
the module namespace that we can patch out. | Mocking imports with patch.dict ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
One situation where mocking can be hard is where you have a local import inside
a function. These are harder to mock because they aren't using an object from
the module namespace that we can patch out. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
34a0b9a4-50f2-4092-a254-7ebdc5b51370 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,429 | supabase-export-v2 | 297020423ba54608 | >>> @patch('package.module.attribute', sentinel.attribute) ... def test(): ... from package.module import attribute ... assert attribute is sentinel.attribute ... >>> test()
If you are patching a module (including :mod:`builtins`) then use :func:`patch`
instead of :func:`patch.object`: | trusted_official_docs | CPython Docs | >>> @patch('package.module.attribute', sentinel.attribute) ... def test(): ... from package.module import attribute ... assert attribute is sentinel.attribute ... >>> test()
If you are patching a module (including :mod:`builtins`) then use :func:`patch`
instead of :func:`patch.object`: | >>> @patch('package.module.attribute', sentinel.attribute) ... def test(): ... from package.module import attribute ... assert attribute is sentinel.attribute ... >>> test()
If you are patching a module (including :mod:`builtins`) then use :func:`patch`
instead of :func:`patch.object`: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
34ac4213-7996-4533-911c-3d3819aad884 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,406 | supabase-export-v2 | cfc456af096d0341 | ``AsyncMock`` and ``MagicMock`` have support to mock :ref:`async-context-managers` through ``__aenter__`` and ``__aexit__``. By default, ``__aenter__`` and ``__aexit__`` are ``AsyncMock`` instances that return an async function.
>>> class AsyncContextManager:
... async def __aenter__(self):
... return self
... async... | trusted_official_docs | CPython Docs | ``AsyncMock`` and ``MagicMock`` have support to mock :ref:`async-context-managers` through ``__aenter__`` and ``__aexit__``. By default, ``__aenter__`` and ``__aexit__`` are ``AsyncMock`` instances that return an async function.
>>> class AsyncContextManager:
... async def __aenter__(self):
... return self
... async... | ``AsyncMock`` and ``MagicMock`` have support to mock :ref:`async-context-managers` through ``__aenter__`` and ``__aexit__``. By default, ``__aenter__`` and ``__aexit__`` are ``AsyncMock`` instances that return an async function.
>>> class AsyncContextManager:
... async def __aenter__(self):
... return self
... async... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
34be8811-01ba-48bd-a9fb-73a0e0cc99f3 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,434 | supabase-export-v2 | 6ccf9d4097486b4d | A nice pattern is to actually decorate test methods themselves:
>>> class MyTest(unittest.TestCase):
... @patch.object(SomeClass, 'attribute', sentinel.attribute)
... def test_something(self):
... self.assertEqual(SomeClass.attribute, sentinel.attribute)
... >>> original = SomeClass.attribute
>>> MyTest('test_some... | trusted_official_docs | CPython Docs | A nice pattern is to actually decorate test methods themselves:
>>> class MyTest(unittest.TestCase):
... @patch.object(SomeClass, 'attribute', sentinel.attribute)
... def test_something(self):
... self.assertEqual(SomeClass.attribute, sentinel.attribute)
... >>> original = SomeClass.attribute
>>> MyTest('test_some... | A nice pattern is to actually decorate test methods themselves:
>>> class MyTest(unittest.TestCase):
... @patch.object(SomeClass, 'attribute', sentinel.attribute)
... def test_something(self):
... self.assertEqual(SomeClass.attribute, sentinel.attribute)
... >>> original = SomeClass.attribute
>>> MyTest('test_some... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
34d5b2fa-8d40-48b5-916a-dba92167c497 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,485 | supabase-export-v2 | 8e7150ea518e7c41 | Applying the same patch to every test method ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you want several patches in place for multiple test methods the obvious way
is to apply the patch decorators to every method. This can feel like unnecessary
repetition. Instead, you can use :func:`patch` (in all its
various for... | trusted_official_docs | CPython Docs | Applying the same patch to every test method ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you want several patches in place for multiple test methods the obvious way
is to apply the patch decorators to every method. This can feel like unnecessary
repetition. Instead, you can use :func:`patch` (in all its
various for... | Applying the same patch to every test method ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you want several patches in place for multiple test methods the obvious way
is to apply the patch decorators to every method. This can feel like unnecessary
repetition. Instead, you can use :func:`patch` (in all its
various for... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
34eda5cb-2102-4dc6-b368-ff23ef49df57 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,368 | supabase-export-v2 | 862f783e01a127e9 | class ``Foo`` with a mock. The ``Foo`` instance is the result of calling the mock, so it is configured by modifying the mock :attr:`~Mock.return_value`. ::
>>> def some_function():
... instance = module.Foo()
... return instance.method()
... >>> with patch('module.Foo') as mock:
... instance = mock.return_value
..... | trusted_official_docs | CPython Docs | class ``Foo`` with a mock. The ``Foo`` instance is the result of calling the mock, so it is configured by modifying the mock :attr:`~Mock.return_value`. ::
>>> def some_function():
... instance = module.Foo()
... return instance.method()
... >>> with patch('module.Foo') as mock:
... instance = mock.return_value
..... | class ``Foo`` with a mock. The ``Foo`` instance is the result of calling the mock, so it is configured by modifying the mock :attr:`~Mock.return_value`. ::
>>> def some_function():
... instance = module.Foo()
... return instance.method()
... >>> with patch('module.Foo') as mock:
... instance = mock.return_value
..... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
356bed9f-8347-49d2-b28b-96e17021a4c8 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,577 | supabase-export-v2 | 825a5536eefe1943 | interested in asserting about *some* of those calls. You may not even care about the order. In this case you can pass ``any_order=True`` to ``assert_has_calls``:
>>> m = MagicMock()
>>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
(...)
>>> calls = [call.fifty('50'), call(1), call.seven(7)]
>>> m.assert_has_calls(c... | trusted_official_docs | CPython Docs | interested in asserting about *some* of those calls. You may not even care about the order. In this case you can pass ``any_order=True`` to ``assert_has_calls``:
>>> m = MagicMock()
>>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
(...)
>>> calls = [call.fifty('50'), call(1), call.seven(7)]
>>> m.assert_has_calls(c... | interested in asserting about *some* of those calls. You may not even care about the order. In this case you can pass ``any_order=True`` to ``assert_has_calls``:
>>> m = MagicMock()
>>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
(...)
>>> calls = [call.fifty('50'), call(1), call.seven(7)]
>>> m.assert_has_calls(c... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
35c0a3fc-68b9-4f48-a0d3-9aa28b0c79eb | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,592 | supabase-export-v2 | 5a55897c8e6093bc | With a bit of tweaking you could have the comparison function raise the :exc:`AssertionError` directly and provide a more useful failure message.
As of version 1.5, the Python testing library `PyHamcrest
<https://pyhamcrest.readthedocs.io/>`_ provides similar functionality,
that may be useful here, in the form of its e... | trusted_official_docs | CPython Docs | With a bit of tweaking you could have the comparison function raise the :exc:`AssertionError` directly and provide a more useful failure message.
As of version 1.5, the Python testing library `PyHamcrest
<https://pyhamcrest.readthedocs.io/>`_ provides similar functionality,
that may be useful here, in the form of its e... | With a bit of tweaking you could have the comparison function raise the :exc:`AssertionError` directly and provide a more useful failure message.
As of version 1.5, the Python testing library `PyHamcrest
<https://pyhamcrest.readthedocs.io/>`_ provides similar functionality,
that may be useful here, in the form of its e... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
37af9ce9-d669-4f6c-8d46-47a64609b7e8 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,474 | supabase-export-v2 | 9ea4841986126561 | Calls to the date constructor are recorded in the ``mock_date`` attributes (``call_count`` and friends) which may also be useful for your tests.
An alternative way of dealing with mocking dates, or other builtin classes,
is discussed in `this blog entry
<https://williambert.online/2011/07/how-to-unit-testing-in-django-... | trusted_official_docs | CPython Docs | Calls to the date constructor are recorded in the ``mock_date`` attributes (``call_count`` and friends) which may also be useful for your tests.
An alternative way of dealing with mocking dates, or other builtin classes,
is discussed in `this blog entry
<https://williambert.online/2011/07/how-to-unit-testing-in-django-... | Calls to the date constructor are recorded in the ``mock_date`` attributes (``call_count`` and friends) which may also be useful for your tests.
An alternative way of dealing with mocking dates, or other builtin classes,
is discussed in `this blog entry
<https://williambert.online/2011/07/how-to-unit-testing-in-django-... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
391db7f1-646d-4302-8bfe-cf332e125214 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,453 | supabase-export-v2 | 50e844c22bce3d75 | >>> mock = Mock() >>> mock().foo(a=2, b=3) <Mock name='mock().foo()' id='...'> >>> mock.return_value.foo.assert_called_with(a=2, b=3)
From here it is a simple step to configure and then make assertions about
chained calls. Of course another alternative is writing your code in a more
testable way in the first place... | trusted_official_docs | CPython Docs | >>> mock = Mock() >>> mock().foo(a=2, b=3) <Mock name='mock().foo()' id='...'> >>> mock.return_value.foo.assert_called_with(a=2, b=3)
From here it is a simple step to configure and then make assertions about
chained calls. Of course another alternative is writing your code in a more
testable way in the first place... | >>> mock = Mock() >>> mock().foo(a=2, b=3) <Mock name='mock().foo()' id='...'> >>> mock.return_value.foo.assert_called_with(a=2, b=3)
From here it is a simple step to configure and then make assertions about
chained calls. Of course another alternative is writing your code in a more
testable way in the first place... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
39e798e6-4c30-43af-85f8-93dde60f1a91 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,554 | supabase-export-v2 | ed474171f99dd388 | in better ways than an unconditional local import (store the module as a class or module attribute and only do the import on first use).
That aside there is a way to use ``mock`` to affect the results of an import. Importing fetches an *object* from the :data:`sys.modules` dictionary. Note that it
fetches an *object*, ... | trusted_official_docs | CPython Docs | in better ways than an unconditional local import (store the module as a class or module attribute and only do the import on first use).
That aside there is a way to use ``mock`` to affect the results of an import. Importing fetches an *object* from the :data:`sys.modules` dictionary. Note that it
fetches an *object*, ... | in better ways than an unconditional local import (store the module as a class or module attribute and only do the import on first use).
That aside there is a way to use ``mock`` to affect the results of an import. Importing fetches an *object* from the :data:`sys.modules` dictionary. Note that it
fetches an *object*, ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
3a7170e1-a758-43c3-856c-30cc876ae0d5 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,375 | supabase-export-v2 | 1de39180c9cc38b1 | >>> mock = MagicMock() >>> mock.method() <MagicMock name='mock.method()' id='...'> >>> mock.attribute.method(10, x=53) <MagicMock name='mock.attribute.method()' id='...'> >>> mock.mock_calls [call.method(), call.attribute.method(10, x=53)]
If you make an assertion about ``mock_calls`` and any unexpected methods
have be... | trusted_official_docs | CPython Docs | >>> mock = MagicMock() >>> mock.method() <MagicMock name='mock.method()' id='...'> >>> mock.attribute.method(10, x=53) <MagicMock name='mock.attribute.method()' id='...'> >>> mock.mock_calls [call.method(), call.attribute.method(10, x=53)]
If you make an assertion about ``mock_calls`` and any unexpected methods
have be... | >>> mock = MagicMock() >>> mock.method() <MagicMock name='mock.method()' id='...'> >>> mock.attribute.method(10, x=53) <MagicMock name='mock.attribute.method()' id='...'> >>> mock.mock_calls [call.method(), call.attribute.method(10, x=53)]
If you make an assertion about ``mock_calls`` and any unexpected methods
have be... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
3af19274-8486-4127-a781-f2943530cd69 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,512 | supabase-export-v2 | 184b83eca0683f54 | val = {6} ... mymodule.grob(val) ... >>> val set() >>> mock_frob.assert_called_with({6}) Traceback (most recent call last): ... AssertionError: Expected: (({6},), {}) Called with: ((set(),), {})
One possibility would be for mock to copy the arguments you pass in. This
could then cause problems if you do assertions that... | trusted_official_docs | CPython Docs | val = {6} ... mymodule.grob(val) ... >>> val set() >>> mock_frob.assert_called_with({6}) Traceback (most recent call last): ... AssertionError: Expected: (({6},), {}) Called with: ((set(),), {})
One possibility would be for mock to copy the arguments you pass in. This
could then cause problems if you do assertions that... | val = {6} ... mymodule.grob(val) ... >>> val set() >>> mock_frob.assert_called_with({6}) Traceback (most recent call last): ... AssertionError: Expected: (({6},), {}) Called with: ((set(),), {})
One possibility would be for mock to copy the arguments you pass in. This
could then cause problems if you do assertions that... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
3bbc5e2b-c4b6-4988-8628-faafe4116730 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,356 | supabase-export-v2 | 66575979607c3ca8 | attribute is set to ``True``. More importantly we can use the :meth:`~Mock.assert_called_with` or :meth:`~Mock.assert_called_once_with` method to check that it was called with the correct arguments.
This example tests that calling ``ProductionClass().method`` results in a call to
the ``something`` method: | trusted_official_docs | CPython Docs | attribute is set to ``True``. More importantly we can use the :meth:`~Mock.assert_called_with` or :meth:`~Mock.assert_called_once_with` method to check that it was called with the correct arguments.
This example tests that calling ``ProductionClass().method`` results in a call to
the ``something`` method: | attribute is set to ``True``. More importantly we can use the :meth:`~Mock.assert_called_with` or :meth:`~Mock.assert_called_once_with` method to check that it was called with the correct arguments.
This example tests that calling ``ProductionClass().method`` results in a call to
the ``something`` method: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
3bd618f2-89c9-4790-87d4-38d82830c226 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,541 | supabase-export-v2 | 4067fcfb2b5bdbaa | After it has been used you can make assertions about the access using the normal mock methods and attributes:
>>> mock.__getitem__.call_args_list
[call('a'), call('c'), call('d'), call('b'), call('d')]
>>> mock.__setitem__.call_args_list
[call('b', 'fish'), call('d', 'eggs')]
>>> my_dict
{'a': 1, 'b': 'fish', 'c':... | trusted_official_docs | CPython Docs | After it has been used you can make assertions about the access using the normal mock methods and attributes:
>>> mock.__getitem__.call_args_list
[call('a'), call('c'), call('d'), call('b'), call('d')]
>>> mock.__setitem__.call_args_list
[call('b', 'fish'), call('d', 'eggs')]
>>> my_dict
{'a': 1, 'b': 'fish', 'c':... | After it has been used you can make assertions about the access using the normal mock methods and attributes:
>>> mock.__getitem__.call_args_list
[call('a'), call('c'), call('d'), call('b'), call('d')]
>>> mock.__setitem__.call_args_list
[call('b', 'fish'), call('d', 'eggs')]
>>> my_dict
{'a': 1, 'b': 'fish', 'c':... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
3eb357de-79e6-4d97-9771-bfd7b3b491ab | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,492 | supabase-export-v2 | bf1d3da2a49e11de | Mocking unbound methods ~~~~~~~~~~~~~~~~~~~~~~~
Sometimes a test needs to patch an *unbound method*, which means patching the
method on the class rather than on the instance. In order to make assertions
about which objects were calling this particular method, you need to pass
``self`` as the first argument. The issue i... | trusted_official_docs | CPython Docs | Mocking unbound methods ~~~~~~~~~~~~~~~~~~~~~~~
Sometimes a test needs to patch an *unbound method*, which means patching the
method on the class rather than on the instance. In order to make assertions
about which objects were calling this particular method, you need to pass
``self`` as the first argument. The issue i... | Mocking unbound methods ~~~~~~~~~~~~~~~~~~~~~~~
Sometimes a test needs to patch an *unbound method*, which means patching the
method on the class rather than on the instance. In order to make assertions
about which objects were calling this particular method, you need to pass
``self`` as the first argument. The issue i... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
3f6d9935-76cd-4a58-af4a-96e209b4ef58 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,467 | supabase-export-v2 | 051c23283fb9e97f | Partial mocking ~~~~~~~~~~~~~~~
For some tests, you may want to mock out a call to :meth:`datetime.date.today`
to return a known date, but don't want to prevent the code under test from
creating new date objects. Unfortunately :class:`datetime.date` is written in C,
so you cannot just monkey-patch out the static :meth:... | trusted_official_docs | CPython Docs | Partial mocking ~~~~~~~~~~~~~~~
For some tests, you may want to mock out a call to :meth:`datetime.date.today`
to return a known date, but don't want to prevent the code under test from
creating new date objects. Unfortunately :class:`datetime.date` is written in C,
so you cannot just monkey-patch out the static :meth:... | Partial mocking ~~~~~~~~~~~~~~~
For some tests, you may want to mock out a call to :meth:`datetime.date.today`
to return a known date, but don't want to prevent the code under test from
creating new date objects. Unfortunately :class:`datetime.date` is written in C,
so you cannot just monkey-patch out the static :meth:... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
4074aef0-dbd8-44d2-abf5-74dc339abb1a | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,487 | supabase-export-v2 | b2886fbb367544f7 | self.assertIs(mymodule.SomeClass, MockSomeClass) ... ... def test_two(self, MockSomeClass): ... self.assertIs(mymodule.SomeClass, MockSomeClass) ... ... def not_a_test(self): ... return 'something' ... >>> MyTest('test_one').test_one() >>> MyTest('test_two').test_two() >>> MyTest('test_two').not_a_test() 'something'
An... | trusted_official_docs | CPython Docs | self.assertIs(mymodule.SomeClass, MockSomeClass) ... ... def test_two(self, MockSomeClass): ... self.assertIs(mymodule.SomeClass, MockSomeClass) ... ... def not_a_test(self): ... return 'something' ... >>> MyTest('test_one').test_one() >>> MyTest('test_two').test_two() >>> MyTest('test_two').not_a_test() 'something'
An... | self.assertIs(mymodule.SomeClass, MockSomeClass) ... ... def test_two(self, MockSomeClass): ... self.assertIs(mymodule.SomeClass, MockSomeClass) ... ... def not_a_test(self): ... return 'something' ... >>> MyTest('test_one').test_one() >>> MyTest('test_two').test_two() >>> MyTest('test_two').not_a_test() 'something'
An... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
409fb6a6-14f1-44ba-8f53-a82b5436200d | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,550 | supabase-export-v2 | c4cad927e53c9d3a | MagicMock(**kwargs) ... >>> mymock = Subclass() >>> mymock.foo <MagicMock name='mock.foo' id='...'> >>> assert isinstance(mymock, Subclass) >>> assert not isinstance(mymock.foo, Subclass) >>> assert not isinstance(mymock(), Subclass)
.. [#] An exception to this rule are the non-callable mocks. Attributes use the
calla... | trusted_official_docs | CPython Docs | MagicMock(**kwargs) ... >>> mymock = Subclass() >>> mymock.foo <MagicMock name='mock.foo' id='...'> >>> assert isinstance(mymock, Subclass) >>> assert not isinstance(mymock.foo, Subclass) >>> assert not isinstance(mymock(), Subclass)
.. [#] An exception to this rule are the non-callable mocks. Attributes use the
calla... | MagicMock(**kwargs) ... >>> mymock = Subclass() >>> mymock.foo <MagicMock name='mock.foo' id='...'> >>> assert isinstance(mymock, Subclass) >>> assert not isinstance(mymock.foo, Subclass) >>> assert not isinstance(mymock(), Subclass)
.. [#] An exception to this rule are the non-callable mocks. Attributes use the
calla... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
46d23e95-686f-4e2b-8629-546ceb730dd9 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,500 | supabase-export-v2 | c63ced812a528bb1 | If your mock is only being called once you can use the :meth:`~Mock.assert_called_once_with` method that also asserts that the :attr:`~Mock.call_count` is one.
>>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
>>> mock.foo_bar()
>>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
Traceback (most ... | trusted_official_docs | CPython Docs | If your mock is only being called once you can use the :meth:`~Mock.assert_called_once_with` method that also asserts that the :attr:`~Mock.call_count` is one.
>>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
>>> mock.foo_bar()
>>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
Traceback (most ... | If your mock is only being called once you can use the :meth:`~Mock.assert_called_once_with` method that also asserts that the :attr:`~Mock.call_count` is one.
>>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
>>> mock.foo_bar()
>>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
Traceback (most ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
4983ccbd-624d-4fff-a82f-278da92f353a | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,458 | supabase-export-v2 | 63b7822a67375418 | configuration to do. Let's assume the object it returns is 'file-like', so we'll ensure that our response object uses the builtin :func:`open` as its ``spec``.
To do this we create a mock instance as our mock backend and create a mock
response object for it. To set the response as the return value for that final
``star... | trusted_official_docs | CPython Docs | configuration to do. Let's assume the object it returns is 'file-like', so we'll ensure that our response object uses the builtin :func:`open` as its ``spec``.
To do this we create a mock instance as our mock backend and create a mock
response object for it. To set the response as the return value for that final
``star... | configuration to do. Let's assume the object it returns is 'file-like', so we'll ensure that our response object uses the builtin :func:`open` as its ``spec``.
To do this we create a mock instance as our mock backend and create a mock
response object for it. To set the response as the return value for that final
``star... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
4a2f672b-e848-4c1d-bc78-c146047e2f11 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,408 | supabase-export-v2 | 2bfee62f716494ff | Creating a mock from an existing object ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
One problem with over use of mocking is that it couples your tests to the
implementation of your mocks rather than your real code. Suppose you have a
class that implements ``some_method``. In a test for another class, you
provide a mock of ... | trusted_official_docs | CPython Docs | Creating a mock from an existing object ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
One problem with over use of mocking is that it couples your tests to the
implementation of your mocks rather than your real code. Suppose you have a
class that implements ``some_method``. In a test for another class, you
provide a mock of ... | Creating a mock from an existing object ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
One problem with over use of mocking is that it couples your tests to the
implementation of your mocks rather than your real code. Suppose you have a
class that implements ``some_method``. In a test for another class, you
provide a mock of ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
4b0ba5c0-e9e8-4040-8e1a-f436a9f97ecd | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,572 | supabase-export-v2 | d3b97754a6a13ff8 | then you can attach them to a manager mock using the :meth:`~Mock.attach_mock` method. After attaching calls will be recorded in ``mock_calls`` of the manager. ::
>>> manager = MagicMock()
>>> with patch('mymodule.Class1') as MockClass1:
... with patch('mymodule.Class2') as MockClass2:
... manager.attach_mock(MockCl... | trusted_official_docs | CPython Docs | then you can attach them to a manager mock using the :meth:`~Mock.attach_mock` method. After attaching calls will be recorded in ``mock_calls`` of the manager. ::
>>> manager = MagicMock()
>>> with patch('mymodule.Class1') as MockClass1:
... with patch('mymodule.Class2') as MockClass2:
... manager.attach_mock(MockCl... | then you can attach them to a manager mock using the :meth:`~Mock.attach_mock` method. After attaching calls will be recorded in ``mock_calls`` of the manager. ::
>>> manager = MagicMock()
>>> with patch('mymodule.Class1') as MockClass1:
... with patch('mymodule.Class2') as MockClass2:
... manager.attach_mock(MockCl... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
4cfd2a70-19f7-4bff-8795-4747d93511da | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,530 | supabase-export-v2 | 0ad0d1608bcaa65b | with :class:`MagicMock`, which will behave like a dictionary, and using :data:`~Mock.side_effect` to delegate dictionary access to a real underlying dictionary that is under our control.
When the :meth:`~object.__getitem__` and :meth:`~object.__setitem__` methods
of our ``MagicMock`` are called
(normal dictionary acces... | trusted_official_docs | CPython Docs | with :class:`MagicMock`, which will behave like a dictionary, and using :data:`~Mock.side_effect` to delegate dictionary access to a real underlying dictionary that is under our control.
When the :meth:`~object.__getitem__` and :meth:`~object.__setitem__` methods
of our ``MagicMock`` are called
(normal dictionary acces... | with :class:`MagicMock`, which will behave like a dictionary, and using :data:`~Mock.side_effect` to delegate dictionary access to a real underlying dictionary that is under our control.
When the :meth:`~object.__getitem__` and :meth:`~object.__setitem__` methods
of our ``MagicMock`` are called
(normal dictionary acces... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
515417dd-8110-4850-b6d2-2c8f8c491eb7 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,456 | supabase-export-v2 | e554bfe27f554353 | >>> class Something: ... def __init__(self): ... self.backend = BackendProvider() ... def method(self): ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call() ... # more code
Assuming that ``BackendProvider`` is already well tested, how do we test
``method()``? Specifically, we want... | trusted_official_docs | CPython Docs | >>> class Something: ... def __init__(self): ... self.backend = BackendProvider() ... def method(self): ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call() ... # more code
Assuming that ``BackendProvider`` is already well tested, how do we test
``method()``? Specifically, we want... | >>> class Something: ... def __init__(self): ... self.backend = BackendProvider() ... def method(self): ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call() ... # more code
Assuming that ``BackendProvider`` is already well tested, how do we test
``method()``? Specifically, we want... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
5294d7d6-dc5d-4fd3-bfff-7496e0e1d9b5 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,443 | supabase-export-v2 | 79d6376f0fc38f34 | ``patch``, ``patch.object`` and ``patch.dict`` can all be used as context managers.
Where you use :func:`patch` to create a mock for you, you can get a reference to the
mock using the "as" form of the with statement: | trusted_official_docs | CPython Docs | ``patch``, ``patch.object`` and ``patch.dict`` can all be used as context managers.
Where you use :func:`patch` to create a mock for you, you can get a reference to the
mock using the "as" form of the with statement: | ``patch``, ``patch.object`` and ``patch.dict`` can all be used as context managers.
Where you use :func:`patch` to create a mock for you, you can get a reference to the
mock using the "as" form of the with statement: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
53df1498-be86-4549-bf74-01d84637bf77 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,438 | supabase-export-v2 | ffd538d91400ca34 | You can stack up multiple patch decorators using this pattern::
>>> class MyTest(unittest.TestCase):
... @patch('package.module.ClassName1')
... @patch('package.module.ClassName2')
... def test_something(self, MockClass2, MockClass1):
... self.assertIs(package.module.ClassName1, MockClass1)
... self.assertIs(packa... | trusted_official_docs | CPython Docs | You can stack up multiple patch decorators using this pattern::
>>> class MyTest(unittest.TestCase):
... @patch('package.module.ClassName1')
... @patch('package.module.ClassName2')
... def test_something(self, MockClass2, MockClass1):
... self.assertIs(package.module.ClassName1, MockClass1)
... self.assertIs(packa... | You can stack up multiple patch decorators using this pattern::
>>> class MyTest(unittest.TestCase):
... @patch('package.module.ClassName1')
... @patch('package.module.ClassName2')
... def test_something(self, MockClass2, MockClass1):
... self.assertIs(package.module.ClassName1, MockClass1)
... self.assertIs(packa... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
546a2f57-e13e-49c9-8f8c-decc9d5783d7 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,503 | supabase-export-v2 | 44e45945127133b1 | >>> mock = Mock(return_value=None) >>> mock(1, 2, 3) >>> mock(4, 5, 6) >>> mock() >>> mock.call_args_list [call(1, 2, 3), call(4, 5, 6), call()]
The :data:`call` helper makes it easy to make assertions about these calls. You
can build up a list of expected calls and compare it to ``call_args_list``. This
looks remarkab... | trusted_official_docs | CPython Docs | >>> mock = Mock(return_value=None) >>> mock(1, 2, 3) >>> mock(4, 5, 6) >>> mock() >>> mock.call_args_list [call(1, 2, 3), call(4, 5, 6), call()]
The :data:`call` helper makes it easy to make assertions about these calls. You
can build up a list of expected calls and compare it to ``call_args_list``. This
looks remarkab... | >>> mock = Mock(return_value=None) >>> mock(1, 2, 3) >>> mock(4, 5, 6) >>> mock() >>> mock.call_args_list [call(1, 2, 3), call(4, 5, 6), call()]
The :data:`call` helper makes it easy to make assertions about these calls. You
can build up a list of expected calls and compare it to ``call_args_list``. This
looks remarkab... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
550026a2-2444-4980-92ec-7a86998ba99f | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,488 | supabase-export-v2 | 8ce138d46730a0da | An alternative way of managing patches is to use the :ref:`start-and-stop`. These allow you to move the patching into your ``setUp`` and ``tearDown`` methods. ::
>>> class MyTest(unittest.TestCase):
... def setUp(self):
... self.patcher = patch('mymodule.foo')
... self.mock_foo = self.patcher.start()
... ... def te... | trusted_official_docs | CPython Docs | An alternative way of managing patches is to use the :ref:`start-and-stop`. These allow you to move the patching into your ``setUp`` and ``tearDown`` methods. ::
>>> class MyTest(unittest.TestCase):
... def setUp(self):
... self.patcher = patch('mymodule.foo')
... self.mock_foo = self.patcher.start()
... ... def te... | An alternative way of managing patches is to use the :ref:`start-and-stop`. These allow you to move the patching into your ``setUp`` and ``tearDown`` methods. ::
>>> class MyTest(unittest.TestCase):
... def setUp(self):
... self.patcher = patch('mymodule.foo')
... self.mock_foo = self.patcher.start()
... ... def te... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
55896617-7d2a-42ff-a8cc-8851fff220b5 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,514 | supabase-export-v2 | 9adb0ae5226f9f00 | store the arguments so that we can use the mock methods for doing the assertion. Again a helper function sets this up for us. ::
>>> from copy import deepcopy
>>> from unittest.mock import Mock, patch, DEFAULT
>>> def copy_call_args(mock):
... new_mock = Mock()
... def side_effect(*args, **kwargs):
... args = deep... | trusted_official_docs | CPython Docs | store the arguments so that we can use the mock methods for doing the assertion. Again a helper function sets this up for us. ::
>>> from copy import deepcopy
>>> from unittest.mock import Mock, patch, DEFAULT
>>> def copy_call_args(mock):
... new_mock = Mock()
... def side_effect(*args, **kwargs):
... args = deep... | store the arguments so that we can use the mock methods for doing the assertion. Again a helper function sets this up for us. ::
>>> from copy import deepcopy
>>> from unittest.mock import Mock, patch, DEFAULT
>>> def copy_call_args(mock):
... new_mock = Mock()
... def side_effect(*args, **kwargs):
... args = deep... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
5782b934-89a3-4f13-9872-d441de5d0762 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,410 | supabase-export-v2 | 02ac6e13932cfde5 | the implementation of your specification, then tests that use that class will start failing immediately without you having to instantiate the class in those tests.
>>> mock = Mock(spec=SomeClass)
>>> mock.old_method()
Traceback (most recent call last):
... AttributeError: Mock object has no attribute 'old_method'. D... | trusted_official_docs | CPython Docs | the implementation of your specification, then tests that use that class will start failing immediately without you having to instantiate the class in those tests.
>>> mock = Mock(spec=SomeClass)
>>> mock.old_method()
Traceback (most recent call last):
... AttributeError: Mock object has no attribute 'old_method'. D... | the implementation of your specification, then tests that use that class will start failing immediately without you having to instantiate the class in those tests.
>>> mock = Mock(spec=SomeClass)
>>> mock.old_method()
Traceback (most recent call last):
... AttributeError: Mock object has no attribute 'old_method'. D... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
58557fae-af86-4c60-9750-0c8b73d9c1df | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,469 | supabase-export-v2 | 01be97a452cdd511 | you can effectively wrap the date class with a mock, while passing through calls to the constructor to the real class (and returning real instances).
The :func:`patch decorator <patch>` is used here to
mock out the ``date`` class in the module under test. The :attr:`~Mock.side_effect`
attribute on the mock date class i... | trusted_official_docs | CPython Docs | you can effectively wrap the date class with a mock, while passing through calls to the constructor to the real class (and returning real instances).
The :func:`patch decorator <patch>` is used here to
mock out the ``date`` class in the module under test. The :attr:`~Mock.side_effect`
attribute on the mock date class i... | you can effectively wrap the date class with a mock, while passing through calls to the constructor to the real class (and returning real instances).
The :func:`patch decorator <patch>` is used here to
mock out the ``date`` class in the module under test. The :attr:`~Mock.side_effect`
attribute on the mock date class i... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
5893debf-88cc-483d-a565-93c9b65f9693 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,484 | supabase-export-v2 | 710948bff459f485 | but we aren't concerned about them here. A very good introduction to generators and how powerful they are is: `Generator Tricks for Systems Programmers <http://www.dabeaz.com/generators/>`_.
Applying the same patch to every test method
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | trusted_official_docs | CPython Docs | but we aren't concerned about them here. A very good introduction to generators and how powerful they are is: `Generator Tricks for Systems Programmers <http://www.dabeaz.com/generators/>`_.
Applying the same patch to every test method
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | but we aren't concerned about them here. A very good introduction to generators and how powerful they are is: `Generator Tricks for Systems Programmers <http://www.dabeaz.com/generators/>`_.
Applying the same patch to every test method
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
5c6e3fb5-2603-4801-90ce-a1367601e9d1 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,581 | supabase-export-v2 | 867e2dfd1fbeda46 | we are only interested in some of the attributes of this object then we can create a matcher that will check these attributes for us.
You can see in this example how a 'standard' call to ``assert_called_with`` isn't
sufficient: | trusted_official_docs | CPython Docs | we are only interested in some of the attributes of this object then we can create a matcher that will check these attributes for us.
You can see in this example how a 'standard' call to ``assert_called_with`` isn't
sufficient: | we are only interested in some of the attributes of this object then we can create a matcher that will check these attributes for us.
You can see in this example how a 'standard' call to ``assert_called_with`` isn't
sufficient: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
5cf21a7a-09af-4d50-b125-321eeeddea20 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,575 | supabase-export-v2 | 83b04d9170dce594 | >>> m = MagicMock() >>> m().foo().bar().baz() <MagicMock name='mock().foo().bar().baz()' id='...'> >>> m.one().two().three() <MagicMock name='mock.one().two().three()' id='...'> >>> calls = call.one().two().three().call_list() >>> m.assert_has_calls(calls)
Even though the chained call ``m.one().two().three()`` aren't t... | trusted_official_docs | CPython Docs | >>> m = MagicMock() >>> m().foo().bar().baz() <MagicMock name='mock().foo().bar().baz()' id='...'> >>> m.one().two().three() <MagicMock name='mock.one().two().three()' id='...'> >>> calls = call.one().two().three().call_list() >>> m.assert_has_calls(calls)
Even though the chained call ``m.one().two().three()`` aren't t... | >>> m = MagicMock() >>> m().foo().bar().baz() <MagicMock name='mock().foo().bar().baz()' id='...'> >>> m.one().two().three() <MagicMock name='mock.one().two().three()' id='...'> >>> calls = call.one().two().three().call_list() >>> m.assert_has_calls(calls)
Even though the chained call ``m.one().two().three()`` aren't t... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
616f522c-d2ce-4677-bf27-b37e172c7709 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,576 | supabase-export-v2 | 2ee9d2da804459db | Even though the chained call ``m.one().two().three()`` aren't the only calls that have been made to the mock, the assert still succeeds.
Sometimes a mock may have several calls made to it, and you are only interested
in asserting about *some* of those calls. You may not even care about the
order. In this case you can p... | trusted_official_docs | CPython Docs | Even though the chained call ``m.one().two().three()`` aren't the only calls that have been made to the mock, the assert still succeeds.
Sometimes a mock may have several calls made to it, and you are only interested
in asserting about *some* of those calls. You may not even care about the
order. In this case you can p... | Even though the chained call ``m.one().two().three()`` aren't the only calls that have been made to the mock, the assert still succeeds.
Sometimes a mock may have several calls made to it, and you are only interested
in asserting about *some* of those calls. You may not even care about the
order. In this case you can p... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
62b1877e-cb30-4b40-a12e-026b51f10830 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,391 | supabase-export-v2 | 234cada143f06fe9 | We can use :data:`call` to construct the set of calls in a "chained call" like this for easy assertion afterwards:
>>> mock = Mock()
>>> cursor = mock.connection.cursor.return_value
>>> cursor.execute.return_value = ['foo']
>>> mock.connection.cursor().execute("SELECT 1")
['foo']
>>> expected = call.connection.cur... | trusted_official_docs | CPython Docs | We can use :data:`call` to construct the set of calls in a "chained call" like this for easy assertion afterwards:
>>> mock = Mock()
>>> cursor = mock.connection.cursor.return_value
>>> cursor.execute.return_value = ['foo']
>>> mock.connection.cursor().execute("SELECT 1")
['foo']
>>> expected = call.connection.cur... | We can use :data:`call` to construct the set of calls in a "chained call" like this for easy assertion afterwards:
>>> mock = Mock()
>>> cursor = mock.connection.cursor.return_value
>>> cursor.execute.return_value = ['foo']
>>> mock.connection.cursor().execute("SELECT 1")
['foo']
>>> expected = call.connection.cur... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
63aeeb63-1426-4b25-b1b9-c35ccaffaceb | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,490 | supabase-export-v2 | 9bd31688edae9aa8 | can be fiddlier than you might think, because if an exception is raised in the setUp then tearDown is not called. :meth:`unittest.TestCase.addCleanup` makes this easier::
>>> class MyTest(unittest.TestCase):
... def setUp(self):
... patcher = patch('mymodule.foo')
... self.addCleanup(patcher.stop)
... self.mock_foo... | trusted_official_docs | CPython Docs | can be fiddlier than you might think, because if an exception is raised in the setUp then tearDown is not called. :meth:`unittest.TestCase.addCleanup` makes this easier::
>>> class MyTest(unittest.TestCase):
... def setUp(self):
... patcher = patch('mymodule.foo')
... self.addCleanup(patcher.stop)
... self.mock_foo... | can be fiddlier than you might think, because if an exception is raised in the setUp then tearDown is not called. :meth:`unittest.TestCase.addCleanup` makes this easier::
>>> class MyTest(unittest.TestCase):
... def setUp(self):
... patcher = patch('mymodule.foo')
... self.addCleanup(patcher.stop)
... self.mock_foo... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
63d49df4-353b-4caf-979c-0033d3e1f92e | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,367 | supabase-export-v2 | 90df1ff0a509f475 | mock. Instances are created by *calling the class*. This means you access the "mock instance" by looking at the return value of the mocked class.
In the example below we have a function ``some_function`` that instantiates ``Foo``
and calls a method on it. The call to :func:`patch` replaces the class ``Foo`` with a
mock... | trusted_official_docs | CPython Docs | mock. Instances are created by *calling the class*. This means you access the "mock instance" by looking at the return value of the mocked class.
In the example below we have a function ``some_function`` that instantiates ``Foo``
and calls a method on it. The call to :func:`patch` replaces the class ``Foo`` with a
mock... | mock. Instances are created by *calling the class*. This means you access the "mock instance" by looking at the return value of the mocked class.
In the example below we have a function ``some_function`` that instantiates ``Foo``
and calls a method on it. The call to :func:`patch` replaces the class ``Foo`` with a
mock... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
67780555-184b-4cb3-b161-e7bea71abc04 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,413 | supabase-export-v2 | 245638e0316b0463 | >>> def f(a, b, c): pass ... >>> mock = Mock(spec=f) >>> mock(1, 2, 3) <Mock name='mock()' id='140161580456576'> >>> mock.assert_called_with(a=1, b=2, c=3)
If you want this smarter matching to also work with method calls on the mock,
you can use :ref:`auto-speccing <auto-speccing>`. | trusted_official_docs | CPython Docs | >>> def f(a, b, c): pass ... >>> mock = Mock(spec=f) >>> mock(1, 2, 3) <Mock name='mock()' id='140161580456576'> >>> mock.assert_called_with(a=1, b=2, c=3)
If you want this smarter matching to also work with method calls on the mock,
you can use :ref:`auto-speccing <auto-speccing>`. | >>> def f(a, b, c): pass ... >>> mock = Mock(spec=f) >>> mock(1, 2, 3) <Mock name='mock()' id='140161580456576'> >>> mock.assert_called_with(a=1, b=2, c=3)
If you want this smarter matching to also work with method calls on the mock,
you can use :ref:`auto-speccing <auto-speccing>`. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
67a4301a-8696-42dd-9e5e-37fe62c67271 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,371 | supabase-export-v2 | dcc37b707674e3e2 | mock and can be helpful when the mock appears in test failure messages. The name is also propagated to attributes or methods of the mock:
>>> mock = MagicMock(name='foo')
>>> mock
<MagicMock name='foo' id='...'>
>>> mock.method
<MagicMock name='foo.method' id='...'> | trusted_official_docs | CPython Docs | mock and can be helpful when the mock appears in test failure messages. The name is also propagated to attributes or methods of the mock:
>>> mock = MagicMock(name='foo')
>>> mock
<MagicMock name='foo' id='...'>
>>> mock.method
<MagicMock name='foo.method' id='...'> | mock and can be helpful when the mock appears in test failure messages. The name is also propagated to attributes or methods of the mock:
>>> mock = MagicMock(name='foo')
>>> mock
<MagicMock name='foo' id='...'>
>>> mock.method
<MagicMock name='foo.method' id='...'> | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
68170b73-cecf-4080-afdf-41139df42add | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,548 | supabase-export-v2 | 318c8646fcf19175 | is inconvenient. For example, `one user <https://code.google.com/archive/p/mock/issues/105>`_ is subclassing mock to created a `Twisted adaptor <https://twisted.org/documents/11.0.0/api/twisted.python.components.html>`_. Having this applied to attributes too actually causes errors.
``Mock`` (in all its flavours) uses a... | trusted_official_docs | CPython Docs | is inconvenient. For example, `one user <https://code.google.com/archive/p/mock/issues/105>`_ is subclassing mock to created a `Twisted adaptor <https://twisted.org/documents/11.0.0/api/twisted.python.components.html>`_. Having this applied to attributes too actually causes errors.
``Mock`` (in all its flavours) uses a... | is inconvenient. For example, `one user <https://code.google.com/archive/p/mock/issues/105>`_ is subclassing mock to created a `Twisted adaptor <https://twisted.org/documents/11.0.0/api/twisted.python.components.html>`_. Having this applied to attributes too actually causes errors.
``Mock`` (in all its flavours) uses a... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
6a51fb8b-c965-4ef5-923c-e52633f4809c | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,424 | supabase-export-v2 | e76e1fa42afebf94 | you patch objects in the namespace where they are looked up. This is normally straightforward, but for a quick guide read :ref:`where to patch <where-to-patch>`.
A common need in tests is to patch a class attribute or a module attribute,
for example patching a builtin or patching a class in a module to test that it
is ... | trusted_official_docs | CPython Docs | you patch objects in the namespace where they are looked up. This is normally straightforward, but for a quick guide read :ref:`where to patch <where-to-patch>`.
A common need in tests is to patch a class attribute or a module attribute,
for example patching a builtin or patching a class in a module to test that it
is ... | you patch objects in the namespace where they are looked up. This is normally straightforward, but for a quick guide read :ref:`where to patch <where-to-patch>`.
A common need in tests is to patch a class attribute or a module attribute,
for example patching a builtin or patching a class in a module to test that it
is ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
6c7c7cae-e60d-403f-b27f-97fd5ba2b908 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,399 | supabase-export-v2 | 2c81b0835eaa0066 | >>> mock = MagicMock(side_effect=[4, 5, 6]) >>> mock() 4 >>> mock() 5 >>> mock() 6
For more advanced use cases, like dynamically varying the return values
depending on what the mock is called with, ``side_effect`` can be a function. The function will be called with the same arguments as the mock. Whatever the
function ... | trusted_official_docs | CPython Docs | >>> mock = MagicMock(side_effect=[4, 5, 6]) >>> mock() 4 >>> mock() 5 >>> mock() 6
For more advanced use cases, like dynamically varying the return values
depending on what the mock is called with, ``side_effect`` can be a function. The function will be called with the same arguments as the mock. Whatever the
function ... | >>> mock = MagicMock(side_effect=[4, 5, 6]) >>> mock() 4 >>> mock() 5 >>> mock() 6
For more advanced use cases, like dynamically varying the return values
depending on what the mock is called with, ``side_effect`` can be a function. The function will be called with the same arguments as the mock. Whatever the
function ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
6d449c9d-9ed4-4cb2-b2e3-9ecc50883b00 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,445 | supabase-export-v2 | 070a82c1f37768ab | pass ... >>> with patch.object(ProductionClass, 'method') as mock_method: ... mock_method.return_value = None ... real = ProductionClass() ... real.method(1, 2, 3) ... >>> mock_method.assert_called_with(1, 2, 3)
As an alternative ``patch``, ``patch.object`` and ``patch.dict`` can be used as
class decorators. When used ... | trusted_official_docs | CPython Docs | pass ... >>> with patch.object(ProductionClass, 'method') as mock_method: ... mock_method.return_value = None ... real = ProductionClass() ... real.method(1, 2, 3) ... >>> mock_method.assert_called_with(1, 2, 3)
As an alternative ``patch``, ``patch.object`` and ``patch.dict`` can be used as
class decorators. When used ... | pass ... >>> with patch.object(ProductionClass, 'method') as mock_method: ... mock_method.return_value = None ... real = ProductionClass() ... real.method(1, 2, 3) ... >>> mock_method.assert_called_with(1, 2, 3)
As an alternative ``patch``, ``patch.object`` and ``patch.dict`` can be used as
class decorators. When used ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
6f059d8f-8bb2-42ee-a523-dbc005b8244c | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,504 | supabase-export-v2 | a588a309e4b4429f | calls. You can build up a list of expected calls and compare it to ``call_args_list``. This looks remarkably similar to the repr of the ``call_args_list``:
>>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
>>> mock.call_args_list == expected
True | trusted_official_docs | CPython Docs | calls. You can build up a list of expected calls and compare it to ``call_args_list``. This looks remarkably similar to the repr of the ``call_args_list``:
>>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
>>> mock.call_args_list == expected
True | calls. You can build up a list of expected calls and compare it to ``call_args_list``. This looks remarkably similar to the repr of the ``call_args_list``:
>>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
>>> mock.call_args_list == expected
True | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
7095857a-7db0-4060-a858-79fe24803890 | CPython Docs | file://datasets/cpython/Doc/library/unittest.mock-examples.rst | unknown | 7bcbcebe-cc8a-441d-b05d-03531e5ebd16 | 14,531 | supabase-export-v2 | 562754a3f4573b20 | dictionary access) then ``side_effect`` is called with the key (and in the case of ``__setitem__`` the value too). We can also control what is returned.
After the ``MagicMock`` has been used we can use attributes like
:data:`~Mock.call_args_list` to assert about how the dictionary was used: | trusted_official_docs | CPython Docs | dictionary access) then ``side_effect`` is called with the key (and in the case of ``__setitem__`` the value too). We can also control what is returned.
After the ``MagicMock`` has been used we can use attributes like
:data:`~Mock.call_args_list` to assert about how the dictionary was used: | dictionary access) then ``side_effect`` is called with the key (and in the case of ``__setitem__`` the value too). We can also control what is returned.
After the ``MagicMock`` has been used we can use attributes like
:data:`~Mock.call_args_list` to assert about how the dictionary was used: | 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.