aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python
diff options
context:
space:
mode:
authorAlexander Smirnov <alex@ydb.tech>2024-10-28 20:34:11 +0000
committerAlexander Smirnov <alex@ydb.tech>2024-10-28 20:34:11 +0000
commitef9875b11a33dbd25e92bc6b4cf692c18c9ba0ce (patch)
tree1f2fd4e4d9e585da35937b42fbda5f854af04728 /contrib/python
parent37ae9cc90160b53eb0e22021c47b3996a01cd656 (diff)
parente3c8507a3d1cb090278f211232ddfde3bedc54d4 (diff)
downloadydb-ef9875b11a33dbd25e92bc6b4cf692c18c9ba0ce.tar.gz
Merge branch 'rightlib' into mergelibs-241028-2033
Diffstat (limited to 'contrib/python')
-rw-r--r--contrib/python/MarkupSafe/py3/.dist-info/METADATA115
-rw-r--r--contrib/python/MarkupSafe/py3/LICENSE.txt (renamed from contrib/python/MarkupSafe/py3/LICENSE.rst)0
-rw-r--r--contrib/python/MarkupSafe/py3/README.md40
-rw-r--r--contrib/python/MarkupSafe/py3/README.rst67
-rw-r--r--contrib/python/MarkupSafe/py3/markupsafe/__init__.py359
-rw-r--r--contrib/python/MarkupSafe/py3/markupsafe/_native.py61
-rw-r--r--contrib/python/MarkupSafe/py3/markupsafe/_speedups.c156
-rw-r--r--contrib/python/MarkupSafe/py3/markupsafe/_speedups.pyi10
-rw-r--r--contrib/python/MarkupSafe/py3/tests/__init__.py0
-rw-r--r--contrib/python/MarkupSafe/py3/tests/conftest.py36
-rw-r--r--contrib/python/MarkupSafe/py3/tests/test_escape.py13
-rw-r--r--contrib/python/MarkupSafe/py3/tests/test_exception_custom_html.py9
-rw-r--r--contrib/python/MarkupSafe/py3/tests/test_leak.py25
-rw-r--r--contrib/python/MarkupSafe/py3/tests/test_markupsafe.py75
-rw-r--r--contrib/python/MarkupSafe/py3/ya.make2
-rw-r--r--contrib/python/anyio/.dist-info/METADATA6
-rw-r--r--contrib/python/anyio/anyio/_backends/_asyncio.py233
-rw-r--r--contrib/python/anyio/anyio/_backends/_trio.py39
-rw-r--r--contrib/python/anyio/anyio/_core/_fileio.py29
-rw-r--r--contrib/python/anyio/anyio/_core/_signals.py6
-rw-r--r--contrib/python/anyio/anyio/_core/_streams.py4
-rw-r--r--contrib/python/anyio/anyio/_core/_subprocesses.py21
-rw-r--r--contrib/python/anyio/anyio/abc/_eventloop.py8
-rw-r--r--contrib/python/anyio/anyio/abc/_sockets.py8
-rw-r--r--contrib/python/anyio/anyio/from_thread.py16
-rw-r--r--contrib/python/anyio/anyio/pytest_plugin.py51
-rw-r--r--contrib/python/anyio/anyio/streams/tls.py11
-rw-r--r--contrib/python/anyio/ya.make2
-rw-r--r--contrib/python/argcomplete/py3/.dist-info/METADATA4
-rw-r--r--contrib/python/argcomplete/py3/argcomplete/packages/_argparse.py2
-rw-r--r--contrib/python/argcomplete/py3/ya.make2
-rw-r--r--contrib/python/clickhouse-connect/.dist-info/METADATA2
-rw-r--r--contrib/python/clickhouse-connect/clickhouse_connect/__version__.py2
-rw-r--r--contrib/python/clickhouse-connect/clickhouse_connect/driver/__init__.py5
-rw-r--r--contrib/python/clickhouse-connect/clickhouse_connect/driver/asyncclient.py47
-rw-r--r--contrib/python/clickhouse-connect/ya.make2
-rw-r--r--contrib/python/hypothesis/py3/.dist-info/METADATA2
-rw-r--r--contrib/python/hypothesis/py3/hypothesis/stateful.py16
-rw-r--r--contrib/python/hypothesis/py3/hypothesis/version.py2
-rw-r--r--contrib/python/hypothesis/py3/ya.make2
-rw-r--r--contrib/python/zope.interface/py3/.dist-info/METADATA33
-rw-r--r--contrib/python/zope.interface/py3/ya.make2
-rw-r--r--contrib/python/zope.interface/py3/zope/interface/common/interfaces.py72
-rw-r--r--contrib/python/zope.interface/py3/zope/interface/common/tests/basemapping.py2
-rw-r--r--contrib/python/zope.interface/py3/zope/interface/common/tests/test_collections.py10
-rw-r--r--contrib/python/zope.interface/py3/zope/interface/declarations.py2
-rw-r--r--contrib/python/zope.interface/py3/zope/interface/interface.py4
-rw-r--r--contrib/python/zope.interface/py3/zope/interface/interfaces.py1
-rw-r--r--contrib/python/zope.interface/py3/zope/interface/tests/test_advice.py12
-rw-r--r--contrib/python/zope.interface/py3/zope/interface/tests/test_declarations.py72
-rw-r--r--contrib/python/zope.interface/py3/zope/interface/tests/test_interface.py182
-rw-r--r--contrib/python/zope.interface/py3/zope/interface/tests/test_interfaces.py2
-rw-r--r--contrib/python/zope.interface/py3/zope/interface/tests/test_odd_declarations.py32
-rw-r--r--contrib/python/zope.interface/py3/zope/interface/tests/test_registry.py572
54 files changed, 1261 insertions, 1227 deletions
diff --git a/contrib/python/MarkupSafe/py3/.dist-info/METADATA b/contrib/python/MarkupSafe/py3/.dist-info/METADATA
index dfe37d52dfb..cbf0cfef4f1 100644
--- a/contrib/python/MarkupSafe/py3/.dist-info/METADATA
+++ b/contrib/python/MarkupSafe/py3/.dist-info/METADATA
@@ -1,16 +1,41 @@
Metadata-Version: 2.1
Name: MarkupSafe
-Version: 2.1.5
+Version: 3.0.1
Summary: Safely add untrusted strings to HTML/XML markup.
-Home-page: https://palletsprojects.com/p/markupsafe/
-Maintainer: Pallets
-Maintainer-email: contact@palletsprojects.com
-License: BSD-3-Clause
+Maintainer-email: Pallets <contact@palletsprojects.com>
+License: Copyright 2010 Pallets
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ 3. Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
Project-URL: Donate, https://palletsprojects.com/donate
Project-URL: Documentation, https://markupsafe.palletsprojects.com/
Project-URL: Changes, https://markupsafe.palletsprojects.com/changes/
-Project-URL: Source Code, https://github.com/pallets/markupsafe/
-Project-URL: Issue Tracker, https://github.com/pallets/markupsafe/issues/
+Project-URL: Source, https://github.com/pallets/markupsafe/
Project-URL: Chat, https://discord.gg/pallets
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
@@ -20,12 +45,12 @@ Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
Classifier: Topic :: Text Processing :: Markup :: HTML
-Requires-Python: >=3.7
-Description-Content-Type: text/x-rst
-License-File: LICENSE.rst
+Classifier: Typing :: Typed
+Requires-Python: >=3.9
+Description-Content-Type: text/markdown
+License-File: LICENSE.txt
-MarkupSafe
-==========
+# MarkupSafe
MarkupSafe implements a text object that escapes characters so it is
safe to use in HTML and XML. Characters that have special meanings are
@@ -34,60 +59,34 @@ injection attacks, meaning untrusted user input can safely be displayed
on a page.
-Installing
-----------
+## Examples
-Install and update using `pip`_:
+```pycon
+>>> from markupsafe import Markup, escape
-.. code-block:: text
+>>> # escape replaces special characters and wraps in Markup
+>>> escape("<script>alert(document.cookie);</script>")
+Markup('&lt;script&gt;alert(document.cookie);&lt;/script&gt;')
- pip install -U MarkupSafe
+>>> # wrap in Markup to mark text "safe" and prevent escaping
+>>> Markup("<strong>Hello</strong>")
+Markup('<strong>hello</strong>')
-.. _pip: https://pip.pypa.io/en/stable/getting-started/
+>>> escape(Markup("<strong>Hello</strong>"))
+Markup('<strong>hello</strong>')
+>>> # Markup is a str subclass
+>>> # methods and operators escape their arguments
+>>> template = Markup("Hello <em>{name}</em>")
+>>> template.format(name='"World"')
+Markup('Hello <em>&#34;World&#34;</em>')
+```
-Examples
---------
-
-.. code-block:: pycon
-
- >>> from markupsafe import Markup, escape
-
- >>> # escape replaces special characters and wraps in Markup
- >>> escape("<script>alert(document.cookie);</script>")
- Markup('&lt;script&gt;alert(document.cookie);&lt;/script&gt;')
-
- >>> # wrap in Markup to mark text "safe" and prevent escaping
- >>> Markup("<strong>Hello</strong>")
- Markup('<strong>hello</strong>')
-
- >>> escape(Markup("<strong>Hello</strong>"))
- Markup('<strong>hello</strong>')
-
- >>> # Markup is a str subclass
- >>> # methods and operators escape their arguments
- >>> template = Markup("Hello <em>{name}</em>")
- >>> template.format(name='"World"')
- Markup('Hello <em>&#34;World&#34;</em>')
-
-
-Donate
-------
+## Donate
The Pallets organization develops and supports MarkupSafe and other
popular packages. In order to grow the community of contributors and
users, and allow the maintainers to devote more time to the projects,
-`please donate today`_.
-
-.. _please donate today: https://palletsprojects.com/donate
-
-
-Links
------
+[please donate today][].
-- Documentation: https://markupsafe.palletsprojects.com/
-- Changes: https://markupsafe.palletsprojects.com/changes/
-- PyPI Releases: https://pypi.org/project/MarkupSafe/
-- Source Code: https://github.com/pallets/markupsafe/
-- Issue Tracker: https://github.com/pallets/markupsafe/issues/
-- Chat: https://discord.gg/pallets
+[please donate today]: https://palletsprojects.com/donate
diff --git a/contrib/python/MarkupSafe/py3/LICENSE.rst b/contrib/python/MarkupSafe/py3/LICENSE.txt
index 9d227a0cc43..9d227a0cc43 100644
--- a/contrib/python/MarkupSafe/py3/LICENSE.rst
+++ b/contrib/python/MarkupSafe/py3/LICENSE.txt
diff --git a/contrib/python/MarkupSafe/py3/README.md b/contrib/python/MarkupSafe/py3/README.md
new file mode 100644
index 00000000000..df8fbaf908a
--- /dev/null
+++ b/contrib/python/MarkupSafe/py3/README.md
@@ -0,0 +1,40 @@
+# MarkupSafe
+
+MarkupSafe implements a text object that escapes characters so it is
+safe to use in HTML and XML. Characters that have special meanings are
+replaced so that they display as the actual characters. This mitigates
+injection attacks, meaning untrusted user input can safely be displayed
+on a page.
+
+
+## Examples
+
+```pycon
+>>> from markupsafe import Markup, escape
+
+>>> # escape replaces special characters and wraps in Markup
+>>> escape("<script>alert(document.cookie);</script>")
+Markup('&lt;script&gt;alert(document.cookie);&lt;/script&gt;')
+
+>>> # wrap in Markup to mark text "safe" and prevent escaping
+>>> Markup("<strong>Hello</strong>")
+Markup('<strong>hello</strong>')
+
+>>> escape(Markup("<strong>Hello</strong>"))
+Markup('<strong>hello</strong>')
+
+>>> # Markup is a str subclass
+>>> # methods and operators escape their arguments
+>>> template = Markup("Hello <em>{name}</em>")
+>>> template.format(name='"World"')
+Markup('Hello <em>&#34;World&#34;</em>')
+```
+
+## Donate
+
+The Pallets organization develops and supports MarkupSafe and other
+popular packages. In order to grow the community of contributors and
+users, and allow the maintainers to devote more time to the projects,
+[please donate today][].
+
+[please donate today]: https://palletsprojects.com/donate
diff --git a/contrib/python/MarkupSafe/py3/README.rst b/contrib/python/MarkupSafe/py3/README.rst
deleted file mode 100644
index 16431d3a6ab..00000000000
--- a/contrib/python/MarkupSafe/py3/README.rst
+++ /dev/null
@@ -1,67 +0,0 @@
-MarkupSafe
-==========
-
-MarkupSafe implements a text object that escapes characters so it is
-safe to use in HTML and XML. Characters that have special meanings are
-replaced so that they display as the actual characters. This mitigates
-injection attacks, meaning untrusted user input can safely be displayed
-on a page.
-
-
-Installing
-----------
-
-Install and update using `pip`_:
-
-.. code-block:: text
-
- pip install -U MarkupSafe
-
-.. _pip: https://pip.pypa.io/en/stable/getting-started/
-
-
-Examples
---------
-
-.. code-block:: pycon
-
- >>> from markupsafe import Markup, escape
-
- >>> # escape replaces special characters and wraps in Markup
- >>> escape("<script>alert(document.cookie);</script>")
- Markup('&lt;script&gt;alert(document.cookie);&lt;/script&gt;')
-
- >>> # wrap in Markup to mark text "safe" and prevent escaping
- >>> Markup("<strong>Hello</strong>")
- Markup('<strong>hello</strong>')
-
- >>> escape(Markup("<strong>Hello</strong>"))
- Markup('<strong>hello</strong>')
-
- >>> # Markup is a str subclass
- >>> # methods and operators escape their arguments
- >>> template = Markup("Hello <em>{name}</em>")
- >>> template.format(name='"World"')
- Markup('Hello <em>&#34;World&#34;</em>')
-
-
-Donate
-------
-
-The Pallets organization develops and supports MarkupSafe and other
-popular packages. In order to grow the community of contributors and
-users, and allow the maintainers to devote more time to the projects,
-`please donate today`_.
-
-.. _please donate today: https://palletsprojects.com/donate
-
-
-Links
------
-
-- Documentation: https://markupsafe.palletsprojects.com/
-- Changes: https://markupsafe.palletsprojects.com/changes/
-- PyPI Releases: https://pypi.org/project/MarkupSafe/
-- Source Code: https://github.com/pallets/markupsafe/
-- Issue Tracker: https://github.com/pallets/markupsafe/issues/
-- Chat: https://discord.gg/pallets
diff --git a/contrib/python/MarkupSafe/py3/markupsafe/__init__.py b/contrib/python/MarkupSafe/py3/markupsafe/__init__.py
index b40f24c66de..fee8dc7acca 100644
--- a/contrib/python/MarkupSafe/py3/markupsafe/__init__.py
+++ b/contrib/python/MarkupSafe/py3/markupsafe/__init__.py
@@ -1,29 +1,84 @@
-import functools
+from __future__ import annotations
+
+import collections.abc as cabc
import string
-import sys
import typing as t
+try:
+ from ._speedups import _escape_inner
+except ImportError:
+ from ._native import _escape_inner
+
if t.TYPE_CHECKING:
import typing_extensions as te
- class HasHTML(te.Protocol):
- def __html__(self) -> str:
- pass
- _P = te.ParamSpec("_P")
+class _HasHTML(t.Protocol):
+ def __html__(self, /) -> str: ...
+
+
+class _TPEscape(t.Protocol):
+ def __call__(self, s: t.Any, /) -> Markup: ...
+
+
+def escape(s: t.Any, /) -> Markup:
+ """Replace the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in
+ the string with HTML-safe sequences. Use this if you need to display
+ text that might contain such characters in HTML.
+
+ If the object has an ``__html__`` method, it is called and the
+ return value is assumed to already be safe for HTML.
+
+ :param s: An object to be converted to a string and escaped.
+ :return: A :class:`Markup` string with the escaped text.
+ """
+ # If the object is already a plain string, skip __html__ check and string
+ # conversion. This is the most common use case.
+ # Use type(s) instead of s.__class__ because a proxy object may be reporting
+ # the __class__ of the proxied value.
+ if type(s) is str:
+ return Markup(_escape_inner(s))
+
+ if hasattr(s, "__html__"):
+ return Markup(s.__html__())
+
+ return Markup(_escape_inner(str(s)))
+
+
+def escape_silent(s: t.Any | None, /) -> Markup:
+ """Like :func:`escape` but treats ``None`` as the empty string.
+ Useful with optional values, as otherwise you get the string
+ ``'None'`` when the value is ``None``.
+
+ >>> escape(None)
+ Markup('None')
+ >>> escape_silent(None)
+ Markup('')
+ """
+ if s is None:
+ return Markup()
+ return escape(s)
-__version__ = "2.1.5"
+def soft_str(s: t.Any, /) -> str:
+ """Convert an object to a string if it isn't already. This preserves
+ a :class:`Markup` string rather than converting it back to a basic
+ string, so it will still be marked as safe and won't be escaped
+ again.
-def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
- @functools.wraps(func)
- def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
- arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
- _escape_argspec(kwargs, kwargs.items(), self.escape)
- return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
+ >>> value = escape("<User 1>")
+ >>> value
+ Markup('&lt;User 1&gt;')
+ >>> escape(str(value))
+ Markup('&amp;lt;User 1&amp;gt;')
+ >>> escape(soft_str(value))
+ Markup('&lt;User 1&gt;')
+ """
+ if not isinstance(s, str):
+ return str(s)
- return wrapped # type: ignore[return-value]
+ return s
class Markup(str):
@@ -65,82 +120,72 @@ class Markup(str):
__slots__ = ()
def __new__(
- cls, base: t.Any = "", encoding: t.Optional[str] = None, errors: str = "strict"
- ) -> "te.Self":
- if hasattr(base, "__html__"):
- base = base.__html__()
+ cls, object: t.Any = "", encoding: str | None = None, errors: str = "strict"
+ ) -> te.Self:
+ if hasattr(object, "__html__"):
+ object = object.__html__()
if encoding is None:
- return super().__new__(cls, base)
+ return super().__new__(cls, object)
- return super().__new__(cls, base, encoding, errors)
+ return super().__new__(cls, object, encoding, errors)
- def __html__(self) -> "te.Self":
+ def __html__(self, /) -> te.Self:
return self
- def __add__(self, other: t.Union[str, "HasHTML"]) -> "te.Self":
- if isinstance(other, str) or hasattr(other, "__html__"):
- return self.__class__(super().__add__(self.escape(other)))
+ def __add__(self, value: str | _HasHTML, /) -> te.Self:
+ if isinstance(value, str) or hasattr(value, "__html__"):
+ return self.__class__(super().__add__(self.escape(value)))
return NotImplemented
- def __radd__(self, other: t.Union[str, "HasHTML"]) -> "te.Self":
- if isinstance(other, str) or hasattr(other, "__html__"):
- return self.escape(other).__add__(self)
+ def __radd__(self, value: str | _HasHTML, /) -> te.Self:
+ if isinstance(value, str) or hasattr(value, "__html__"):
+ return self.escape(value).__add__(self)
return NotImplemented
- def __mul__(self, num: "te.SupportsIndex") -> "te.Self":
- if isinstance(num, int):
- return self.__class__(super().__mul__(num))
+ def __mul__(self, value: t.SupportsIndex, /) -> te.Self:
+ return self.__class__(super().__mul__(value))
- return NotImplemented
-
- __rmul__ = __mul__
+ def __rmul__(self, value: t.SupportsIndex, /) -> te.Self:
+ return self.__class__(super().__mul__(value))
- def __mod__(self, arg: t.Any) -> "te.Self":
- if isinstance(arg, tuple):
+ def __mod__(self, value: t.Any, /) -> te.Self:
+ if isinstance(value, tuple):
# a tuple of arguments, each wrapped
- arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
- elif hasattr(type(arg), "__getitem__") and not isinstance(arg, str):
+ value = tuple(_MarkupEscapeHelper(x, self.escape) for x in value)
+ elif hasattr(type(value), "__getitem__") and not isinstance(value, str):
# a mapping of arguments, wrapped
- arg = _MarkupEscapeHelper(arg, self.escape)
+ value = _MarkupEscapeHelper(value, self.escape)
else:
# a single argument, wrapped with the helper and a tuple
- arg = (_MarkupEscapeHelper(arg, self.escape),)
+ value = (_MarkupEscapeHelper(value, self.escape),)
- return self.__class__(super().__mod__(arg))
+ return self.__class__(super().__mod__(value))
- def __repr__(self) -> str:
+ def __repr__(self, /) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
- def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "te.Self":
- return self.__class__(super().join(map(self.escape, seq)))
-
- join.__doc__ = str.join.__doc__
+ def join(self, iterable: cabc.Iterable[str | _HasHTML], /) -> te.Self:
+ return self.__class__(super().join(map(self.escape, iterable)))
def split( # type: ignore[override]
- self, sep: t.Optional[str] = None, maxsplit: int = -1
- ) -> t.List["te.Self"]:
+ self, /, sep: str | None = None, maxsplit: t.SupportsIndex = -1
+ ) -> list[te.Self]:
return [self.__class__(v) for v in super().split(sep, maxsplit)]
- split.__doc__ = str.split.__doc__
-
def rsplit( # type: ignore[override]
- self, sep: t.Optional[str] = None, maxsplit: int = -1
- ) -> t.List["te.Self"]:
+ self, /, sep: str | None = None, maxsplit: t.SupportsIndex = -1
+ ) -> list[te.Self]:
return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
- rsplit.__doc__ = str.rsplit.__doc__
-
def splitlines( # type: ignore[override]
- self, keepends: bool = False
- ) -> t.List["te.Self"]:
+ self, /, keepends: bool = False
+ ) -> list[te.Self]:
return [self.__class__(v) for v in super().splitlines(keepends)]
- splitlines.__doc__ = str.splitlines.__doc__
-
- def unescape(self) -> str:
+ def unescape(self, /) -> str:
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
@@ -151,7 +196,7 @@ class Markup(str):
return unescape(str(self))
- def striptags(self) -> str:
+ def striptags(self, /) -> str:
""":meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
@@ -163,31 +208,17 @@ class Markup(str):
# Look for comments then tags separately. Otherwise, a comment that
# contains a tag would end early, leaving some of the comment behind.
- while True:
- # keep finding comment start marks
- start = value.find("<!--")
-
- if start == -1:
- break
-
+ # keep finding comment start marks
+ while (start := value.find("<!--")) != -1:
# find a comment end mark beyond the start, otherwise stop
- end = value.find("-->", start)
-
- if end == -1:
+ if (end := value.find("-->", start)) == -1:
break
value = f"{value[:start]}{value[end + 3:]}"
# remove tags using the same method
- while True:
- start = value.find("<")
-
- if start == -1:
- break
-
- end = value.find(">", start)
-
- if end == -1:
+ while (start := value.find("<")) != -1:
+ if (end := value.find(">", start)) == -1:
break
value = f"{value[:start]}{value[end + 1:]}"
@@ -197,7 +228,7 @@ class Markup(str):
return self.__class__(value).unescape()
@classmethod
- def escape(cls, s: t.Any) -> "te.Self":
+ def escape(cls, s: t.Any, /) -> te.Self:
"""Escape a string. Calls :func:`escape` and ensures that for
subclasses the correct type is returned.
"""
@@ -208,49 +239,90 @@ class Markup(str):
return rv # type: ignore[return-value]
- __getitem__ = _simple_escaping_wrapper(str.__getitem__)
- capitalize = _simple_escaping_wrapper(str.capitalize)
- title = _simple_escaping_wrapper(str.title)
- lower = _simple_escaping_wrapper(str.lower)
- upper = _simple_escaping_wrapper(str.upper)
- replace = _simple_escaping_wrapper(str.replace)
- ljust = _simple_escaping_wrapper(str.ljust)
- rjust = _simple_escaping_wrapper(str.rjust)
- lstrip = _simple_escaping_wrapper(str.lstrip)
- rstrip = _simple_escaping_wrapper(str.rstrip)
- center = _simple_escaping_wrapper(str.center)
- strip = _simple_escaping_wrapper(str.strip)
- translate = _simple_escaping_wrapper(str.translate)
- expandtabs = _simple_escaping_wrapper(str.expandtabs)
- swapcase = _simple_escaping_wrapper(str.swapcase)
- zfill = _simple_escaping_wrapper(str.zfill)
- casefold = _simple_escaping_wrapper(str.casefold)
-
- if sys.version_info >= (3, 9):
- removeprefix = _simple_escaping_wrapper(str.removeprefix)
- removesuffix = _simple_escaping_wrapper(str.removesuffix)
-
- def partition(self, sep: str) -> t.Tuple["te.Self", "te.Self", "te.Self"]:
- l, s, r = super().partition(self.escape(sep))
+ def __getitem__(self, key: t.SupportsIndex | slice, /) -> te.Self:
+ return self.__class__(super().__getitem__(key))
+
+ def capitalize(self, /) -> te.Self:
+ return self.__class__(super().capitalize())
+
+ def title(self, /) -> te.Self:
+ return self.__class__(super().title())
+
+ def lower(self, /) -> te.Self:
+ return self.__class__(super().lower())
+
+ def upper(self, /) -> te.Self:
+ return self.__class__(super().upper())
+
+ def replace(self, old: str, new: str, count: t.SupportsIndex = -1, /) -> te.Self:
+ return self.__class__(super().replace(old, self.escape(new), count))
+
+ def ljust(self, width: t.SupportsIndex, fillchar: str = " ", /) -> te.Self:
+ return self.__class__(super().ljust(width, self.escape(fillchar)))
+
+ def rjust(self, width: t.SupportsIndex, fillchar: str = " ", /) -> te.Self:
+ return self.__class__(super().rjust(width, self.escape(fillchar)))
+
+ def lstrip(self, chars: str | None = None, /) -> te.Self:
+ return self.__class__(super().lstrip(chars))
+
+ def rstrip(self, chars: str | None = None, /) -> te.Self:
+ return self.__class__(super().rstrip(chars))
+
+ def center(self, width: t.SupportsIndex, fillchar: str = " ", /) -> te.Self:
+ return self.__class__(super().center(width, self.escape(fillchar)))
+
+ def strip(self, chars: str | None = None, /) -> te.Self:
+ return self.__class__(super().strip(chars))
+
+ def translate(
+ self,
+ table: cabc.Mapping[int, str | int | None], # type: ignore[override]
+ /,
+ ) -> str:
+ return self.__class__(super().translate(table))
+
+ def expandtabs(self, /, tabsize: t.SupportsIndex = 8) -> te.Self:
+ return self.__class__(super().expandtabs(tabsize))
+
+ def swapcase(self, /) -> te.Self:
+ return self.__class__(super().swapcase())
+
+ def zfill(self, width: t.SupportsIndex, /) -> te.Self:
+ return self.__class__(super().zfill(width))
+
+ def casefold(self, /) -> te.Self:
+ return self.__class__(super().casefold())
+
+ def removeprefix(self, prefix: str, /) -> te.Self:
+ return self.__class__(super().removeprefix(prefix))
+
+ def removesuffix(self, suffix: str) -> te.Self:
+ return self.__class__(super().removesuffix(suffix))
+
+ def partition(self, sep: str, /) -> tuple[te.Self, te.Self, te.Self]:
+ left, sep, right = super().partition(sep)
cls = self.__class__
- return cls(l), cls(s), cls(r)
+ return cls(left), cls(sep), cls(right)
- def rpartition(self, sep: str) -> t.Tuple["te.Self", "te.Self", "te.Self"]:
- l, s, r = super().rpartition(self.escape(sep))
+ def rpartition(self, sep: str, /) -> tuple[te.Self, te.Self, te.Self]:
+ left, sep, right = super().rpartition(sep)
cls = self.__class__
- return cls(l), cls(s), cls(r)
+ return cls(left), cls(sep), cls(right)
- def format(self, *args: t.Any, **kwargs: t.Any) -> "te.Self":
+ def format(self, *args: t.Any, **kwargs: t.Any) -> te.Self:
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, args, kwargs))
- def format_map( # type: ignore[override]
- self, map: t.Mapping[str, t.Any]
- ) -> "te.Self":
+ def format_map(
+ self,
+ mapping: cabc.Mapping[str, t.Any], # type: ignore[override]
+ /,
+ ) -> te.Self:
formatter = EscapeFormatter(self.escape)
- return self.__class__(formatter.vformat(self, (), map))
+ return self.__class__(formatter.vformat(self, (), mapping))
- def __html_format__(self, format_spec: str) -> "te.Self":
+ def __html_format__(self, format_spec: str, /) -> te.Self:
if format_spec:
raise ValueError("Unsupported format specification for Markup.")
@@ -260,8 +332,8 @@ class Markup(str):
class EscapeFormatter(string.Formatter):
__slots__ = ("escape",)
- def __init__(self, escape: t.Callable[[t.Any], Markup]) -> None:
- self.escape = escape
+ def __init__(self, escape: _TPEscape) -> None:
+ self.escape: _TPEscape = escape
super().__init__()
def format_field(self, value: t.Any, format_spec: str) -> str:
@@ -278,55 +350,46 @@ class EscapeFormatter(string.Formatter):
else:
# We need to make sure the format spec is str here as
# otherwise the wrong callback methods are invoked.
- rv = string.Formatter.format_field(self, value, str(format_spec))
+ rv = super().format_field(value, str(format_spec))
return str(self.escape(rv))
-_ListOrDict = t.TypeVar("_ListOrDict", list, dict)
-
-
-def _escape_argspec(
- obj: _ListOrDict, iterable: t.Iterable[t.Any], escape: t.Callable[[t.Any], Markup]
-) -> _ListOrDict:
- """Helper for various string-wrapped functions."""
- for key, value in iterable:
- if isinstance(value, str) or hasattr(value, "__html__"):
- obj[key] = escape(value)
-
- return obj
-
-
class _MarkupEscapeHelper:
"""Helper for :meth:`Markup.__mod__`."""
__slots__ = ("obj", "escape")
- def __init__(self, obj: t.Any, escape: t.Callable[[t.Any], Markup]) -> None:
- self.obj = obj
- self.escape = escape
+ def __init__(self, obj: t.Any, escape: _TPEscape) -> None:
+ self.obj: t.Any = obj
+ self.escape: _TPEscape = escape
- def __getitem__(self, item: t.Any) -> "te.Self":
- return self.__class__(self.obj[item], self.escape)
+ def __getitem__(self, key: t.Any, /) -> te.Self:
+ return self.__class__(self.obj[key], self.escape)
- def __str__(self) -> str:
+ def __str__(self, /) -> str:
return str(self.escape(self.obj))
- def __repr__(self) -> str:
+ def __repr__(self, /) -> str:
return str(self.escape(repr(self.obj)))
- def __int__(self) -> int:
+ def __int__(self, /) -> int:
return int(self.obj)
- def __float__(self) -> float:
+ def __float__(self, /) -> float:
return float(self.obj)
-# circular import
-try:
- from ._speedups import escape as escape
- from ._speedups import escape_silent as escape_silent
- from ._speedups import soft_str as soft_str
-except ImportError:
- from ._native import escape as escape
- from ._native import escape_silent as escape_silent # noqa: F401
- from ._native import soft_str as soft_str # noqa: F401
+def __getattr__(name: str) -> t.Any:
+ if name == "__version__":
+ import importlib.metadata
+ import warnings
+
+ warnings.warn(
+ "The '__version__' attribute is deprecated and will be removed in"
+ " MarkupSafe 3.1. Use feature detection, or"
+ ' `importlib.metadata.version("markupsafe")`, instead.',
+ stacklevel=2,
+ )
+ return importlib.metadata.version("markupsafe")
+
+ raise AttributeError(name)
diff --git a/contrib/python/MarkupSafe/py3/markupsafe/_native.py b/contrib/python/MarkupSafe/py3/markupsafe/_native.py
index 8117b2716d1..088b3bca983 100644
--- a/contrib/python/MarkupSafe/py3/markupsafe/_native.py
+++ b/contrib/python/MarkupSafe/py3/markupsafe/_native.py
@@ -1,63 +1,8 @@
-import typing as t
-
-from . import Markup
-
-
-def escape(s: t.Any) -> Markup:
- """Replace the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in
- the string with HTML-safe sequences. Use this if you need to display
- text that might contain such characters in HTML.
-
- If the object has an ``__html__`` method, it is called and the
- return value is assumed to already be safe for HTML.
-
- :param s: An object to be converted to a string and escaped.
- :return: A :class:`Markup` string with the escaped text.
- """
- if hasattr(s, "__html__"):
- return Markup(s.__html__())
-
- return Markup(
- str(s)
- .replace("&", "&amp;")
+def _escape_inner(s: str, /) -> str:
+ return (
+ s.replace("&", "&amp;")
.replace(">", "&gt;")
.replace("<", "&lt;")
.replace("'", "&#39;")
.replace('"', "&#34;")
)
-
-
-def escape_silent(s: t.Optional[t.Any]) -> Markup:
- """Like :func:`escape` but treats ``None`` as the empty string.
- Useful with optional values, as otherwise you get the string
- ``'None'`` when the value is ``None``.
-
- >>> escape(None)
- Markup('None')
- >>> escape_silent(None)
- Markup('')
- """
- if s is None:
- return Markup()
-
- return escape(s)
-
-
-def soft_str(s: t.Any) -> str:
- """Convert an object to a string if it isn't already. This preserves
- a :class:`Markup` string rather than converting it back to a basic
- string, so it will still be marked as safe and won't be escaped
- again.
-
- >>> value = escape("<User 1>")
- >>> value
- Markup('&lt;User 1&gt;')
- >>> escape(str(value))
- Markup('&amp;lt;User 1&amp;gt;')
- >>> escape(soft_str(value))
- Markup('&lt;User 1&gt;')
- """
- if not isinstance(s, str):
- return str(s)
-
- return s
diff --git a/contrib/python/MarkupSafe/py3/markupsafe/_speedups.c b/contrib/python/MarkupSafe/py3/markupsafe/_speedups.c
index 3c463fb82d5..73c2955827a 100644
--- a/contrib/python/MarkupSafe/py3/markupsafe/_speedups.c
+++ b/contrib/python/MarkupSafe/py3/markupsafe/_speedups.c
@@ -1,22 +1,5 @@
#include <Python.h>
-static PyObject* markup;
-
-static int
-init_constants(void)
-{
- PyObject *module;
-
- /* import markup type so that we can mark the return value */
- module = PyImport_ImportModule("markupsafe");
- if (!module)
- return 0;
- markup = PyObject_GetAttrString(module, "Markup");
- Py_DECREF(module);
-
- return 1;
-}
-
#define GET_DELTA(inp, inp_end, delta) \
while (inp < inp_end) { \
switch (*inp++) { \
@@ -166,135 +149,29 @@ escape_unicode_kind4(PyUnicodeObject *in)
}
static PyObject*
-escape_unicode(PyUnicodeObject *in)
+escape_unicode(PyObject *self, PyObject *s)
{
- if (PyUnicode_READY(in))
+ if (!PyUnicode_CheckExact(s))
+ return NULL;
+
+ // This check is no longer needed in Python 3.12.
+ if (PyUnicode_READY(s))
return NULL;
- switch (PyUnicode_KIND(in)) {
+ switch (PyUnicode_KIND(s)) {
case PyUnicode_1BYTE_KIND:
- return escape_unicode_kind1(in);
+ return escape_unicode_kind1((PyUnicodeObject*) s);
case PyUnicode_2BYTE_KIND:
- return escape_unicode_kind2(in);
+ return escape_unicode_kind2((PyUnicodeObject*) s);
case PyUnicode_4BYTE_KIND:
- return escape_unicode_kind4(in);
+ return escape_unicode_kind4((PyUnicodeObject*) s);
}
assert(0); /* shouldn't happen */
return NULL;
}
-static PyObject*
-escape(PyObject *self, PyObject *text)
-{
- static PyObject *id_html;
- PyObject *s = NULL, *rv = NULL, *html;
-
- if (id_html == NULL) {
- id_html = PyUnicode_InternFromString("__html__");
- if (id_html == NULL) {
- return NULL;
- }
- }
-
- /* we don't have to escape integers, bools or floats */
- if (PyLong_CheckExact(text) ||
- PyFloat_CheckExact(text) || PyBool_Check(text) ||
- text == Py_None)
- return PyObject_CallFunctionObjArgs(markup, text, NULL);
-
- /* if the object has an __html__ method that performs the escaping */
- html = PyObject_GetAttr(text ,id_html);
- if (html) {
- s = PyObject_CallObject(html, NULL);
- Py_DECREF(html);
- if (s == NULL) {
- return NULL;
- }
- /* Convert to Markup object */
- rv = PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL);
- Py_DECREF(s);
- return rv;
- }
-
- /* otherwise make the object unicode if it isn't, then escape */
- PyErr_Clear();
- if (!PyUnicode_Check(text)) {
- PyObject *unicode = PyObject_Str(text);
- if (!unicode)
- return NULL;
- s = escape_unicode((PyUnicodeObject*)unicode);
- Py_DECREF(unicode);
- }
- else
- s = escape_unicode((PyUnicodeObject*)text);
-
- /* convert the unicode string into a markup object. */
- rv = PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL);
- Py_DECREF(s);
- return rv;
-}
-
-
-static PyObject*
-escape_silent(PyObject *self, PyObject *text)
-{
- if (text != Py_None)
- return escape(self, text);
- return PyObject_CallFunctionObjArgs(markup, NULL);
-}
-
-
-static PyObject*
-soft_str(PyObject *self, PyObject *s)
-{
- if (!PyUnicode_Check(s))
- return PyObject_Str(s);
- Py_INCREF(s);
- return s;
-}
-
-
static PyMethodDef module_methods[] = {
- {
- "escape",
- (PyCFunction)escape,
- METH_O,
- "Replace the characters ``&``, ``<``, ``>``, ``'``, and ``\"`` in"
- " the string with HTML-safe sequences. Use this if you need to display"
- " text that might contain such characters in HTML.\n\n"
- "If the object has an ``__html__`` method, it is called and the"
- " return value is assumed to already be safe for HTML.\n\n"
- ":param s: An object to be converted to a string and escaped.\n"
- ":return: A :class:`Markup` string with the escaped text.\n"
- },
- {
- "escape_silent",
- (PyCFunction)escape_silent,
- METH_O,
- "Like :func:`escape` but treats ``None`` as the empty string."
- " Useful with optional values, as otherwise you get the string"
- " ``'None'`` when the value is ``None``.\n\n"
- ">>> escape(None)\n"
- "Markup('None')\n"
- ">>> escape_silent(None)\n"
- "Markup('')\n"
- },
- {
- "soft_str",
- (PyCFunction)soft_str,
- METH_O,
- "Convert an object to a string if it isn't already. This preserves"
- " a :class:`Markup` string rather than converting it back to a basic"
- " string, so it will still be marked as safe and won't be escaped"
- " again.\n\n"
- ">>> value = escape(\"<User 1>\")\n"
- ">>> value\n"
- "Markup('&lt;User 1&gt;')\n"
- ">>> escape(str(value))\n"
- "Markup('&amp;lt;User 1&amp;gt;')\n"
- ">>> escape(soft_str(value))\n"
- "Markup('&lt;User 1&gt;')\n"
- },
+ {"_escape_inner", (PyCFunction)escape_unicode, METH_O, NULL},
{NULL, NULL, 0, NULL} /* Sentinel */
};
@@ -313,8 +190,15 @@ static struct PyModuleDef module_definition = {
PyMODINIT_FUNC
PyInit__speedups(void)
{
- if (!init_constants())
+ PyObject *m = PyModule_Create(&module_definition);
+
+ if (m == NULL) {
return NULL;
+ }
+
+ #ifdef Py_GIL_DISABLED
+ PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
+ #endif
- return PyModule_Create(&module_definition);
+ return m;
}
diff --git a/contrib/python/MarkupSafe/py3/markupsafe/_speedups.pyi b/contrib/python/MarkupSafe/py3/markupsafe/_speedups.pyi
index f673240f6d2..8c8885852a2 100644
--- a/contrib/python/MarkupSafe/py3/markupsafe/_speedups.pyi
+++ b/contrib/python/MarkupSafe/py3/markupsafe/_speedups.pyi
@@ -1,9 +1 @@
-from typing import Any
-from typing import Optional
-
-from . import Markup
-
-def escape(s: Any) -> Markup: ...
-def escape_silent(s: Optional[Any]) -> Markup: ...
-def soft_str(s: Any) -> str: ...
-def soft_unicode(s: Any) -> str: ...
+def _escape_inner(s: str, /) -> str: ...
diff --git a/contrib/python/MarkupSafe/py3/tests/__init__.py b/contrib/python/MarkupSafe/py3/tests/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
--- /dev/null
+++ b/contrib/python/MarkupSafe/py3/tests/__init__.py
diff --git a/contrib/python/MarkupSafe/py3/tests/conftest.py b/contrib/python/MarkupSafe/py3/tests/conftest.py
index d040ea8b1c6..d941970b8e9 100644
--- a/contrib/python/MarkupSafe/py3/tests/conftest.py
+++ b/contrib/python/MarkupSafe/py3/tests/conftest.py
@@ -1,5 +1,12 @@
+from __future__ import annotations
+
+import sys
+import typing as t
+from types import ModuleType
+
import pytest
+import markupsafe
from markupsafe import _native
try:
@@ -8,8 +15,17 @@ except ImportError:
_speedups = None # type: ignore
+def pytest_report_header() -> list[str]:
+ """Return a list of strings to be displayed in the header of the report."""
+ if sys.version_info >= (3, 13):
+ return [f"Free-threaded: {not sys._is_gil_enabled()}"]
+
+ return []
+
+
@pytest.fixture(
scope="session",
+ autouse=True,
params=(
_native,
pytest.param(
@@ -18,20 +34,6 @@ except ImportError:
),
),
)
-def _mod(request):
- return request.param
-
-
-@pytest.fixture(scope="session")
-def escape(_mod):
- return _mod.escape
-
-
-@pytest.fixture(scope="session")
-def escape_silent(_mod):
- return _mod.escape_silent
-
-
-@pytest.fixture(scope="session")
-def soft_str(_mod):
- return _mod.soft_str
+def _mod(request: pytest.FixtureRequest) -> None:
+ mod = t.cast(ModuleType, request.param)
+ markupsafe._escape_inner = mod._escape_inner # type: ignore[attr-defined]
diff --git a/contrib/python/MarkupSafe/py3/tests/test_escape.py b/contrib/python/MarkupSafe/py3/tests/test_escape.py
index bf53facedda..03e0b64892f 100644
--- a/contrib/python/MarkupSafe/py3/tests/test_escape.py
+++ b/contrib/python/MarkupSafe/py3/tests/test_escape.py
@@ -1,5 +1,8 @@
+from __future__ import annotations
+
import pytest
+from markupsafe import escape
from markupsafe import Markup
@@ -18,12 +21,12 @@ from markupsafe import Markup
("こんにちは&><'\"", "こんにちは&amp;&gt;&lt;&#39;&#34;"),
# 4 byte
(
- "\U0001F363\U0001F362&><'\"\U0001F37A xyz",
- "\U0001F363\U0001F362&amp;&gt;&lt;&#39;&#34;\U0001F37A xyz",
+ "\U0001f363\U0001f362&><'\"\U0001f37a xyz",
+ "\U0001f363\U0001f362&amp;&gt;&lt;&#39;&#34;\U0001f37a xyz",
),
- ("&><'\"\U0001F37A xyz", "&amp;&gt;&lt;&#39;&#34;\U0001F37A xyz"),
- ("\U0001F363\U0001F362&><'\"", "\U0001F363\U0001F362&amp;&gt;&lt;&#39;&#34;"),
+ ("&><'\"\U0001f37a xyz", "&amp;&gt;&lt;&#39;&#34;\U0001f37a xyz"),
+ ("\U0001f363\U0001f362&><'\"", "\U0001f363\U0001f362&amp;&gt;&lt;&#39;&#34;"),
),
)
-def test_escape(escape, value, expect):
+def test_escape(value: str, expect: str) -> None:
assert escape(value) == Markup(expect)
diff --git a/contrib/python/MarkupSafe/py3/tests/test_exception_custom_html.py b/contrib/python/MarkupSafe/py3/tests/test_exception_custom_html.py
index ec2f10b1d19..582c7491367 100644
--- a/contrib/python/MarkupSafe/py3/tests/test_exception_custom_html.py
+++ b/contrib/python/MarkupSafe/py3/tests/test_exception_custom_html.py
@@ -1,12 +1,16 @@
+from __future__ import annotations
+
import pytest
+from markupsafe import escape
+
class CustomHtmlThatRaises:
- def __html__(self):
+ def __html__(self) -> str:
raise ValueError(123)
-def test_exception_custom_html(escape):
+def test_exception_custom_html() -> None:
"""Checks whether exceptions in custom __html__ implementations are
propagated correctly.
@@ -14,5 +18,6 @@ def test_exception_custom_html(escape):
https://github.com/pallets/markupsafe/issues/108
"""
obj = CustomHtmlThatRaises()
+
with pytest.raises(ValueError):
escape(obj)
diff --git a/contrib/python/MarkupSafe/py3/tests/test_leak.py b/contrib/python/MarkupSafe/py3/tests/test_leak.py
index 55b10b98a42..b786e0725de 100644
--- a/contrib/python/MarkupSafe/py3/tests/test_leak.py
+++ b/contrib/python/MarkupSafe/py3/tests/test_leak.py
@@ -1,28 +1,25 @@
-import gc
-import platform
+from __future__ import annotations
-import pytest
+import gc
from markupsafe import escape
-@pytest.mark.skipif(
- escape.__module__ == "markupsafe._native",
- reason="only test memory leak with speedups",
-)
-def test_markup_leaks():
+def test_markup_leaks() -> None:
counts = set()
+ # Try to start with a "clean" count. Works for PyPy but not 3.13 JIT.
+ gc.collect()
- for _i in range(20):
- for _j in range(1000):
+ for _ in range(20):
+ for _ in range(1000):
escape("foo")
escape("<foo>")
escape("foo")
escape("<foo>")
- if platform.python_implementation() == "PyPy":
- gc.collect()
-
counts.add(len(gc.get_objects()))
- assert len(counts) == 1
+ # Some implementations, such as PyPy and Python 3.13 JIT, end up with 2
+ # counts rather than one. Presumably this is internals stabilizing. A leak
+ # would presumably have a different count every loop.
+ assert len(counts) < 3
diff --git a/contrib/python/MarkupSafe/py3/tests/test_markupsafe.py b/contrib/python/MarkupSafe/py3/tests/test_markupsafe.py
index 94bea387954..85d9ea16be7 100644
--- a/contrib/python/MarkupSafe/py3/tests/test_markupsafe.py
+++ b/contrib/python/MarkupSafe/py3/tests/test_markupsafe.py
@@ -1,9 +1,16 @@
+from __future__ import annotations
+
+import typing as t
+
import pytest
+from markupsafe import escape
+from markupsafe import escape_silent
from markupsafe import Markup
+from markupsafe import soft_str
-def test_adding(escape):
+def test_adding() -> None:
unsafe = '<script type="application/x-some-script">alert("foo");</script>'
safe = Markup("<em>username</em>")
assert unsafe + safe == str(escape(unsafe)) + str(safe)
@@ -22,22 +29,22 @@ def test_adding(escape):
("%.2f", 3.14, "3.14"),
),
)
-def test_string_interpolation(template, data, expect):
+def test_string_interpolation(template: str, data: t.Any, expect: str) -> None:
assert Markup(template) % data == expect
-def test_type_behavior():
+def test_type_behavior() -> None:
assert type(Markup("foo") + "bar") is Markup
x = Markup("foo")
assert x.__html__() is x
-def test_html_interop():
+def test_html_interop() -> None:
class Foo:
- def __html__(self):
+ def __html__(self) -> str:
return "<em>awesome</em>"
- def __str__(self):
+ def __str__(self) -> str:
return "awesome"
assert Markup(Foo()) == "<em>awesome</em>"
@@ -46,18 +53,18 @@ def test_html_interop():
@pytest.mark.parametrize("args", ["foo", 42, ("foo", 42)])
-def test_missing_interpol(args):
+def test_missing_interpol(args: t.Any) -> None:
with pytest.raises(TypeError):
- Markup("<em></em>") % args
+ assert Markup("<em></em>") % args
-def test_tuple_interpol():
+def test_tuple_interpol() -> None:
result = Markup("<em>%s:%s</em>") % ("<foo>", "<bar>")
expect = Markup("<em>&lt;foo&gt;:&lt;bar&gt;</em>")
assert result == expect
-def test_dict_interpol():
+def test_dict_interpol() -> None:
result = Markup("<em>%(foo)s</em>") % {"foo": "<foo>"}
expect = Markup("<em>&lt;foo&gt;</em>")
assert result == expect
@@ -67,7 +74,7 @@ def test_dict_interpol():
assert result == expect
-def test_escaping(escape):
+def test_escaping() -> None:
assert escape("\"<>&'") == "&#34;&lt;&gt;&amp;&#39;"
assert (
Markup(
@@ -82,7 +89,7 @@ def test_escaping(escape):
)
-def test_unescape():
+def test_unescape() -> None:
assert Markup("&lt;test&gt;").unescape() == "<test>"
result = Markup("jack & tavi are cooler than mike &amp; russ").unescape()
@@ -97,7 +104,7 @@ def test_unescape():
assert twice == expect
-def test_format():
+def test_format() -> None:
result = Markup("<em>{awesome}</em>").format(awesome="<awesome>")
assert result == "<em>&lt;awesome&gt;</em>"
@@ -108,39 +115,39 @@ def test_format():
assert result == "<bar/>"
-def test_format_map():
+def test_format_map() -> None:
result = Markup("<em>{value}</em>").format_map({"value": "<value>"})
assert result == "<em>&lt;value&gt;</em>"
-def test_formatting_empty():
+def test_formatting_empty() -> None:
formatted = Markup("{}").format(0)
assert formatted == Markup("0")
-def test_custom_formatting():
+def test_custom_formatting() -> None:
class HasHTMLOnly:
- def __html__(self):
+ def __html__(self) -> Markup:
return Markup("<foo>")
class HasHTMLAndFormat:
- def __html__(self):
+ def __html__(self) -> Markup:
return Markup("<foo>")
- def __html_format__(self, spec):
+ def __html_format__(self, spec: str) -> Markup:
return Markup("<FORMAT>")
assert Markup("{0}").format(HasHTMLOnly()) == Markup("<foo>")
assert Markup("{0}").format(HasHTMLAndFormat()) == Markup("<FORMAT>")
-def test_complex_custom_formatting():
+def test_complex_custom_formatting() -> None:
class User:
- def __init__(self, id, username):
+ def __init__(self, id: int, username: str) -> None:
self.id = id
self.username = username
- def __html_format__(self, format_spec):
+ def __html_format__(self, format_spec: str) -> Markup:
if format_spec == "link":
return Markup('<a href="/user/{0}">{1}</a>').format(
self.id, self.__html__()
@@ -150,7 +157,7 @@ def test_complex_custom_formatting():
return self.__html__()
- def __html__(self):
+ def __html__(self) -> Markup:
return Markup("<span class=user>{0}</span>").format(self.username)
user = User(1, "foo")
@@ -159,43 +166,43 @@ def test_complex_custom_formatting():
assert result == expect
-def test_formatting_with_objects():
+def test_formatting_with_objects() -> None:
class Stringable:
- def __str__(self):
+ def __str__(self) -> str:
return "строка"
assert Markup("{s}").format(s=Stringable()) == Markup("строка")
-def test_escape_silent(escape, escape_silent):
+def test_escape_silent() -> None:
assert escape_silent(None) == Markup()
assert escape(None) == Markup(None)
assert escape_silent("<foo>") == Markup("&lt;foo&gt;")
-def test_splitting():
+def test_splitting() -> None:
expect = [Markup("a"), Markup("b")]
assert Markup("a b").split() == expect
assert Markup("a b").rsplit() == expect
assert Markup("a\nb").splitlines() == expect
-def test_mul():
+def test_mul() -> None:
assert Markup("a") * 3 == Markup("aaa")
-def test_escape_return_type(escape):
+def test_escape_return_type() -> None:
assert isinstance(escape("a"), Markup)
assert isinstance(escape(Markup("a")), Markup)
class Foo:
- def __html__(self):
+ def __html__(self) -> str:
return "<strong>Foo</strong>"
assert isinstance(escape(Foo()), Markup)
-def test_soft_str(soft_str):
- assert type(soft_str("")) is str
- assert type(soft_str(Markup())) is Markup
- assert type(soft_str(15)) is str
+def test_soft_str() -> None:
+ assert type(soft_str("")) is str # noqa: E721
+ assert type(soft_str(Markup())) is Markup # noqa: E721
+ assert type(soft_str(15)) is str # noqa: E721
diff --git a/contrib/python/MarkupSafe/py3/ya.make b/contrib/python/MarkupSafe/py3/ya.make
index f1664c93e8f..7b942e706ab 100644
--- a/contrib/python/MarkupSafe/py3/ya.make
+++ b/contrib/python/MarkupSafe/py3/ya.make
@@ -2,7 +2,7 @@
PY3_LIBRARY()
-VERSION(2.1.5)
+VERSION(3.0.1)
LICENSE(BSD-3-Clause)
diff --git a/contrib/python/anyio/.dist-info/METADATA b/contrib/python/anyio/.dist-info/METADATA
index 747e994c6be..e28bbd52d06 100644
--- a/contrib/python/anyio/.dist-info/METADATA
+++ b/contrib/python/anyio/.dist-info/METADATA
@@ -1,6 +1,6 @@
Metadata-Version: 2.1
Name: anyio
-Version: 4.6.0
+Version: 4.6.2
Summary: High level compatibility layer for multiple asynchronous event loop implementations
Author-email: Alex Grönholm <alex.gronholm@nextday.fi>
License: MIT
@@ -15,12 +15,13 @@ Classifier: Framework :: AnyIO
Classifier: Typing :: Typed
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
-Requires-Python: >=3.9
+Requires-Python: >=3.8
Description-Content-Type: text/x-rst
License-File: LICENSE
Requires-Dist: idna >=2.8
@@ -42,6 +43,7 @@ Requires-Dist: pytest >=7.0 ; extra == 'test'
Requires-Dist: pytest-mock >=3.6.1 ; extra == 'test'
Requires-Dist: trustme ; extra == 'test'
Requires-Dist: uvloop >=0.21.0b1 ; (platform_python_implementation == "CPython" and platform_system != "Windows") and extra == 'test'
+Requires-Dist: truststore >=0.9.1 ; (python_version >= "3.10") and extra == 'test'
Provides-Extra: trio
Requires-Dist: trio >=0.26.1 ; extra == 'trio'
diff --git a/contrib/python/anyio/anyio/_backends/_asyncio.py b/contrib/python/anyio/anyio/_backends/_asyncio.py
index 9342fab8181..fa5349a8c23 100644
--- a/contrib/python/anyio/anyio/_backends/_asyncio.py
+++ b/contrib/python/anyio/anyio/_backends/_asyncio.py
@@ -20,18 +20,9 @@ from asyncio import (
)
from asyncio.base_events import _run_until_complete_cb # type: ignore[attr-defined]
from collections import OrderedDict, deque
-from collections.abc import (
- AsyncGenerator,
- AsyncIterator,
- Awaitable,
- Callable,
- Collection,
- Coroutine,
- Iterable,
- Sequence,
-)
+from collections.abc import AsyncIterator, Iterable
from concurrent.futures import Future
-from contextlib import AbstractContextManager, suppress
+from contextlib import suppress
from contextvars import Context, copy_context
from dataclasses import dataclass
from functools import partial, wraps
@@ -51,7 +42,15 @@ from types import TracebackType
from typing import (
IO,
Any,
+ AsyncGenerator,
+ Awaitable,
+ Callable,
+ Collection,
+ ContextManager,
+ Coroutine,
Optional,
+ Sequence,
+ Tuple,
TypeVar,
cast,
)
@@ -359,14 +358,6 @@ def _task_started(task: asyncio.Task) -> bool:
#
-def is_anyio_cancellation(exc: CancelledError) -> bool:
- return (
- bool(exc.args)
- and isinstance(exc.args[0], str)
- and exc.args[0].startswith("Cancelled by cancel scope ")
- )
-
-
class CancelScope(BaseCancelScope):
def __new__(
cls, *, deadline: float = math.inf, shield: bool = False
@@ -453,77 +444,35 @@ class CancelScope(BaseCancelScope):
host_task_state.cancel_scope = self._parent_scope
- # Undo all cancellations done by this scope
- if self._cancelling is not None:
- while self._cancel_calls:
- self._cancel_calls -= 1
- if self._host_task.uncancel() <= self._cancelling:
- break
-
- # We only swallow the exception iff it was an AnyIO CancelledError, either
- # directly as exc_val or inside an exception group and there are no cancelled
- # parent cancel scopes visible to us here
- not_swallowed_exceptions = 0
- swallow_exception = False
- if exc_val is not None:
- for exc in iterate_exceptions(exc_val):
- if self._cancel_called and isinstance(exc, CancelledError):
- if not (swallow_exception := self._uncancel(exc)):
- not_swallowed_exceptions += 1
- else:
- not_swallowed_exceptions += 1
-
- # Restart the cancellation effort in the closest visible, cancelled parent
- # scope if necessary
+ # Restart the cancellation effort in the closest directly cancelled parent
+ # scope if this one was shielded
self._restart_cancellation_in_parent()
- return swallow_exception and not not_swallowed_exceptions
- @property
- def _effectively_cancelled(self) -> bool:
- cancel_scope: CancelScope | None = self
- while cancel_scope is not None:
- if cancel_scope._cancel_called:
- return True
-
- if cancel_scope.shield:
- return False
-
- cancel_scope = cancel_scope._parent_scope
+ if self._cancel_called and exc_val is not None:
+ for exc in iterate_exceptions(exc_val):
+ if isinstance(exc, CancelledError):
+ self._cancelled_caught = self._uncancel(exc)
+ if self._cancelled_caught:
+ break
- return False
+ return self._cancelled_caught
- @property
- def _parent_cancellation_is_visible_to_us(self) -> bool:
- return (
- self._parent_scope is not None
- and not self.shield
- and self._parent_scope._effectively_cancelled
- )
+ return None
def _uncancel(self, cancelled_exc: CancelledError) -> bool:
- if self._host_task is None:
+ if sys.version_info < (3, 9) or self._host_task is None:
self._cancel_calls = 0
return True
- while True:
- if is_anyio_cancellation(cancelled_exc):
- # Only swallow the cancellation exception if it's an AnyIO cancel
- # exception and there are no other cancel scopes down the line pending
- # cancellation
- self._cancelled_caught = (
- self._effectively_cancelled
- and not self._parent_cancellation_is_visible_to_us
- )
- return self._cancelled_caught
-
- # Sometimes third party frameworks catch a CancelledError and raise a new
- # one, so as a workaround we have to look at the previous ones in
- # __context__ too for a matching cancel message
- if isinstance(cancelled_exc.__context__, CancelledError):
- cancelled_exc = cancelled_exc.__context__
- continue
+ # Undo all cancellations done by this scope
+ if self._cancelling is not None:
+ while self._cancel_calls:
+ self._cancel_calls -= 1
+ if self._host_task.uncancel() <= self._cancelling:
+ return True
- return False
+ self._cancel_calls = 0
+ return f"Cancelled by cancel scope {id(self):x}" in cancelled_exc.args
def _timeout(self) -> None:
if self._deadline != math.inf:
@@ -547,17 +496,19 @@ class CancelScope(BaseCancelScope):
should_retry = False
current = current_task()
for task in self._tasks:
- should_retry = True
if task._must_cancel: # type: ignore[attr-defined]
continue
# The task is eligible for cancellation if it has started
+ should_retry = True
if task is not current and (task is self._host_task or _task_started(task)):
waiter = task._fut_waiter # type: ignore[attr-defined]
if not isinstance(waiter, asyncio.Future) or not waiter.done():
- task.cancel(f"Cancelled by cancel scope {id(origin):x}")
- if task is origin._host_task:
- origin._cancel_calls += 1
+ origin._cancel_calls += 1
+ if sys.version_info >= (3, 9):
+ task.cancel(f"Cancelled by cancel scope {id(origin):x}")
+ else:
+ task.cancel()
# Deliver cancellation to child scopes that aren't shielded or running their own
# cancellation callbacks
@@ -595,6 +546,17 @@ class CancelScope(BaseCancelScope):
scope = scope._parent_scope
+ def _parent_cancelled(self) -> bool:
+ # Check whether any parent has been cancelled
+ cancel_scope = self._parent_scope
+ while cancel_scope is not None and not cancel_scope._shield:
+ if cancel_scope._cancel_called:
+ return True
+ else:
+ cancel_scope = cancel_scope._parent_scope
+
+ return False
+
def cancel(self) -> None:
if not self._cancel_called:
if self._timeout_handle:
@@ -701,50 +663,38 @@ class TaskGroup(abc.TaskGroup):
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> bool | None:
+ ignore_exception = self.cancel_scope.__exit__(exc_type, exc_val, exc_tb)
if exc_val is not None:
self.cancel_scope.cancel()
if not isinstance(exc_val, CancelledError):
self._exceptions.append(exc_val)
- try:
- if self._tasks:
- with CancelScope() as wait_scope:
- while self._tasks:
- try:
- await asyncio.wait(self._tasks)
- except CancelledError as exc:
- # Shield the scope against further cancellation attempts,
- # as they're not productive (#695)
- wait_scope.shield = True
- self.cancel_scope.cancel()
-
- # Set exc_val from the cancellation exception if it was
- # previously unset. However, we should not replace a native
- # cancellation exception with one raise by a cancel scope.
- if exc_val is None or (
- isinstance(exc_val, CancelledError)
- and not is_anyio_cancellation(exc)
- ):
- exc_val = exc
- else:
- # If there are no child tasks to wait on, run at least one checkpoint
- # anyway
- await AsyncIOBackend.cancel_shielded_checkpoint()
+ cancelled_exc_while_waiting_tasks: CancelledError | None = None
+ while self._tasks:
+ try:
+ await asyncio.wait(self._tasks)
+ except CancelledError as exc:
+ # This task was cancelled natively; reraise the CancelledError later
+ # unless this task was already interrupted by another exception
+ self.cancel_scope.cancel()
+ if cancelled_exc_while_waiting_tasks is None:
+ cancelled_exc_while_waiting_tasks = exc
- self._active = False
- if self._exceptions:
- raise BaseExceptionGroup(
- "unhandled errors in a TaskGroup", self._exceptions
- )
- elif exc_val:
- raise exc_val
- except BaseException as exc:
- if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__):
- return True
+ self._active = False
+ if self._exceptions:
+ raise BaseExceptionGroup(
+ "unhandled errors in a TaskGroup", self._exceptions
+ )
- raise
+ # Raise the CancelledError received while waiting for child tasks to exit,
+ # unless the context manager itself was previously exited with another
+ # exception, or if any of the child tasks raised an exception other than
+ # CancelledError
+ if cancelled_exc_while_waiting_tasks:
+ if exc_val is None or ignore_exception:
+ raise cancelled_exc_while_waiting_tasks
- return self.cancel_scope.__exit__(exc_type, exc_val, exc_tb)
+ return ignore_exception
def _spawn(
self,
@@ -780,7 +730,7 @@ class TaskGroup(abc.TaskGroup):
if not isinstance(exc, CancelledError):
self._exceptions.append(exc)
- if not self.cancel_scope._effectively_cancelled:
+ if not self.cancel_scope._parent_cancelled():
self.cancel_scope.cancel()
else:
task_status_future.set_exception(exc)
@@ -856,7 +806,7 @@ class TaskGroup(abc.TaskGroup):
# Threads
#
-_Retval_Queue_Type = tuple[Optional[T_Retval], Optional[BaseException]]
+_Retval_Queue_Type = Tuple[Optional[T_Retval], Optional[BaseException]]
class WorkerThread(Thread):
@@ -1005,7 +955,7 @@ class Process(abc.Process):
_stderr: StreamReaderWrapper | None
async def aclose(self) -> None:
- with CancelScope(shield=True) as scope:
+ with CancelScope(shield=True):
if self._stdin:
await self._stdin.aclose()
if self._stdout:
@@ -1013,14 +963,14 @@ class Process(abc.Process):
if self._stderr:
await self._stderr.aclose()
- scope.shield = False
- try:
- await self.wait()
- except BaseException:
- scope.shield = True
- self.kill()
+ try:
+ await self.wait()
+ except BaseException:
+ self.kill()
+ with CancelScope(shield=True):
await self.wait()
- raise
+
+ raise
async def wait(self) -> int:
return await self._process.wait()
@@ -1731,9 +1681,10 @@ class Lock(BaseLock):
self._waiters: deque[tuple[asyncio.Task, asyncio.Future]] = deque()
async def acquire(self) -> None:
+ task = cast(asyncio.Task, current_task())
if self._owner_task is None and not self._waiters:
await AsyncIOBackend.checkpoint_if_cancelled()
- self._owner_task = current_task()
+ self._owner_task = task
# Unless on the "fast path", yield control of the event loop so that other
# tasks can run too
@@ -1746,7 +1697,9 @@ class Lock(BaseLock):
return
- task = cast(asyncio.Task, current_task())
+ if self._owner_task == task:
+ raise RuntimeError("Attempted to acquire an already held Lock")
+
fut: asyncio.Future[None] = asyncio.Future()
item = task, fut
self._waiters.append(item)
@@ -1762,10 +1715,14 @@ class Lock(BaseLock):
self._waiters.remove(item)
def acquire_nowait(self) -> None:
+ task = cast(asyncio.Task, current_task())
if self._owner_task is None and not self._waiters:
- self._owner_task = current_task()
+ self._owner_task = task
return
+ if self._owner_task is task:
+ raise RuntimeError("Attempted to acquire an already held Lock")
+
raise WouldBlock
def locked(self) -> bool:
@@ -2065,7 +2022,9 @@ class AsyncIOTaskInfo(TaskInfo):
if task_state := _task_states.get(task):
if cancel_scope := task_state.cancel_scope:
- return cancel_scope._effectively_cancelled
+ return cancel_scope.cancel_called or (
+ not cancel_scope.shield and cancel_scope._parent_cancelled()
+ )
return False
@@ -2159,7 +2118,7 @@ class TestRunner(abc.TestRunner):
) -> T_Retval:
if not self._runner_task:
self._send_stream, receive_stream = create_memory_object_stream[
- tuple[Awaitable[Any], asyncio.Future]
+ Tuple[Awaitable[Any], asyncio.Future]
](1)
self._runner_task = self.get_loop().create_task(
self._run_tests_and_fixtures(receive_stream)
@@ -2521,7 +2480,7 @@ class AsyncIOBackend(AsyncBackend):
cls, host: str, port: int, local_address: IPSockAddrType | None = None
) -> abc.SocketStream:
transport, protocol = cast(
- tuple[asyncio.Transport, StreamProtocol],
+ Tuple[asyncio.Transport, StreamProtocol],
await get_running_loop().create_connection(
StreamProtocol, host, port, local_addr=local_address
),
@@ -2700,7 +2659,7 @@ class AsyncIOBackend(AsyncBackend):
@classmethod
def open_signal_receiver(
cls, *signals: Signals
- ) -> AbstractContextManager[AsyncIterator[Signals]]:
+ ) -> ContextManager[AsyncIterator[Signals]]:
return _SignalReceiver(signals)
@classmethod
diff --git a/contrib/python/anyio/anyio/_backends/_trio.py b/contrib/python/anyio/anyio/_backends/_trio.py
index de2189ce78d..aee974deb66 100644
--- a/contrib/python/anyio/anyio/_backends/_trio.py
+++ b/contrib/python/anyio/anyio/_backends/_trio.py
@@ -7,18 +7,8 @@ import socket
import sys
import types
import weakref
-from collections.abc import (
- AsyncGenerator,
- AsyncIterator,
- Awaitable,
- Callable,
- Collection,
- Coroutine,
- Iterable,
- Sequence,
-)
+from collections.abc import AsyncIterator, Iterable
from concurrent.futures import Future
-from contextlib import AbstractContextManager
from dataclasses import dataclass
from functools import partial
from io import IOBase
@@ -29,8 +19,15 @@ from types import TracebackType
from typing import (
IO,
Any,
+ AsyncGenerator,
+ Awaitable,
+ Callable,
+ Collection,
+ ContextManager,
+ Coroutine,
Generic,
NoReturn,
+ Sequence,
TypeVar,
cast,
overload,
@@ -662,9 +659,19 @@ class Lock(BaseLock):
self._fast_acquire = fast_acquire
self.__original = trio.Lock()
+ @staticmethod
+ def _convert_runtime_error_msg(exc: RuntimeError) -> None:
+ if exc.args == ("attempt to re-acquire an already held Lock",):
+ exc.args = ("Attempted to acquire an already held Lock",)
+
async def acquire(self) -> None:
if not self._fast_acquire:
- await self.__original.acquire()
+ try:
+ await self.__original.acquire()
+ except RuntimeError as exc:
+ self._convert_runtime_error_msg(exc)
+ raise
+
return
# This is the "fast path" where we don't let other tasks run
@@ -673,12 +680,18 @@ class Lock(BaseLock):
self.__original.acquire_nowait()
except trio.WouldBlock:
await self.__original._lot.park()
+ except RuntimeError as exc:
+ self._convert_runtime_error_msg(exc)
+ raise
def acquire_nowait(self) -> None:
try:
self.__original.acquire_nowait()
except trio.WouldBlock:
raise WouldBlock from None
+ except RuntimeError as exc:
+ self._convert_runtime_error_msg(exc)
+ raise
def locked(self) -> bool:
return self.__original.locked()
@@ -1276,7 +1289,7 @@ class TrioBackend(AsyncBackend):
@classmethod
def open_signal_receiver(
cls, *signals: Signals
- ) -> AbstractContextManager[AsyncIterator[Signals]]:
+ ) -> ContextManager[AsyncIterator[Signals]]:
return _SignalReceiver(signals)
@classmethod
diff --git a/contrib/python/anyio/anyio/_core/_fileio.py b/contrib/python/anyio/anyio/_core/_fileio.py
index 23ccb0d66f5..214a90bfd84 100644
--- a/contrib/python/anyio/anyio/_core/_fileio.py
+++ b/contrib/python/anyio/anyio/_core/_fileio.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import os
import pathlib
import sys
-from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Sequence
+from collections.abc import Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass
from functools import partial
from os import PathLike
@@ -12,6 +12,7 @@ from typing import (
TYPE_CHECKING,
Any,
AnyStr,
+ AsyncIterator,
Final,
Generic,
overload,
@@ -217,6 +218,18 @@ class Path:
It implements the Python 3.10 version of :class:`pathlib.Path` interface, except for
the deprecated :meth:`~pathlib.Path.link_to` method.
+ Some methods may be unavailable or have limited functionality, based on the Python
+ version:
+
+ * :meth:`~pathlib.Path.from_uri` (available on Python 3.13 or later)
+ * :meth:`~pathlib.Path.full_match` (available on Python 3.13 or later)
+ * :meth:`~pathlib.Path.is_junction` (available on Python 3.12 or later)
+ * :meth:`~pathlib.Path.match` (the ``case_sensitive`` paramater is only available on
+ Python 3.13 or later)
+ * :meth:`~pathlib.Path.relative_to` (the ``walk_up`` parameter is only available on
+ Python 3.12 or later)
+ * :meth:`~pathlib.Path.walk` (available on Python 3.12 or later)
+
Any methods that do disk I/O need to be awaited on. These methods are:
* :meth:`~pathlib.Path.absolute`
@@ -232,7 +245,10 @@ class Path:
* :meth:`~pathlib.Path.is_dir`
* :meth:`~pathlib.Path.is_fifo`
* :meth:`~pathlib.Path.is_file`
+ * :meth:`~pathlib.Path.is_junction`
* :meth:`~pathlib.Path.is_mount`
+ * :meth:`~pathlib.Path.is_socket`
+ * :meth:`~pathlib.Path.is_symlink`
* :meth:`~pathlib.Path.lchmod`
* :meth:`~pathlib.Path.lstat`
* :meth:`~pathlib.Path.mkdir`
@@ -243,11 +259,14 @@ class Path:
* :meth:`~pathlib.Path.readlink`
* :meth:`~pathlib.Path.rename`
* :meth:`~pathlib.Path.replace`
+ * :meth:`~pathlib.Path.resolve`
* :meth:`~pathlib.Path.rmdir`
* :meth:`~pathlib.Path.samefile`
* :meth:`~pathlib.Path.stat`
+ * :meth:`~pathlib.Path.symlink_to`
* :meth:`~pathlib.Path.touch`
* :meth:`~pathlib.Path.unlink`
+ * :meth:`~pathlib.Path.walk`
* :meth:`~pathlib.Path.write_bytes`
* :meth:`~pathlib.Path.write_text`
@@ -385,9 +404,6 @@ class Path:
except ValueError:
return False
- async def is_junction(self) -> bool:
- return await to_thread.run_sync(self._path.is_junction)
-
async def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None:
func = partial(os.chmod, follow_symlinks=follow_symlinks)
return await to_thread.run_sync(func, self._path, mode)
@@ -447,6 +463,11 @@ class Path:
async def is_file(self) -> bool:
return await to_thread.run_sync(self._path.is_file, abandon_on_cancel=True)
+ if sys.version_info >= (3, 12):
+
+ async def is_junction(self) -> bool:
+ return await to_thread.run_sync(self._path.is_junction)
+
async def is_mount(self) -> bool:
return await to_thread.run_sync(
os.path.ismount, self._path, abandon_on_cancel=True
diff --git a/contrib/python/anyio/anyio/_core/_signals.py b/contrib/python/anyio/anyio/_core/_signals.py
index f3451d302f5..115c749bd93 100644
--- a/contrib/python/anyio/anyio/_core/_signals.py
+++ b/contrib/python/anyio/anyio/_core/_signals.py
@@ -1,15 +1,13 @@
from __future__ import annotations
from collections.abc import AsyncIterator
-from contextlib import AbstractContextManager
from signal import Signals
+from typing import ContextManager
from ._eventloop import get_async_backend
-def open_signal_receiver(
- *signals: Signals,
-) -> AbstractContextManager[AsyncIterator[Signals]]:
+def open_signal_receiver(*signals: Signals) -> ContextManager[AsyncIterator[Signals]]:
"""
Start receiving operating system signals.
diff --git a/contrib/python/anyio/anyio/_core/_streams.py b/contrib/python/anyio/anyio/_core/_streams.py
index 6a9814e5a91..aa6b0c222ad 100644
--- a/contrib/python/anyio/anyio/_core/_streams.py
+++ b/contrib/python/anyio/anyio/_core/_streams.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import math
-from typing import TypeVar
+from typing import Tuple, TypeVar
from warnings import warn
from ..streams.memory import (
@@ -14,7 +14,7 @@ T_Item = TypeVar("T_Item")
class create_memory_object_stream(
- tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]],
+ Tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]],
):
"""
Create a memory object stream.
diff --git a/contrib/python/anyio/anyio/_core/_subprocesses.py b/contrib/python/anyio/anyio/_core/_subprocesses.py
index 7ba41a5b031..1ac2d549dff 100644
--- a/contrib/python/anyio/anyio/_core/_subprocesses.py
+++ b/contrib/python/anyio/anyio/_core/_subprocesses.py
@@ -160,25 +160,38 @@ async def open_process(
child process prior to the execution of the subprocess. (POSIX only)
:param pass_fds: sequence of file descriptors to keep open between the parent and
child processes. (POSIX only)
- :param user: effective user to run the process as (POSIX only)
- :param group: effective group to run the process as (POSIX only)
- :param extra_groups: supplementary groups to set in the subprocess (POSIX only)
+ :param user: effective user to run the process as (Python >= 3.9; POSIX only)
+ :param group: effective group to run the process as (Python >= 3.9; POSIX only)
+ :param extra_groups: supplementary groups to set in the subprocess (Python >= 3.9;
+ POSIX only)
:param umask: if not negative, this umask is applied in the child process before
- running the given command (POSIX only)
+ running the given command (Python >= 3.9; POSIX only)
:return: an asynchronous process object
"""
kwargs: dict[str, Any] = {}
if user is not None:
+ if sys.version_info < (3, 9):
+ raise TypeError("the 'user' argument requires Python 3.9 or later")
+
kwargs["user"] = user
if group is not None:
+ if sys.version_info < (3, 9):
+ raise TypeError("the 'group' argument requires Python 3.9 or later")
+
kwargs["group"] = group
if extra_groups is not None:
+ if sys.version_info < (3, 9):
+ raise TypeError("the 'extra_groups' argument requires Python 3.9 or later")
+
kwargs["extra_groups"] = group
if umask >= 0:
+ if sys.version_info < (3, 9):
+ raise TypeError("the 'umask' argument requires Python 3.9 or later")
+
kwargs["umask"] = umask
return await get_async_backend().open_process(
diff --git a/contrib/python/anyio/anyio/abc/_eventloop.py b/contrib/python/anyio/anyio/abc/_eventloop.py
index 93d0e9d25b4..2c73bb9ffb8 100644
--- a/contrib/python/anyio/anyio/abc/_eventloop.py
+++ b/contrib/python/anyio/anyio/abc/_eventloop.py
@@ -3,8 +3,7 @@ from __future__ import annotations
import math
import sys
from abc import ABCMeta, abstractmethod
-from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
-from contextlib import AbstractContextManager
+from collections.abc import AsyncIterator, Awaitable
from os import PathLike
from signal import Signals
from socket import AddressFamily, SocketKind, socket
@@ -12,6 +11,9 @@ from typing import (
IO,
TYPE_CHECKING,
Any,
+ Callable,
+ ContextManager,
+ Sequence,
TypeVar,
Union,
overload,
@@ -350,7 +352,7 @@ class AsyncBackend(metaclass=ABCMeta):
@abstractmethod
def open_signal_receiver(
cls, *signals: Signals
- ) -> AbstractContextManager[AsyncIterator[Signals]]:
+ ) -> ContextManager[AsyncIterator[Signals]]:
pass
@classmethod
diff --git a/contrib/python/anyio/anyio/abc/_sockets.py b/contrib/python/anyio/anyio/abc/_sockets.py
index 1c6a450cdcd..b321225a7b8 100644
--- a/contrib/python/anyio/anyio/abc/_sockets.py
+++ b/contrib/python/anyio/anyio/abc/_sockets.py
@@ -8,7 +8,7 @@ from io import IOBase
from ipaddress import IPv4Address, IPv6Address
from socket import AddressFamily
from types import TracebackType
-from typing import Any, TypeVar, Union
+from typing import Any, Tuple, TypeVar, Union
from .._core._typedattr import (
TypedAttributeProvider,
@@ -19,10 +19,10 @@ from ._streams import ByteStream, Listener, UnreliableObjectStream
from ._tasks import TaskGroup
IPAddressType = Union[str, IPv4Address, IPv6Address]
-IPSockAddrType = tuple[str, int]
+IPSockAddrType = Tuple[str, int]
SockAddrType = Union[IPSockAddrType, str]
-UDPPacketType = tuple[bytes, IPSockAddrType]
-UNIXDatagramPacketType = tuple[bytes, str]
+UDPPacketType = Tuple[bytes, IPSockAddrType]
+UNIXDatagramPacketType = Tuple[bytes, str]
T_Retval = TypeVar("T_Retval")
diff --git a/contrib/python/anyio/anyio/from_thread.py b/contrib/python/anyio/anyio/from_thread.py
index 93a4cfe8e49..b8785845bad 100644
--- a/contrib/python/anyio/anyio/from_thread.py
+++ b/contrib/python/anyio/anyio/from_thread.py
@@ -3,17 +3,15 @@ from __future__ import annotations
import sys
from collections.abc import Awaitable, Callable, Generator
from concurrent.futures import Future
-from contextlib import (
- AbstractAsyncContextManager,
- AbstractContextManager,
- contextmanager,
-)
+from contextlib import AbstractContextManager, contextmanager
from dataclasses import dataclass, field
from inspect import isawaitable
from threading import Lock, Thread, get_ident
from types import TracebackType
from typing import (
Any,
+ AsyncContextManager,
+ ContextManager,
Generic,
TypeVar,
cast,
@@ -89,9 +87,7 @@ class _BlockingAsyncContextManager(Generic[T_co], AbstractContextManager):
type[BaseException] | None, BaseException | None, TracebackType | None
] = (None, None, None)
- def __init__(
- self, async_cm: AbstractAsyncContextManager[T_co], portal: BlockingPortal
- ):
+ def __init__(self, async_cm: AsyncContextManager[T_co], portal: BlockingPortal):
self._async_cm = async_cm
self._portal = portal
@@ -378,8 +374,8 @@ class BlockingPortal:
return f, task_status_future.result()
def wrap_async_context_manager(
- self, cm: AbstractAsyncContextManager[T_co]
- ) -> AbstractContextManager[T_co]:
+ self, cm: AsyncContextManager[T_co]
+ ) -> ContextManager[T_co]:
"""
Wrap an async context manager as a synchronous context manager via this portal.
diff --git a/contrib/python/anyio/anyio/pytest_plugin.py b/contrib/python/anyio/anyio/pytest_plugin.py
index c9fe1bde92e..b7d93056145 100644
--- a/contrib/python/anyio/anyio/pytest_plugin.py
+++ b/contrib/python/anyio/anyio/pytest_plugin.py
@@ -1,13 +1,14 @@
from __future__ import annotations
import sys
-from collections.abc import Iterator
+from collections.abc import Generator, Iterator
from contextlib import ExitStack, contextmanager
-from inspect import isasyncgenfunction, iscoroutinefunction
-from typing import Any, cast
+from inspect import isasyncgenfunction, iscoroutinefunction, ismethod
+from typing import Any, Dict, Tuple, cast
import pytest
import sniffio
+from _pytest.fixtures import SubRequest
from _pytest.outcomes import Exit
from ._core._eventloop import get_all_backends, get_async_backend
@@ -27,7 +28,7 @@ def extract_backend_and_options(backend: object) -> tuple[str, dict[str, Any]]:
return backend, {}
elif isinstance(backend, tuple) and len(backend) == 2:
if isinstance(backend[0], str) and isinstance(backend[1], dict):
- return cast(tuple[str, dict[str, Any]], backend)
+ return cast(Tuple[str, Dict[str, Any]], backend)
raise TypeError("anyio_backend must be either a string or tuple of (string, dict)")
@@ -70,28 +71,56 @@ def pytest_configure(config: Any) -> None:
)
-def pytest_fixture_setup(fixturedef: Any, request: Any) -> None:
- def wrapper(*args, anyio_backend, **kwargs): # type: ignore[no-untyped-def]
+@pytest.hookimpl(hookwrapper=True)
+def pytest_fixture_setup(fixturedef: Any, request: Any) -> Generator[Any]:
+ def wrapper(
+ *args: Any, anyio_backend: Any, request: SubRequest, **kwargs: Any
+ ) -> Any:
+ # Rebind any fixture methods to the request instance
+ if (
+ request.instance
+ and ismethod(func)
+ and type(func.__self__) is type(request.instance)
+ ):
+ local_func = func.__func__.__get__(request.instance)
+ else:
+ local_func = func
+
backend_name, backend_options = extract_backend_and_options(anyio_backend)
if has_backend_arg:
kwargs["anyio_backend"] = anyio_backend
+ if has_request_arg:
+ kwargs["request"] = request
+
with get_runner(backend_name, backend_options) as runner:
- if isasyncgenfunction(func):
- yield from runner.run_asyncgen_fixture(func, kwargs)
+ if isasyncgenfunction(local_func):
+ yield from runner.run_asyncgen_fixture(local_func, kwargs)
else:
- yield runner.run_fixture(func, kwargs)
+ yield runner.run_fixture(local_func, kwargs)
# Only apply this to coroutine functions and async generator functions in requests
# that involve the anyio_backend fixture
func = fixturedef.func
if isasyncgenfunction(func) or iscoroutinefunction(func):
if "anyio_backend" in request.fixturenames:
- has_backend_arg = "anyio_backend" in fixturedef.argnames
fixturedef.func = wrapper
- if not has_backend_arg:
+ original_argname = fixturedef.argnames
+
+ if not (has_backend_arg := "anyio_backend" in fixturedef.argnames):
fixturedef.argnames += ("anyio_backend",)
+ if not (has_request_arg := "request" in fixturedef.argnames):
+ fixturedef.argnames += ("request",)
+
+ try:
+ return (yield)
+ finally:
+ fixturedef.func = func
+ fixturedef.argnames = original_argname
+
+ return (yield)
+
@pytest.hookimpl(tryfirst=True)
def pytest_pycollect_makeitem(collector: Any, name: Any, obj: Any) -> None:
diff --git a/contrib/python/anyio/anyio/streams/tls.py b/contrib/python/anyio/anyio/streams/tls.py
index 83240b4d352..d01c8e6f4c2 100644
--- a/contrib/python/anyio/anyio/streams/tls.py
+++ b/contrib/python/anyio/anyio/streams/tls.py
@@ -7,7 +7,7 @@ import sys
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from functools import wraps
-from typing import Any, TypeVar
+from typing import Any, Tuple, TypeVar
from .. import (
BrokenResourceError,
@@ -25,8 +25,8 @@ else:
T_Retval = TypeVar("T_Retval")
PosArgsT = TypeVarTuple("PosArgsT")
-_PCTRTT = tuple[tuple[str, str], ...]
-_PCTRTTT = tuple[_PCTRTT, ...]
+_PCTRTT = Tuple[Tuple[str, str], ...]
+_PCTRTTT = Tuple[_PCTRTT, ...]
class TLSAttribute(TypedAttributeSet):
@@ -162,9 +162,8 @@ class TLSStream(ByteStream):
except ssl.SSLError as exc:
self._read_bio.write_eof()
self._write_bio.write_eof()
- if (
- isinstance(exc, ssl.SSLEOFError)
- or "UNEXPECTED_EOF_WHILE_READING" in exc.strerror
+ if isinstance(exc, ssl.SSLEOFError) or (
+ exc.strerror and "UNEXPECTED_EOF_WHILE_READING" in exc.strerror
):
if self.standard_compatible:
raise BrokenResourceError from exc
diff --git a/contrib/python/anyio/ya.make b/contrib/python/anyio/ya.make
index cec445229c9..bb56a53ce5f 100644
--- a/contrib/python/anyio/ya.make
+++ b/contrib/python/anyio/ya.make
@@ -2,7 +2,7 @@
PY3_LIBRARY()
-VERSION(4.6.0)
+VERSION(4.6.2)
LICENSE(MIT)
diff --git a/contrib/python/argcomplete/py3/.dist-info/METADATA b/contrib/python/argcomplete/py3/.dist-info/METADATA
index ce75d7bfa8b..8bda4dd4a3d 100644
--- a/contrib/python/argcomplete/py3/.dist-info/METADATA
+++ b/contrib/python/argcomplete/py3/.dist-info/METADATA
@@ -1,6 +1,6 @@
Metadata-Version: 2.1
Name: argcomplete
-Version: 3.5.0
+Version: 3.5.1
Summary: Bash tab completion for argparse
Home-page: https://github.com/kislyuk/argcomplete
Author: Andrey Kislyuk
@@ -9,7 +9,7 @@ License: Apache Software License
Project-URL: Documentation, https://kislyuk.github.io/argcomplete
Project-URL: Source Code, https://github.com/kislyuk/argcomplete
Project-URL: Issue Tracker, https://github.com/kislyuk/argcomplete/issues
-Project-URL: Change Log, https://github.com/kislyuk/argcomplete/blob/master/Changes.rst
+Project-URL: Change Log, https://github.com/kislyuk/argcomplete/blob/develop/Changes.rst
Platform: MacOS X
Platform: Posix
Classifier: Environment :: Console
diff --git a/contrib/python/argcomplete/py3/argcomplete/packages/_argparse.py b/contrib/python/argcomplete/py3/argcomplete/packages/_argparse.py
index 2a064f9a8f7..d10cf01da9d 100644
--- a/contrib/python/argcomplete/py3/argcomplete/packages/_argparse.py
+++ b/contrib/python/argcomplete/py3/argcomplete/packages/_argparse.py
@@ -162,6 +162,8 @@ class IntrospectiveArgumentParser(ArgumentParser):
def consume_optional(start_index):
# get the optional identified at this index
option_tuple = option_string_indices[start_index]
+ if isinstance(option_tuple, list): # Python 3.12.7+
+ option_tuple = option_tuple[0]
if len(option_tuple) == 3:
action, option_string, explicit_arg = option_tuple
else: # Python 3.11.9+, 3.12.3+, 3.13+
diff --git a/contrib/python/argcomplete/py3/ya.make b/contrib/python/argcomplete/py3/ya.make
index 16487619c8f..ddce3929fb6 100644
--- a/contrib/python/argcomplete/py3/ya.make
+++ b/contrib/python/argcomplete/py3/ya.make
@@ -2,7 +2,7 @@
PY3_LIBRARY()
-VERSION(3.5.0)
+VERSION(3.5.1)
LICENSE(Apache-2.0)
diff --git a/contrib/python/clickhouse-connect/.dist-info/METADATA b/contrib/python/clickhouse-connect/.dist-info/METADATA
index bb928a4bc25..f47d5e0e6cb 100644
--- a/contrib/python/clickhouse-connect/.dist-info/METADATA
+++ b/contrib/python/clickhouse-connect/.dist-info/METADATA
@@ -1,6 +1,6 @@
Metadata-Version: 2.1
Name: clickhouse-connect
-Version: 0.8.2
+Version: 0.8.3
Summary: ClickHouse Database Core Driver for Python, Pandas, and Superset
Home-page: https://github.com/ClickHouse/clickhouse-connect
Author: ClickHouse Inc.
diff --git a/contrib/python/clickhouse-connect/clickhouse_connect/__version__.py b/contrib/python/clickhouse-connect/clickhouse_connect/__version__.py
index c400d68132e..b4ab55be618 100644
--- a/contrib/python/clickhouse-connect/clickhouse_connect/__version__.py
+++ b/contrib/python/clickhouse-connect/clickhouse_connect/__version__.py
@@ -1 +1 @@
-version = '0.8.2'
+version = '0.8.3'
diff --git a/contrib/python/clickhouse-connect/clickhouse_connect/driver/__init__.py b/contrib/python/clickhouse-connect/clickhouse_connect/driver/__init__.py
index fe3e4b3fbc5..58efb5f8a83 100644
--- a/contrib/python/clickhouse-connect/clickhouse_connect/driver/__init__.py
+++ b/contrib/python/clickhouse-connect/clickhouse_connect/driver/__init__.py
@@ -133,6 +133,7 @@ async def create_async_client(*,
dsn: Optional[str] = None,
settings: Optional[Dict[str, Any]] = None,
generic_args: Optional[Dict[str, Any]] = None,
+ executor_threads: Optional[int] = None,
**kwargs) -> AsyncClient:
"""
The preferred method to get an async ClickHouse Connect Client instance.
@@ -154,6 +155,8 @@ async def create_async_client(*,
:param settings: ClickHouse server settings to be used with the session/every request
:param generic_args: Used internally to parse DBAPI connection strings into keyword arguments and ClickHouse settings.
It is not recommended to use this parameter externally
+ :param: executor_threads 'max_worker' threads used by the client ThreadPoolExecutor. If not set, the default
+ of 4 + detected CPU cores will be used
:param kwargs -- Recognized keyword arguments (used by the HTTP client), see below
:param compress: Enable compression for ClickHouse HTTP inserts and query results. True will select the preferred
@@ -194,4 +197,4 @@ async def create_async_client(*,
loop = asyncio.get_running_loop()
_client = await loop.run_in_executor(None, _create_client)
- return AsyncClient(client=_client)
+ return AsyncClient(client=_client, executor_threads=executor_threads)
diff --git a/contrib/python/clickhouse-connect/clickhouse_connect/driver/asyncclient.py b/contrib/python/clickhouse-connect/clickhouse_connect/driver/asyncclient.py
index bf56c9783fa..b63a14f7761 100644
--- a/contrib/python/clickhouse-connect/clickhouse_connect/driver/asyncclient.py
+++ b/contrib/python/clickhouse-connect/clickhouse_connect/driver/asyncclient.py
@@ -1,5 +1,7 @@
import asyncio
import io
+import os
+from concurrent.futures.thread import ThreadPoolExecutor
from datetime import tzinfo
from typing import Optional, Union, Dict, Any, Sequence, Iterable, Generator, BinaryIO
@@ -20,10 +22,13 @@ class AsyncClient:
Internally, each of the methods that uses IO is wrapped in a call to EventLoop.run_in_executor.
"""
- def __init__(self, *, client: Client):
+ def __init__(self, *, client: Client, executor_threads: int = 0):
if isinstance(client, HttpClient):
client.headers['User-Agent'] = client.headers['User-Agent'].replace('mode:sync;', 'mode:async;')
self.client = client
+ if executor_threads == 0:
+ executor_threads = min(32, (os.cpu_count() or 1) + 4) # Mimic the default behavior
+ self.executor = ThreadPoolExecutor(max_workers=executor_threads)
def set_client_setting(self, key, value):
@@ -88,7 +93,7 @@ class AsyncClient:
external_data=external_data)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _query)
+ result = await loop.run_in_executor(self.executor, _query)
return result
async def query_column_block_stream(self,
@@ -117,7 +122,7 @@ class AsyncClient:
external_data=external_data)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _query_column_block_stream)
+ result = await loop.run_in_executor(self.executor, _query_column_block_stream)
return result
async def query_row_block_stream(self,
@@ -146,7 +151,7 @@ class AsyncClient:
external_data=external_data)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _query_row_block_stream)
+ result = await loop.run_in_executor(self.executor, _query_row_block_stream)
return result
async def query_rows_stream(self,
@@ -175,7 +180,7 @@ class AsyncClient:
external_data=external_data)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _query_rows_stream)
+ result = await loop.run_in_executor(self.executor, _query_rows_stream)
return result
async def raw_query(self,
@@ -202,7 +207,7 @@ class AsyncClient:
use_database=use_database, external_data=external_data)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _raw_query)
+ result = await loop.run_in_executor(self.executor, _raw_query)
return result
async def raw_stream(self, query: str,
@@ -228,7 +233,7 @@ class AsyncClient:
use_database=use_database, external_data=external_data)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _raw_stream)
+ result = await loop.run_in_executor(self.executor, _raw_stream)
return result
async def query_np(self,
@@ -255,7 +260,7 @@ class AsyncClient:
external_data=external_data)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _query_np)
+ result = await loop.run_in_executor(self.executor, _query_np)
return result
async def query_np_stream(self,
@@ -282,7 +287,7 @@ class AsyncClient:
context=context, external_data=external_data)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _query_np_stream)
+ result = await loop.run_in_executor(self.executor, _query_np_stream)
return result
async def query_df(self,
@@ -314,7 +319,7 @@ class AsyncClient:
external_data=external_data, use_extended_dtypes=use_extended_dtypes)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _query_df)
+ result = await loop.run_in_executor(self.executor, _query_df)
return result
async def query_df_stream(self,
@@ -347,7 +352,7 @@ class AsyncClient:
external_data=external_data, use_extended_dtypes=use_extended_dtypes)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _query_df_stream)
+ result = await loop.run_in_executor(self.executor, _query_df_stream)
return result
def create_query_context(self,
@@ -433,7 +438,7 @@ class AsyncClient:
use_strings=use_strings, external_data=external_data)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _query_arrow)
+ result = await loop.run_in_executor(self.executor, _query_arrow)
return result
async def query_arrow_stream(self,
@@ -457,7 +462,7 @@ class AsyncClient:
use_strings=use_strings, external_data=external_data)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _query_arrow_stream)
+ result = await loop.run_in_executor(self.executor, _query_arrow_stream)
return result
async def command(self,
@@ -486,7 +491,7 @@ class AsyncClient:
use_database=use_database, external_data=external_data)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _command)
+ result = await loop.run_in_executor(self.executor, _command)
return result
async def ping(self) -> bool:
@@ -499,7 +504,7 @@ class AsyncClient:
return self.client.ping()
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _ping)
+ result = await loop.run_in_executor(self.executor, _ping)
return result
async def insert(self,
@@ -537,7 +542,7 @@ class AsyncClient:
column_oriented=column_oriented, settings=settings, context=context)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _insert)
+ result = await loop.run_in_executor(self.executor, _insert)
return result
async def insert_df(self, table: str = None,
@@ -572,7 +577,7 @@ class AsyncClient:
context=context)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _insert_df)
+ result = await loop.run_in_executor(self.executor, _insert_df)
return result
async def insert_arrow(self, table: str,
@@ -591,7 +596,7 @@ class AsyncClient:
return self.client.insert_arrow(table=table, arrow_table=arrow_table, database=database, settings=settings)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _insert_arrow)
+ result = await loop.run_in_executor(self.executor, _insert_arrow)
return result
async def create_insert_context(self,
@@ -625,7 +630,7 @@ class AsyncClient:
column_oriented=column_oriented, settings=settings, data=data)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _create_insert_context)
+ result = await loop.run_in_executor(self.executor, _create_insert_context)
return result
async def data_insert(self, context: InsertContext) -> QuerySummary:
@@ -639,7 +644,7 @@ class AsyncClient:
return self.client.data_insert(context=context)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _data_insert)
+ result = await loop.run_in_executor(self.executor, _data_insert)
return result
async def raw_insert(self, table: str,
@@ -663,5 +668,5 @@ class AsyncClient:
settings=settings, fmt=fmt, compression=compression)
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, _raw_insert)
+ result = await loop.run_in_executor(self.executor, _raw_insert)
return result
diff --git a/contrib/python/clickhouse-connect/ya.make b/contrib/python/clickhouse-connect/ya.make
index 89d942df53e..23919d9b305 100644
--- a/contrib/python/clickhouse-connect/ya.make
+++ b/contrib/python/clickhouse-connect/ya.make
@@ -2,7 +2,7 @@
PY3_LIBRARY()
-VERSION(0.8.2)
+VERSION(0.8.3)
LICENSE(Apache-2.0)
diff --git a/contrib/python/hypothesis/py3/.dist-info/METADATA b/contrib/python/hypothesis/py3/.dist-info/METADATA
index 418a478f2cf..7916731906c 100644
--- a/contrib/python/hypothesis/py3/.dist-info/METADATA
+++ b/contrib/python/hypothesis/py3/.dist-info/METADATA
@@ -1,6 +1,6 @@
Metadata-Version: 2.1
Name: hypothesis
-Version: 6.112.4
+Version: 6.112.5
Summary: A library for property-based testing
Home-page: https://hypothesis.works
Author: David R. MacIver and Zac Hatfield-Dodds
diff --git a/contrib/python/hypothesis/py3/hypothesis/stateful.py b/contrib/python/hypothesis/py3/hypothesis/stateful.py
index 06e97b7ba5b..190d7076fd8 100644
--- a/contrib/python/hypothesis/py3/hypothesis/stateful.py
+++ b/contrib/python/hypothesis/py3/hypothesis/stateful.py
@@ -501,9 +501,12 @@ class Bundle(SearchStrategy[Ex]):
drawn from this bundle will be consumed (as above) when requested.
"""
- def __init__(self, name: str, *, consume: bool = False) -> None:
+ def __init__(
+ self, name: str, *, consume: bool = False, draw_references: bool = True
+ ) -> None:
self.name = name
self.consume = consume
+ self.draw_references = draw_references
def do_draw(self, data):
machine = data.draw(self_strategy)
@@ -522,7 +525,9 @@ class Bundle(SearchStrategy[Ex]):
else:
reference = bundle[position]
- return reference
+ if self.draw_references:
+ return reference
+ return machine.names_to_values[reference.name]
def __repr__(self):
consume = self.consume
@@ -541,6 +546,13 @@ class Bundle(SearchStrategy[Ex]):
machine = data.draw(self_strategy)
return bool(machine.bundle(self.name))
+ def flatmap(self, expand):
+ if self.draw_references:
+ return type(self)(
+ self.name, consume=self.consume, draw_references=False
+ ).flatmap(expand)
+ return super().flatmap(expand)
+
def consumes(bundle: Bundle[Ex]) -> SearchStrategy[Ex]:
"""When introducing a rule in a RuleBasedStateMachine, this function can
diff --git a/contrib/python/hypothesis/py3/hypothesis/version.py b/contrib/python/hypothesis/py3/hypothesis/version.py
index a2112a2f362..11ed8649776 100644
--- a/contrib/python/hypothesis/py3/hypothesis/version.py
+++ b/contrib/python/hypothesis/py3/hypothesis/version.py
@@ -8,5 +8,5 @@
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.
-__version_info__ = (6, 112, 4)
+__version_info__ = (6, 112, 5)
__version__ = ".".join(map(str, __version_info__))
diff --git a/contrib/python/hypothesis/py3/ya.make b/contrib/python/hypothesis/py3/ya.make
index 7dc523a75e6..13a8342b392 100644
--- a/contrib/python/hypothesis/py3/ya.make
+++ b/contrib/python/hypothesis/py3/ya.make
@@ -2,7 +2,7 @@
PY3_LIBRARY()
-VERSION(6.112.4)
+VERSION(6.112.5)
LICENSE(MPL-2.0)
diff --git a/contrib/python/zope.interface/py3/.dist-info/METADATA b/contrib/python/zope.interface/py3/.dist-info/METADATA
index 369d5d2401b..30f01bb8931 100644
--- a/contrib/python/zope.interface/py3/.dist-info/METADATA
+++ b/contrib/python/zope.interface/py3/.dist-info/METADATA
@@ -1,10 +1,10 @@
Metadata-Version: 2.1
Name: zope.interface
-Version: 7.0.3
+Version: 7.1.0
Summary: Interfaces for Python
Home-page: https://github.com/zopefoundation/zope.interface
Author: Zope Foundation and Contributors
-Author-email: zope-dev@zope.org
+Author-email: zope-dev@zope.dev
License: ZPL 2.1
Keywords: interface,components,plugins
Classifier: Development Status :: 5 - Production/Stable
@@ -18,25 +18,27 @@ Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Framework :: Zope :: 3
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
License-File: LICENSE.txt
Requires-Dist: setuptools
Provides-Extra: docs
-Requires-Dist: Sphinx; extra == "docs"
-Requires-Dist: repoze.sphinx.autointerface; extra == "docs"
-Requires-Dist: sphinx-rtd-theme; extra == "docs"
+Requires-Dist: Sphinx ; extra == 'docs'
+Requires-Dist: repoze.sphinx.autointerface ; extra == 'docs'
+Requires-Dist: furo ; extra == 'docs'
Provides-Extra: test
-Requires-Dist: coverage>=5.0.3; extra == "test"
-Requires-Dist: zope.event; extra == "test"
-Requires-Dist: zope.testing; extra == "test"
+Requires-Dist: coverage[toml] ; extra == 'test'
+Requires-Dist: zope.event ; extra == 'test'
+Requires-Dist: zope.testing ; extra == 'test'
Provides-Extra: testing
-Requires-Dist: coverage>=5.0.3; extra == "testing"
-Requires-Dist: zope.event; extra == "testing"
-Requires-Dist: zope.testing; extra == "testing"
+Requires-Dist: coverage[toml] ; extra == 'testing'
+Requires-Dist: zope.event ; extra == 'testing'
+Requires-Dist: zope.testing ; extra == 'testing'
====================
``zope.interface``
@@ -74,6 +76,15 @@ For detailed documentation, please see https://zopeinterface.readthedocs.io/en/l
Changes
=========
+7.1.0 (2024-10-10)
+==================
+
+- Declare support for Python 3.13.
+
+- Fix segmentation faults on Python 3.13.
+ (`#323 <https://github.com/zopefoundation/zope.interface/issues/323>`_)
+
+
7.0.3 (2024-08-27)
==================
diff --git a/contrib/python/zope.interface/py3/ya.make b/contrib/python/zope.interface/py3/ya.make
index 966c73c1fe4..2448b66894e 100644
--- a/contrib/python/zope.interface/py3/ya.make
+++ b/contrib/python/zope.interface/py3/ya.make
@@ -2,7 +2,7 @@
PY3_LIBRARY()
-VERSION(7.0.3)
+VERSION(7.1.0)
LICENSE(ZPL-2.1)
diff --git a/contrib/python/zope.interface/py3/zope/interface/common/interfaces.py b/contrib/python/zope.interface/py3/zope/interface/common/interfaces.py
index 74386de0248..90757958228 100644
--- a/contrib/python/zope.interface/py3/zope/interface/common/interfaces.py
+++ b/contrib/python/zope.interface/py3/zope/interface/common/interfaces.py
@@ -19,6 +19,8 @@ from zope.interface import classImplements
class IException(Interface):
"Interface for `Exception`"
+
+
classImplements(Exception, IException) # noqa E305
@@ -28,116 +30,162 @@ class IStandardError(IException):
class IWarning(IException):
"Interface for `Warning`"
+
+
classImplements(Warning, IWarning) # noqa E305
class ISyntaxError(IStandardError):
"Interface for `SyntaxError`"
+
+
classImplements(SyntaxError, ISyntaxError) # noqa E305
class ILookupError(IStandardError):
"Interface for `LookupError`"
+
+
classImplements(LookupError, ILookupError) # noqa E305
class IValueError(IStandardError):
"Interface for `ValueError`"
+
+
classImplements(ValueError, IValueError) # noqa E305
class IRuntimeError(IStandardError):
"Interface for `RuntimeError`"
+
+
classImplements(RuntimeError, IRuntimeError) # noqa E305
class IArithmeticError(IStandardError):
"Interface for `ArithmeticError`"
+
+
classImplements(ArithmeticError, IArithmeticError) # noqa E305
class IAssertionError(IStandardError):
"Interface for `AssertionError`"
+
+
classImplements(AssertionError, IAssertionError) # noqa E305
class IAttributeError(IStandardError):
"Interface for `AttributeError`"
+
+
classImplements(AttributeError, IAttributeError) # noqa E305
class IDeprecationWarning(IWarning):
"Interface for `DeprecationWarning`"
+
+
classImplements(DeprecationWarning, IDeprecationWarning) # noqa E305
class IEOFError(IStandardError):
"Interface for `EOFError`"
+
+
classImplements(EOFError, IEOFError) # noqa E305
class IEnvironmentError(IStandardError):
"Interface for `EnvironmentError`"
+
+
classImplements(EnvironmentError, IEnvironmentError) # noqa E305
class IFloatingPointError(IArithmeticError):
"Interface for `FloatingPointError`"
+
+
classImplements(FloatingPointError, IFloatingPointError) # noqa E305
class IIOError(IEnvironmentError):
"Interface for `IOError`"
+
+
classImplements(IOError, IIOError) # noqa E305
class IImportError(IStandardError):
"Interface for `ImportError`"
+
+
classImplements(ImportError, IImportError) # noqa E305
class IIndentationError(ISyntaxError):
"Interface for `IndentationError`"
+
+
classImplements(IndentationError, IIndentationError) # noqa E305
class IIndexError(ILookupError):
"Interface for `IndexError`"
+
+
classImplements(IndexError, IIndexError) # noqa E305
class IKeyError(ILookupError):
"Interface for `KeyError`"
+
+
classImplements(KeyError, IKeyError) # noqa E305
class IKeyboardInterrupt(IStandardError):
"Interface for `KeyboardInterrupt`"
+
+
classImplements(KeyboardInterrupt, IKeyboardInterrupt) # noqa E305
class IMemoryError(IStandardError):
"Interface for `MemoryError`"
+
+
classImplements(MemoryError, IMemoryError) # noqa E305
class INameError(IStandardError):
"Interface for `NameError`"
+
+
classImplements(NameError, INameError) # noqa E305
class INotImplementedError(IRuntimeError):
"Interface for `NotImplementedError`"
+
+
classImplements(NotImplementedError, INotImplementedError) # noqa E305
class IOSError(IEnvironmentError):
"Interface for `OSError`"
+
+
classImplements(OSError, IOSError) # noqa E305
class IOverflowError(IArithmeticError):
"Interface for `ArithmeticError`"
+
+
classImplements(OverflowError, IOverflowError) # noqa E305
@@ -151,59 +199,83 @@ class IOverflowWarning(IWarning):
class IReferenceError(IStandardError):
"Interface for `ReferenceError`"
+
+
classImplements(ReferenceError, IReferenceError) # noqa E305
class IRuntimeWarning(IWarning):
"Interface for `RuntimeWarning`"
+
+
classImplements(RuntimeWarning, IRuntimeWarning) # noqa E305
class IStopIteration(IException):
"Interface for `StopIteration`"
+
+
classImplements(StopIteration, IStopIteration) # noqa E305
class ISyntaxWarning(IWarning):
"Interface for `SyntaxWarning`"
+
+
classImplements(SyntaxWarning, ISyntaxWarning) # noqa E305
class ISystemError(IStandardError):
"Interface for `SystemError`"
+
+
classImplements(SystemError, ISystemError) # noqa E305
class ISystemExit(IException):
"Interface for `SystemExit`"
+
+
classImplements(SystemExit, ISystemExit) # noqa E305
class ITabError(IIndentationError):
"Interface for `TabError`"
+
+
classImplements(TabError, ITabError) # noqa E305
class ITypeError(IStandardError):
"Interface for `TypeError`"
+
+
classImplements(TypeError, ITypeError) # noqa E305
class IUnboundLocalError(INameError):
"Interface for `UnboundLocalError`"
+
+
classImplements(UnboundLocalError, IUnboundLocalError) # noqa E305
class IUnicodeError(IValueError):
"Interface for `UnicodeError`"
+
+
classImplements(UnicodeError, IUnicodeError) # noqa E305
class IUserWarning(IWarning):
"Interface for `UserWarning`"
+
+
classImplements(UserWarning, IUserWarning) # noqa E305
class IZeroDivisionError(IArithmeticError):
"Interface for `ZeroDivisionError`"
+
+
classImplements(ZeroDivisionError, IZeroDivisionError) # noqa E305
diff --git a/contrib/python/zope.interface/py3/zope/interface/common/tests/basemapping.py b/contrib/python/zope.interface/py3/zope/interface/common/tests/basemapping.py
index db4c091ff69..fc4e2850574 100644
--- a/contrib/python/zope.interface/py3/zope/interface/common/tests/basemapping.py
+++ b/contrib/python/zope.interface/py3/zope/interface/common/tests/basemapping.py
@@ -20,7 +20,7 @@ def _testIReadMapping(self, inst, state, absent):
for key in state:
self.assertEqual(inst[key], state[key])
self.assertEqual(inst.get(key, None), state[key])
- self.assertTrue(key in inst)
+ self.assertIn(key, inst)
for key in absent:
self.assertEqual(inst.get(key, None), None)
diff --git a/contrib/python/zope.interface/py3/zope/interface/common/tests/test_collections.py b/contrib/python/zope.interface/py3/zope/interface/common/tests/test_collections.py
index 6d23f6f9609..df7dec99a29 100644
--- a/contrib/python/zope.interface/py3/zope/interface/common/tests/test_collections.py
+++ b/contrib/python/zope.interface/py3/zope/interface/common/tests/test_collections.py
@@ -12,6 +12,7 @@
import array
+import sys
import unittest
from collections import OrderedDict
from collections import abc
@@ -100,6 +101,10 @@ class TestVerifyClass(VerifyClassMixin, unittest.TestCase):
add_abc_interface_tests(TestVerifyClass, collections.ISet.__module__)
+def _get_FrameLocalsProxy():
+ return type(sys._getframe().f_locals)
+
+
class TestVerifyObject(VerifyObjectMixin,
TestVerifyClass):
CONSTRUCTORS = {
@@ -127,6 +132,11 @@ class TestVerifyObject(VerifyObjectMixin,
'async_generator': unittest.SkipTest,
type(iter(tuple())): lambda: iter(tuple()),
}
+ if sys.version_info >= (3, 13):
+ def FrameLocalsProxy_constructor():
+ return _get_FrameLocalsProxy()(sys._getframe())
+ FrameLocalsProxy = _get_FrameLocalsProxy()
+ CONSTRUCTORS[FrameLocalsProxy] = FrameLocalsProxy_constructor
UNVERIFIABLE_RO = {
# ``array.array`` fails the ``test_auto_ro_*`` tests with and
diff --git a/contrib/python/zope.interface/py3/zope/interface/declarations.py b/contrib/python/zope.interface/py3/zope/interface/declarations.py
index a9b983da81f..825c5789205 100644
--- a/contrib/python/zope.interface/py3/zope/interface/declarations.py
+++ b/contrib/python/zope.interface/py3/zope/interface/declarations.py
@@ -953,6 +953,7 @@ class ClassProvides(Declaration, ClassProvidesBase):
__get__ = ClassProvidesBase.__get__
+# autopep8: off (it breaks the statements in the "if")
def directlyProvidedBy(object): # pylint:disable=redefined-builtin
"""Return the interfaces directly provided by the given object
@@ -970,6 +971,7 @@ def directlyProvidedBy(object): # pylint:disable=redefined-builtin
# Strip off the class part of the spec:
return Declaration(provides.__bases__[:-1])
+# autopep8: on
class provider:
diff --git a/contrib/python/zope.interface/py3/zope/interface/interface.py b/contrib/python/zope.interface/py3/zope/interface/interface.py
index 575b6381e3e..e5dddb88115 100644
--- a/contrib/python/zope.interface/py3/zope/interface/interface.py
+++ b/contrib/python/zope.interface/py3/zope/interface/interface.py
@@ -825,8 +825,8 @@ class InterfaceClass(_InterfaceClassBase):
# __firstlineno__: Python 3.13b1+
# https://github.com/python/cpython/pull/118475
'__firstlineno__',
- )
- and aval is not _decorator_non_return # noqa W503
+ ) and
+ aval is not _decorator_non_return # noqa W503
}
def interfaces(self):
diff --git a/contrib/python/zope.interface/py3/zope/interface/interfaces.py b/contrib/python/zope.interface/py3/zope/interface/interfaces.py
index 454fee893c3..9bafeb58428 100644
--- a/contrib/python/zope.interface/py3/zope/interface/interfaces.py
+++ b/contrib/python/zope.interface/py3/zope/interface/interfaces.py
@@ -1156,6 +1156,7 @@ class IRegistrationEvent(IObjectEvent):
class RegistrationEvent(ObjectEvent):
"""There has been a change in a registration
"""
+
def __repr__(self):
return f"{self.__class__.__name__} event:\n{self.object!r}"
diff --git a/contrib/python/zope.interface/py3/zope/interface/tests/test_advice.py b/contrib/python/zope.interface/py3/zope/interface/tests/test_advice.py
index 5d5f0218b00..e439b447797 100644
--- a/contrib/python/zope.interface/py3/zope/interface/tests/test_advice.py
+++ b/contrib/python/zope.interface/py3/zope/interface/tests/test_advice.py
@@ -37,7 +37,7 @@ class FrameInfoTest(unittest.TestCase):
f_locals, f_globals) = advisory_testing.moduleLevelFrameInfo
self.assertEqual(kind, "module")
for d in module.__dict__, f_locals, f_globals:
- self.assertTrue(d is advisory_testing.my_globals)
+ self.assertIs(d, advisory_testing.my_globals)
def test_w_class(self):
from . import advisory_testing
@@ -48,7 +48,7 @@ class FrameInfoTest(unittest.TestCase):
self.assertEqual(kind, "class")
for d in module.__dict__, f_globals:
- self.assertTrue(d is advisory_testing.my_globals)
+ self.assertIs(d, advisory_testing.my_globals)
def test_inside_function_call(self):
from zope.interface.advice import getFrameInfo
@@ -60,7 +60,7 @@ class FrameInfoTest(unittest.TestCase):
self.assertEqual(f_locals, locals())
for d in module.__dict__, f_globals:
- self.assertTrue(d is globals())
+ self.assertIs(d, globals())
def test_inside_exec(self):
from zope.interface.advice import getFrameInfo
@@ -68,9 +68,9 @@ class FrameInfoTest(unittest.TestCase):
_locals = {}
exec(_FUNKY_EXEC, _globals, _locals)
self.assertEqual(_locals['kind'], "exec")
- self.assertTrue(_locals['f_locals'] is _locals)
- self.assertTrue(_locals['module'] is None)
- self.assertTrue(_locals['f_globals'] is _globals)
+ self.assertIs(_locals['f_locals'], _locals)
+ self.assertIsNone(_locals['module'])
+ self.assertIs(_locals['f_globals'], _globals)
_FUNKY_EXEC = """\
diff --git a/contrib/python/zope.interface/py3/zope/interface/tests/test_declarations.py b/contrib/python/zope.interface/py3/zope/interface/tests/test_declarations.py
index 6b76d8eaf87..64fc0e0696b 100644
--- a/contrib/python/zope.interface/py3/zope/interface/tests/test_declarations.py
+++ b/contrib/python/zope.interface/py3/zope/interface/tests/test_declarations.py
@@ -457,15 +457,16 @@ class TestImplements(NameAndModuleComparisonTestsMixin,
self.assertEqual(implementedBy(A), implementedBy(A))
self.assertEqual(hash(implementedBy(A)), hash(implementedBy(A)))
- self.assertTrue(implementedBy(A) < None)
- self.assertTrue(
- None > implementedBy(A)
- ) # pylint:disable=misplaced-comparison-constant
- self.assertTrue(implementedBy(A) < implementedBy(B))
- self.assertTrue(implementedBy(A) > IFoo)
- self.assertTrue(implementedBy(A) <= implementedBy(B))
- self.assertTrue(implementedBy(A) >= IFoo)
- self.assertTrue(implementedBy(A) != IFoo)
+ self.assertLess(implementedBy(A), None)
+ self.assertGreater(
+ None,
+ implementedBy(A)
+ )
+ self.assertLess(implementedBy(A), implementedBy(B))
+ self.assertGreater(implementedBy(A), IFoo)
+ self.assertLessEqual(implementedBy(A), implementedBy(B))
+ self.assertGreaterEqual(implementedBy(A), IFoo)
+ self.assertNotEqual(implementedBy(A), IFoo)
def test_proxy_equality(self):
# https://github.com/zopefoundation/zope.interface/issues/55
@@ -496,19 +497,20 @@ class TestImplements(NameAndModuleComparisonTestsMixin,
# The order of arguments to the operators matters,
# test both
- self.assertTrue(
- implementedByA == implementedByA
- ) # pylint:disable=comparison-with-itself
- self.assertTrue(implementedByA != implementedByB)
- self.assertTrue(implementedByB != implementedByA)
+ self.assertEqual(
+ implementedByA,
+ implementedByA
+ )
+ self.assertNotEqual(implementedByA, implementedByB)
+ self.assertNotEqual(implementedByB, implementedByA)
- self.assertTrue(proxy == implementedByA)
- self.assertTrue(implementedByA == proxy)
- self.assertFalse(proxy != implementedByA)
- self.assertFalse(implementedByA != proxy)
+ self.assertEqual(proxy, implementedByA)
+ self.assertEqual(implementedByA, proxy)
+ self.assertEqual(proxy, implementedByA)
+ self.assertEqual(implementedByA, proxy)
- self.assertTrue(proxy != implementedByB)
- self.assertTrue(implementedByB != proxy)
+ self.assertNotEqual(proxy, implementedByB)
+ self.assertNotEqual(implementedByB, proxy)
def test_changed_deletes_super_cache(self):
impl = self._makeOne()
@@ -581,7 +583,7 @@ class Test_implementedByFallback(unittest.TestCase):
with _MonkeyDict(declarations,
'BuiltinImplementationSpecifications') as specs:
specs[foo] = reg
- self.assertTrue(self._callFUT(foo) is reg)
+ self.assertIs(self._callFUT(foo), reg)
def test_dictless_w_existing_Implements(self):
from zope.interface.declarations import Implements
@@ -592,7 +594,7 @@ class Test_implementedByFallback(unittest.TestCase):
foo = Foo()
foo.__implemented__ = impl
- self.assertTrue(self._callFUT(foo) is impl)
+ self.assertIs(self._callFUT(foo), impl)
def test_dictless_w_existing_not_Implements(self):
from zope.interface.interface import InterfaceClass
@@ -612,7 +614,7 @@ class Test_implementedByFallback(unittest.TestCase):
class Foo:
__implemented__ = impl
- self.assertTrue(self._callFUT(Foo) is impl)
+ self.assertIs(self._callFUT(Foo), impl)
def test_builtins_added_to_cache(self):
from zope.interface import declarations
@@ -637,9 +639,9 @@ class Test_implementedByFallback(unittest.TestCase):
specs[tuple] = t_spec
specs[list] = l_spec
specs[dict] = d_spec
- self.assertTrue(self._callFUT(tuple) is t_spec)
- self.assertTrue(self._callFUT(list) is l_spec)
- self.assertTrue(self._callFUT(dict) is d_spec)
+ self.assertIs(self._callFUT(tuple), t_spec)
+ self.assertIs(self._callFUT(list), l_spec)
+ self.assertIs(self._callFUT(dict), d_spec)
def test_oldstyle_class_no_assertions(self):
# TODO: Figure out P3 story
@@ -714,7 +716,7 @@ class Test_implementedByFallback(unittest.TestCase):
class Foo:
__implemented__ = impl
- self.assertTrue(self._callFUT(Foo) is impl)
+ self.assertIs(self._callFUT(Foo), impl)
def test_super_when_base_implements_interface(self):
from zope.interface import Interface
@@ -963,7 +965,7 @@ class Test_classImplementsOnly(_ImplementsTestMixin, unittest.TestCase):
impl.inherit = Foo
self._callFUT(Foo, IBar)
# Same spec, now different values
- self.assertTrue(Foo.__implemented__ is impl)
+ self.assertIs(Foo.__implemented__, impl)
self.assertEqual(impl.inherit, None)
self.assertEqual(impl.declared, (IBar,))
@@ -1172,7 +1174,7 @@ class Test_implementer(Test_classImplements):
foo = Foo()
decorator = self._makeOne(IFoo)
returned = decorator(foo)
- self.assertTrue(returned is foo)
+ self.assertIs(returned, foo)
spec = foo.__implemented__ # pylint:disable=no-member
self.assertEqual(
spec.__name__, '__tests__.tests.test_declarations.?'
@@ -1564,7 +1566,7 @@ class Test_Provides(unittest.TestCase):
with _Monkey(declarations, InstanceDeclarations=cache):
spec = self._callFUT(Foo, IFoo)
self.assertEqual(list(spec), [IFoo])
- self.assertTrue(cache[(Foo, IFoo)] is spec)
+ self.assertIs(cache[(Foo, IFoo)], spec)
def test_w_cached_spec(self):
from zope.interface import declarations
@@ -1578,7 +1580,7 @@ class Test_Provides(unittest.TestCase):
cache = {(Foo, IFoo): prior}
with _Monkey(declarations, InstanceDeclarations=cache):
spec = self._callFUT(Foo, IFoo)
- self.assertTrue(spec is prior)
+ self.assertIs(spec, prior)
class Test_directlyProvides(unittest.TestCase):
@@ -1775,7 +1777,7 @@ class ClassProvidesBaseFallbackTests(unittest.TestCase):
pass
cpbp = Foo.__provides__ = self._makeOne(Foo, IFoo)
- self.assertTrue(Foo.__provides__ is cpbp)
+ self.assertIs(Foo.__provides__, cpbp)
def test_w_same_class_via_instance(self):
from zope.interface.interface import InterfaceClass
@@ -1841,7 +1843,7 @@ class ClassProvidesTests(unittest.TestCase):
pass
cp = Foo.__provides__ = self._makeOne(Foo, type(Foo), IBar)
- self.assertTrue(Foo.__provides__ is cp)
+ self.assertIs(Foo.__provides__, cp)
self.assertEqual(list(Foo().__provides__), [IFoo])
def test___reduce__(self):
@@ -2323,7 +2325,7 @@ class Test_providedByFallback(unittest.TestCase):
foo.__providedBy__ = object()
expected = foo.__provides__ = object()
spec = self._callFUT(foo)
- self.assertTrue(spec is expected)
+ self.assertIs(spec, expected)
def test_w_providedBy_invalid_spec_w_provides_diff_provides_on_class(self):
@@ -2335,7 +2337,7 @@ class Test_providedByFallback(unittest.TestCase):
expected = foo.__provides__ = object()
Foo.__provides__ = object()
spec = self._callFUT(foo)
- self.assertTrue(spec is expected)
+ self.assertIs(spec, expected)
def test_w_providedBy_invalid_spec_w_provides_same_provides_on_class(self):
from zope.interface.declarations import implementer
diff --git a/contrib/python/zope.interface/py3/zope/interface/tests/test_interface.py b/contrib/python/zope.interface/py3/zope/interface/tests/test_interface.py
index a07ae9f7abf..b6f59c83312 100644
--- a/contrib/python/zope.interface/py3/zope/interface/tests/test_interface.py
+++ b/contrib/python/zope.interface/py3/zope/interface/tests/test_interface.py
@@ -505,8 +505,8 @@ class SpecificationTests(unittest.TestCase):
spec = self._makeOne()
self.assertEqual(spec.__bases__, ())
self.assertEqual(len(spec._implied), 2)
- self.assertTrue(spec in spec._implied)
- self.assertTrue(Interface in spec._implied)
+ self.assertIn(spec, spec._implied)
+ self.assertIn(Interface, spec._implied)
self.assertEqual(len(spec.dependents), 0)
def test_subscribe_first_time(self):
@@ -536,7 +536,7 @@ class SpecificationTests(unittest.TestCase):
spec.unsubscribe(dep)
self.assertEqual(spec.dependents[dep], 1)
spec.unsubscribe(dep)
- self.assertFalse(dep in spec.dependents)
+ self.assertNotIn(dep, spec.dependents)
def test___setBases_subscribes_bases_and_notifies_dependents(self):
from zope.interface.interface import Interface
@@ -568,7 +568,7 @@ class SpecificationTests(unittest.TestCase):
spec._implied[IFoo] = ()
spec.changed(spec)
self.assertIsNone(spec._v_attrs)
- self.assertFalse(IFoo in spec._implied)
+ self.assertNotIn(IFoo, spec._implied)
def test_interfaces_skips_already_seen(self):
from zope.interface.interface import Interface
@@ -600,7 +600,7 @@ class SpecificationTests(unittest.TestCase):
spec = self._makeOne()
foo = object()
spec._v_attrs = {'foo': foo}
- self.assertTrue(spec.get('foo') is foo)
+ self.assertIs(spec.get('foo'), foo)
def test_get_hit_from_base_wo__v_attrs(self):
from zope.interface.interface import Attribute
@@ -613,8 +613,8 @@ class SpecificationTests(unittest.TestCase):
bar = Attribute('bar')
spec = self._makeOne([IFoo, IBar])
- self.assertTrue(spec.get('foo') is IFoo.get('foo'))
- self.assertTrue(spec.get('bar') is IBar.get('bar'))
+ self.assertIs(spec.get('foo'), IFoo.get('foo'))
+ self.assertIs(spec.get('bar'), IBar.get('bar'))
def test_multiple_inheritance_no_interfaces(self):
# If we extend an object that implements interfaces,
@@ -998,7 +998,7 @@ class InterfaceClassTests(unittest.TestCase):
def test___contains___miss(self):
one = self._makeOne()
- self.assertFalse('nonesuch' in one)
+ self.assertNotIn('nonesuch', one)
def test___contains___hit(self):
from zope.interface.interface import Attribute
@@ -1012,8 +1012,8 @@ class InterfaceClassTests(unittest.TestCase):
'bar': fromFunction(_bar),
}
one = self._makeOne(attrs=ATTRS)
- self.assertTrue('foo' in one)
- self.assertTrue('bar' in one)
+ self.assertIn('foo', one)
+ self.assertIn('bar', one)
def test_direct_miss(self):
one = self._makeOne()
@@ -1102,7 +1102,7 @@ class InterfaceClassTests(unittest.TestCase):
self.assertRaises(Invalid, iface.validateInvariants, obj, _errors)
self.assertEqual(_fail_called_with, [((obj,), {})])
self.assertEqual(len(_errors), 1)
- self.assertTrue(isinstance(_errors[0], Invalid))
+ self.assertIsInstance(_errors[0], Invalid)
def test_validateInvariants_fail_in_base_wo_errors_passed(self):
from zope.interface.exceptions import Invalid
@@ -1151,7 +1151,7 @@ class InterfaceClassTests(unittest.TestCase):
self.assertEqual(_passable_called_with, [((obj,), {})])
self.assertEqual(_fail_called_with, [((obj,), {})])
self.assertEqual(len(_errors), 1)
- self.assertTrue(isinstance(_errors[0], Invalid))
+ self.assertIsInstance(_errors[0], Invalid)
def test_validateInvariants_inherited_not_called_multiple_times(self):
_passable_called_with = []
@@ -1191,29 +1191,29 @@ class InterfaceClassTests(unittest.TestCase):
def test_comparison_with_None(self):
# pylint:disable=singleton-comparison,misplaced-comparison-constant
iface = self._makeOne()
- self.assertTrue(iface < None) # noqa E711
- self.assertTrue(iface <= None) # noqa E711
- self.assertFalse(iface == None) # noqa E711
- self.assertTrue(iface != None) # noqa E711
+ self.assertLess(iface, None) # noqa E711
+ self.assertLessEqual(iface, None) # noqa E711
+ self.assertNotEqual(iface, None) # noqa E711
+ self.assertNotEqual(iface, None) # noqa E711
self.assertFalse(iface >= None) # noqa E711
self.assertFalse(iface > None) # noqa E711
self.assertFalse(None < iface) # noqa E711
self.assertFalse(None <= iface) # noqa E711
- self.assertFalse(None == iface) # noqa E711
- self.assertTrue(None != iface) # noqa E711
- self.assertTrue(None >= iface) # noqa E711
- self.assertTrue(None > iface) # noqa E711
+ self.assertNotEqual(None, iface) # noqa E711
+ self.assertNotEqual(None, iface) # noqa E711
+ self.assertGreaterEqual(None, iface) # noqa E711
+ self.assertGreater(None, iface) # noqa E711
def test_comparison_with_same_instance(self):
# pylint:disable=comparison-with-itself
iface = self._makeOne()
self.assertFalse(iface < iface)
- self.assertTrue(iface <= iface)
- self.assertTrue(iface == iface)
- self.assertFalse(iface != iface)
- self.assertTrue(iface >= iface)
+ self.assertLessEqual(iface, iface)
+ self.assertEqual(iface, iface)
+ self.assertEqual(iface, iface)
+ self.assertGreaterEqual(iface, iface)
self.assertFalse(iface > iface)
def test_comparison_with_same_named_instance_in_other_module(self):
@@ -1221,18 +1221,18 @@ class InterfaceClassTests(unittest.TestCase):
one = self._makeOne('IName', __module__='__tests__.tests.one')
other = self._makeOne('IName', __module__='__tests__.tests.other')
- self.assertTrue(one < other)
+ self.assertLess(one, other)
self.assertFalse(other < one)
- self.assertTrue(one <= other)
+ self.assertLessEqual(one, other)
self.assertFalse(other <= one)
- self.assertFalse(one == other)
- self.assertFalse(other == one)
- self.assertTrue(one != other)
- self.assertTrue(other != one)
+ self.assertNotEqual(one, other)
+ self.assertNotEqual(other, one)
+ self.assertNotEqual(one, other)
+ self.assertNotEqual(other, one)
self.assertFalse(one >= other)
- self.assertTrue(other >= one)
+ self.assertGreaterEqual(other, one)
self.assertFalse(one > other)
- self.assertTrue(other > one)
+ self.assertGreater(other, one)
def test_assignment_to__class__(self):
# https://github.com/zopefoundation/zope.interface/issues/6
@@ -1299,7 +1299,7 @@ class InterfaceTests(unittest.TestCase):
class I1(Interface):
attr = Attribute("My attr")
- self.assertTrue(I1['attr'].interface is I1)
+ self.assertIs(I1['attr'].interface, I1)
def test_methods_link_to_interface(self):
from zope.interface import Interface
@@ -1308,7 +1308,7 @@ class InterfaceTests(unittest.TestCase):
def method(foo, bar, bingo):
"A method"
- self.assertTrue(I1['method'].interface is I1)
+ self.assertIs(I1['method'].interface, I1)
def test_classImplements_simple(self):
from zope.interface import Interface
@@ -1339,10 +1339,10 @@ class InterfaceTests(unittest.TestCase):
self.assertTrue(ICurrent.implementedBy(Current))
self.assertFalse(IOther.implementedBy(Current))
self.assertEqual(ICurrent, ICurrent)
- self.assertTrue(ICurrent in implementedBy(Current))
- self.assertFalse(IOther in implementedBy(Current))
- self.assertTrue(ICurrent in providedBy(current))
- self.assertFalse(IOther in providedBy(current))
+ self.assertIn(ICurrent, implementedBy(Current))
+ self.assertNotIn(IOther, implementedBy(Current))
+ self.assertIn(ICurrent, providedBy(current))
+ self.assertNotIn(IOther, providedBy(current))
def test_classImplements_base_not_derived(self):
from zope.interface import Interface
@@ -1366,10 +1366,10 @@ class InterfaceTests(unittest.TestCase):
self.assertTrue(IBase.implementedBy(Current))
self.assertFalse(IDerived.implementedBy(Current))
- self.assertTrue(IBase in implementedBy(Current))
- self.assertFalse(IDerived in implementedBy(Current))
- self.assertTrue(IBase in providedBy(current))
- self.assertFalse(IDerived in providedBy(current))
+ self.assertIn(IBase, implementedBy(Current))
+ self.assertNotIn(IDerived, implementedBy(Current))
+ self.assertIn(IBase, providedBy(current))
+ self.assertNotIn(IDerived, providedBy(current))
def test_classImplements_base_and_derived(self):
from zope.interface import Interface
@@ -1393,12 +1393,12 @@ class InterfaceTests(unittest.TestCase):
self.assertTrue(IBase.implementedBy(Current))
self.assertTrue(IDerived.implementedBy(Current))
- self.assertFalse(IBase in implementedBy(Current))
- self.assertTrue(IBase in implementedBy(Current).flattened())
- self.assertTrue(IDerived in implementedBy(Current))
- self.assertFalse(IBase in providedBy(current))
- self.assertTrue(IBase in providedBy(current).flattened())
- self.assertTrue(IDerived in providedBy(current))
+ self.assertNotIn(IBase, implementedBy(Current))
+ self.assertIn(IBase, implementedBy(Current).flattened())
+ self.assertIn(IDerived, implementedBy(Current))
+ self.assertNotIn(IBase, providedBy(current))
+ self.assertIn(IBase, providedBy(current).flattened())
+ self.assertIn(IDerived, providedBy(current))
def test_classImplements_multiple(self):
from zope.interface import Interface
@@ -1428,10 +1428,10 @@ class InterfaceTests(unittest.TestCase):
self.assertTrue(ILeft.implementedBy(Ambi))
self.assertTrue(IRight.implementedBy(Ambi))
- self.assertTrue(ILeft in implementedBy(Ambi))
- self.assertTrue(IRight in implementedBy(Ambi))
- self.assertTrue(ILeft in providedBy(ambi))
- self.assertTrue(IRight in providedBy(ambi))
+ self.assertIn(ILeft, implementedBy(Ambi))
+ self.assertIn(IRight, implementedBy(Ambi))
+ self.assertIn(ILeft, providedBy(ambi))
+ self.assertIn(IRight, providedBy(ambi))
def test_classImplements_multiple_w_explict_implements(self):
from zope.interface import Interface
@@ -1469,12 +1469,12 @@ class InterfaceTests(unittest.TestCase):
self.assertTrue(ILeft.implementedBy(Mixed))
self.assertFalse(IRight.implementedBy(Mixed))
self.assertTrue(IOther.implementedBy(Mixed))
- self.assertTrue(ILeft in implementedBy(Mixed))
- self.assertFalse(IRight in implementedBy(Mixed))
- self.assertTrue(IOther in implementedBy(Mixed))
- self.assertTrue(ILeft in providedBy(mixed))
- self.assertFalse(IRight in providedBy(mixed))
- self.assertTrue(IOther in providedBy(mixed))
+ self.assertIn(ILeft, implementedBy(Mixed))
+ self.assertNotIn(IRight, implementedBy(Mixed))
+ self.assertIn(IOther, implementedBy(Mixed))
+ self.assertIn(ILeft, providedBy(mixed))
+ self.assertNotIn(IRight, providedBy(mixed))
+ self.assertIn(IOther, providedBy(mixed))
def testInterfaceExtendsInterface(self):
from zope.interface import Interface
@@ -1594,11 +1594,11 @@ class InterfaceTests(unittest.TestCase):
self.assertEqual(len(name_values), 2)
self.assertEqual(name_values[0][0], 'attr')
- self.assertTrue(isinstance(name_values[0][1], Attribute))
+ self.assertIsInstance(name_values[0][1], Attribute)
self.assertEqual(name_values[0][1].__name__, 'attr')
self.assertEqual(name_values[0][1].__doc__, 'My attr')
self.assertEqual(name_values[1][0], 'method')
- self.assertTrue(isinstance(name_values[1][1], Method))
+ self.assertIsInstance(name_values[1][1], Method)
self.assertEqual(name_values[1][1].__name__, 'method')
self.assertEqual(name_values[1][1].__doc__, 'My method')
@@ -1626,15 +1626,15 @@ class InterfaceTests(unittest.TestCase):
self.assertEqual(len(name_values), 3)
self.assertEqual(name_values[0][0], 'attr2')
- self.assertTrue(isinstance(name_values[0][1], Attribute))
+ self.assertIsInstance(name_values[0][1], Attribute)
self.assertEqual(name_values[0][1].__name__, 'attr2')
self.assertEqual(name_values[0][1].__doc__, 'My attr2')
self.assertEqual(name_values[1][0], 'method')
- self.assertTrue(isinstance(name_values[1][1], Method))
+ self.assertIsInstance(name_values[1][1], Method)
self.assertEqual(name_values[1][1].__name__, 'method')
self.assertEqual(name_values[1][1].__doc__, 'My method, overridden')
self.assertEqual(name_values[2][0], 'method2')
- self.assertTrue(isinstance(name_values[2][1], Method))
+ self.assertIsInstance(name_values[2][1], Method)
self.assertEqual(name_values[2][1].__name__, 'method2')
self.assertEqual(name_values[2][1].__doc__, 'My method2')
@@ -1642,19 +1642,19 @@ class InterfaceTests(unittest.TestCase):
self.assertEqual(len(name_values), 4)
self.assertEqual(name_values[0][0], 'attr')
- self.assertTrue(isinstance(name_values[0][1], Attribute))
+ self.assertIsInstance(name_values[0][1], Attribute)
self.assertEqual(name_values[0][1].__name__, 'attr')
self.assertEqual(name_values[0][1].__doc__, 'My attr')
self.assertEqual(name_values[1][0], 'attr2')
- self.assertTrue(isinstance(name_values[1][1], Attribute))
+ self.assertIsInstance(name_values[1][1], Attribute)
self.assertEqual(name_values[1][1].__name__, 'attr2')
self.assertEqual(name_values[1][1].__doc__, 'My attr2')
self.assertEqual(name_values[2][0], 'method')
- self.assertTrue(isinstance(name_values[2][1], Method))
+ self.assertIsInstance(name_values[2][1], Method)
self.assertEqual(name_values[2][1].__name__, 'method')
self.assertEqual(name_values[2][1].__doc__, 'My method, overridden')
self.assertEqual(name_values[3][0], 'method2')
- self.assertTrue(isinstance(name_values[3][1], Method))
+ self.assertIsInstance(name_values[3][1], Method)
self.assertEqual(name_values[3][1].__name__, 'method2')
self.assertEqual(name_values[3][1].__doc__, 'My method2')
@@ -1678,12 +1678,12 @@ class InterfaceTests(unittest.TestCase):
"My method"
a_desc = ISimple.getDescriptionFor('attr')
- self.assertTrue(isinstance(a_desc, Attribute))
+ self.assertIsInstance(a_desc, Attribute)
self.assertEqual(a_desc.__name__, 'attr')
self.assertEqual(a_desc.__doc__, 'My attr')
m_desc = ISimple.getDescriptionFor('method')
- self.assertTrue(isinstance(m_desc, Method))
+ self.assertIsInstance(m_desc, Method)
self.assertEqual(m_desc.__name__, 'method')
self.assertEqual(m_desc.__doc__, 'My method')
@@ -1708,22 +1708,22 @@ class InterfaceTests(unittest.TestCase):
"My method2"
a_desc = IDerived.getDescriptionFor('attr')
- self.assertTrue(isinstance(a_desc, Attribute))
+ self.assertIsInstance(a_desc, Attribute)
self.assertEqual(a_desc.__name__, 'attr')
self.assertEqual(a_desc.__doc__, 'My attr')
m_desc = IDerived.getDescriptionFor('method')
- self.assertTrue(isinstance(m_desc, Method))
+ self.assertIsInstance(m_desc, Method)
self.assertEqual(m_desc.__name__, 'method')
self.assertEqual(m_desc.__doc__, 'My method, overridden')
a2_desc = IDerived.getDescriptionFor('attr2')
- self.assertTrue(isinstance(a2_desc, Attribute))
+ self.assertIsInstance(a2_desc, Attribute)
self.assertEqual(a2_desc.__name__, 'attr2')
self.assertEqual(a2_desc.__doc__, 'My attr2')
m2_desc = IDerived.getDescriptionFor('method2')
- self.assertTrue(isinstance(m2_desc, Method))
+ self.assertIsInstance(m2_desc, Method)
self.assertEqual(m2_desc.__name__, 'method2')
self.assertEqual(m2_desc.__doc__, 'My method2')
@@ -1747,12 +1747,12 @@ class InterfaceTests(unittest.TestCase):
"My method"
a_desc = ISimple['attr']
- self.assertTrue(isinstance(a_desc, Attribute))
+ self.assertIsInstance(a_desc, Attribute)
self.assertEqual(a_desc.__name__, 'attr')
self.assertEqual(a_desc.__doc__, 'My attr')
m_desc = ISimple['method']
- self.assertTrue(isinstance(m_desc, Method))
+ self.assertIsInstance(m_desc, Method)
self.assertEqual(m_desc.__name__, 'method')
self.assertEqual(m_desc.__doc__, 'My method')
@@ -1777,22 +1777,22 @@ class InterfaceTests(unittest.TestCase):
"My method2"
a_desc = IDerived['attr']
- self.assertTrue(isinstance(a_desc, Attribute))
+ self.assertIsInstance(a_desc, Attribute)
self.assertEqual(a_desc.__name__, 'attr')
self.assertEqual(a_desc.__doc__, 'My attr')
m_desc = IDerived['method']
- self.assertTrue(isinstance(m_desc, Method))
+ self.assertIsInstance(m_desc, Method)
self.assertEqual(m_desc.__name__, 'method')
self.assertEqual(m_desc.__doc__, 'My method, overridden')
a2_desc = IDerived['attr2']
- self.assertTrue(isinstance(a2_desc, Attribute))
+ self.assertIsInstance(a2_desc, Attribute)
self.assertEqual(a2_desc.__name__, 'attr2')
self.assertEqual(a2_desc.__doc__, 'My attr2')
m2_desc = IDerived['method2']
- self.assertTrue(isinstance(m2_desc, Method))
+ self.assertIsInstance(m2_desc, Method)
self.assertEqual(m2_desc.__name__, 'method2')
self.assertEqual(m2_desc.__doc__, 'My method2')
@@ -1802,7 +1802,7 @@ class InterfaceTests(unittest.TestCase):
class IEmpty(Interface):
pass
- self.assertFalse('nonesuch' in IEmpty)
+ self.assertNotIn('nonesuch', IEmpty)
def test___contains__simple(self):
from zope.interface import Attribute
@@ -1814,8 +1814,8 @@ class InterfaceTests(unittest.TestCase):
def method():
"My method"
- self.assertTrue('attr' in ISimple)
- self.assertTrue('method' in ISimple)
+ self.assertIn('attr', ISimple)
+ self.assertIn('method', ISimple)
def test___contains__derived(self):
from zope.interface import Attribute
@@ -1836,10 +1836,10 @@ class InterfaceTests(unittest.TestCase):
def method2():
"My method2"
- self.assertTrue('attr' in IDerived)
- self.assertTrue('method' in IDerived)
- self.assertTrue('attr2' in IDerived)
- self.assertTrue('method2' in IDerived)
+ self.assertIn('attr', IDerived)
+ self.assertIn('method', IDerived)
+ self.assertIn('attr2', IDerived)
+ self.assertIn('method2', IDerived)
def test___iter__empty(self):
from zope.interface import Interface
@@ -2223,10 +2223,10 @@ class InterfaceTests(unittest.TestCase):
class I3(I2):
pass
- self.assertTrue(I3.get('a') is I1.get('a'))
+ self.assertIs(I3.get('a'), I1.get('a'))
I2.__bases__ = (Interface,)
- self.assertTrue(I3.get('a') is None)
+ self.assertIsNone(I3.get('a'))
def test___call___defers_to___conform___(self):
from zope.interface import Interface
@@ -2254,7 +2254,7 @@ class InterfaceTests(unittest.TestCase):
pass
c = C()
- self.assertTrue(IFoo(c) is c)
+ self.assertIs(IFoo(c), c)
def test___call___miss_wo_alternate(self):
from zope.interface import Interface
@@ -2278,7 +2278,7 @@ class InterfaceTests(unittest.TestCase):
pass
c = C()
- self.assertTrue(IFoo(c, self) is self)
+ self.assertIs(IFoo(c, self), self)
def test___call___w_adapter_hook(self):
from zope.interface import Interface
@@ -2301,7 +2301,7 @@ class InterfaceTests(unittest.TestCase):
old_adapter_hooks = adapter_hooks[:]
adapter_hooks[:] = [_miss, _hit]
try:
- self.assertTrue(IFoo(c) is self)
+ self.assertIs(IFoo(c), self)
finally:
adapter_hooks[:] = old_adapter_hooks
diff --git a/contrib/python/zope.interface/py3/zope/interface/tests/test_interfaces.py b/contrib/python/zope.interface/py3/zope/interface/tests/test_interfaces.py
index 6c41d494129..a1006493afa 100644
--- a/contrib/python/zope.interface/py3/zope/interface/tests/test_interfaces.py
+++ b/contrib/python/zope.interface/py3/zope/interface/tests/test_interfaces.py
@@ -41,7 +41,7 @@ class ObjectEventTests(unittest.TestCase, _ConformsToIObjectEvent):
def test_ctor(self):
target = object()
event = self._makeOne(target)
- self.assertTrue(event.object is target)
+ self.assertIs(event.object, target)
class RegistrationEventTests(unittest.TestCase,
diff --git a/contrib/python/zope.interface/py3/zope/interface/tests/test_odd_declarations.py b/contrib/python/zope.interface/py3/zope/interface/tests/test_odd_declarations.py
index 75000ddb05f..b0f01e90842 100644
--- a/contrib/python/zope.interface/py3/zope/interface/tests/test_odd_declarations.py
+++ b/contrib/python/zope.interface/py3/zope/interface/tests/test_odd_declarations.py
@@ -94,8 +94,8 @@ class Test(unittest.TestCase):
self.assertEqual([i.getName() for i in providedBy(c).flattened()],
['I4', 'I31', 'I3', 'I1', 'I2', 'Interface']
)
- self.assertTrue(I1 in providedBy(c))
- self.assertFalse(I3 in providedBy(c))
+ self.assertIn(I1, providedBy(c))
+ self.assertNotIn(I3, providedBy(c))
self.assertTrue(providedBy(c).extends(I3))
self.assertTrue(providedBy(c).extends(I31))
self.assertFalse(providedBy(c).extends(I5))
@@ -116,8 +116,8 @@ class Test(unittest.TestCase):
['I4', 'I5', 'I31'])
self.assertEqual([i.getName() for i in providedBy(c).flattened()],
['I4', 'I5', 'I31', 'I3', 'Interface'])
- self.assertFalse(I1 in providedBy(c))
- self.assertFalse(I3 in providedBy(c))
+ self.assertNotIn(I1, providedBy(c))
+ self.assertNotIn(I3, providedBy(c))
self.assertTrue(providedBy(c).extends(I3))
self.assertFalse(providedBy(c).extends(I1))
self.assertTrue(providedBy(c).extends(I31))
@@ -138,8 +138,8 @@ class Test(unittest.TestCase):
['I4', 'I5', 'I31'])
self.assertEqual([i.getName() for i in providedBy(c).flattened()],
['I4', 'I5', 'I31', 'I3', 'Interface'])
- self.assertFalse(I1 in providedBy(c))
- self.assertFalse(I3 in providedBy(c))
+ self.assertNotIn(I1, providedBy(c))
+ self.assertNotIn(I3, providedBy(c))
self.assertTrue(providedBy(c).extends(I3))
self.assertFalse(providedBy(c).extends(I1))
self.assertTrue(providedBy(c).extends(I31))
@@ -211,19 +211,19 @@ class Test(unittest.TestCase):
ob = C()
directlyProvides(ob, I1, I2)
- self.assertTrue(I1 in providedBy(ob))
- self.assertTrue(I2 in providedBy(ob))
- self.assertTrue(IA1 in providedBy(ob))
- self.assertTrue(IA2 in providedBy(ob))
- self.assertTrue(IB in providedBy(ob))
- self.assertTrue(IC in providedBy(ob))
+ self.assertIn(I1, providedBy(ob))
+ self.assertIn(I2, providedBy(ob))
+ self.assertIn(IA1, providedBy(ob))
+ self.assertIn(IA2, providedBy(ob))
+ self.assertIn(IB, providedBy(ob))
+ self.assertIn(IC, providedBy(ob))
directlyProvides(ob, directlyProvidedBy(ob) - I2)
- self.assertTrue(I1 in providedBy(ob))
- self.assertFalse(I2 in providedBy(ob))
- self.assertFalse(I2 in providedBy(ob))
+ self.assertIn(I1, providedBy(ob))
+ self.assertNotIn(I2, providedBy(ob))
+ self.assertNotIn(I2, providedBy(ob))
directlyProvides(ob, directlyProvidedBy(ob), I2)
- self.assertTrue(I2 in providedBy(ob))
+ self.assertIn(I2, providedBy(ob))
# see above
# def TODO_test_classProvides_fails_for_odd_class(self):
diff --git a/contrib/python/zope.interface/py3/zope/interface/tests/test_registry.py b/contrib/python/zope.interface/py3/zope/interface/tests/test_registry.py
index fbe1ed2b545..0da200ebedb 100644
--- a/contrib/python/zope.interface/py3/zope/interface/tests/test_registry.py
+++ b/contrib/python/zope.interface/py3/zope/interface/tests/test_registry.py
@@ -43,8 +43,8 @@ class ComponentsTests(unittest.TestCase):
comp = self._makeOne('testing')
self.assertEqual(comp.__name__, 'testing')
self.assertEqual(comp.__bases__, ())
- self.assertTrue(isinstance(comp.adapters, AdapterRegistry))
- self.assertTrue(isinstance(comp.utilities, AdapterRegistry))
+ self.assertIsInstance(comp.adapters, AdapterRegistry)
+ self.assertIsInstance(comp.utilities, AdapterRegistry)
self.assertEqual(comp.adapters.__bases__, ())
self.assertEqual(comp.utilities.__bases__, ())
self.assertEqual(comp._utility_registrations, {})
@@ -123,7 +123,7 @@ class ComponentsTests(unittest.TestCase):
_monkey, _events = self._wrapEvents()
with _monkey:
comp.registerUtility(_to_reg, ifoo, _name, _info)
- self.assertTrue(comp.utilities._adapters[0][ifoo][_name] is _to_reg)
+ self.assertIs(comp.utilities._adapters[0][ifoo][_name], _to_reg)
self.assertEqual(comp._utility_registrations[ifoo, _name],
(_to_reg, _info, None))
self.assertEqual(comp.utilities._subscribers[0][ifoo][''], (_to_reg,))
@@ -131,14 +131,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Registered))
- self.assertTrue(isinstance(event.object, UtilityRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.component is _to_reg)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is None)
+ self.assertIsInstance(event, Registered)
+ self.assertIsInstance(event.object, UtilityRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.component, _to_reg)
+ self.assertIs(event.object.info, _info)
+ self.assertIsNone(event.object.factory)
def test_registerUtility_w_factory(self):
from zope.interface.declarations import InterfaceClass
@@ -164,14 +164,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Registered))
- self.assertTrue(isinstance(event.object, UtilityRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.component is _to_reg)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is _factory)
+ self.assertIsInstance(event, Registered)
+ self.assertIsInstance(event.object, UtilityRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.component, _to_reg)
+ self.assertIs(event.object.info, _info)
+ self.assertIs(event.object.factory, _factory)
def test_registerUtility_no_provided_available(self):
@@ -210,14 +210,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Registered))
- self.assertTrue(isinstance(event.object, UtilityRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.component is _to_reg)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is None)
+ self.assertIsInstance(event, Registered)
+ self.assertIsInstance(event.object, UtilityRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.component, _to_reg)
+ self.assertIs(event.object.info, _info)
+ self.assertIsNone(event.object.factory)
def test_registerUtility_duplicates_existing_reg(self):
from zope.interface.declarations import InterfaceClass
@@ -305,25 +305,25 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, UtilityRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.component is _before)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is None)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, UtilityRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.component, _before)
+ self.assertIs(event.object.info, _info)
+ self.assertIsNone(event.object.factory)
args, kw = _events[1]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Registered))
- self.assertTrue(isinstance(event.object, UtilityRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.component is _after)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is None)
+ self.assertIsInstance(event, Registered)
+ self.assertIsInstance(event.object, UtilityRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.component, _after)
+ self.assertIs(event.object.info, _info)
+ self.assertIsNone(event.object.factory)
def test_registerUtility_w_existing_subscr(self):
from zope.interface.declarations import InterfaceClass
@@ -463,19 +463,19 @@ class ComponentsTests(unittest.TestCase):
unreg = comp.unregisterUtility(_to_reg, ifoo, _name)
self.assertTrue(unreg)
self.assertFalse(comp.utilities._adapters) # all erased
- self.assertFalse((ifoo, _name) in comp._utility_registrations)
+ self.assertNotIn((ifoo, _name), comp._utility_registrations)
self.assertFalse(comp.utilities._subscribers)
self.assertEqual(len(_events), 1)
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, UtilityRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.component is _to_reg)
- self.assertTrue(event.object.factory is None)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, UtilityRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.component, _to_reg)
+ self.assertIsNone(event.object.factory)
def test_unregisterUtility_w_factory(self):
from zope.interface.declarations import InterfaceClass
@@ -503,13 +503,13 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, UtilityRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.component is _to_reg)
- self.assertTrue(event.object.factory is _factory)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, UtilityRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.component, _to_reg)
+ self.assertIs(event.object.factory, _factory)
def test_unregisterUtility_wo_explicit_provided(self):
from zope.interface.declarations import InterfaceClass
@@ -538,14 +538,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, UtilityRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.component is _to_reg)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is None)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, UtilityRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.component, _to_reg)
+ self.assertIs(event.object.info, _info)
+ self.assertIsNone(event.object.factory)
def test_unregisterUtility_wo_component_or_factory(self):
from zope.interface.declarations import InterfaceClass
@@ -575,14 +575,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, UtilityRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.component is _to_reg)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is None)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, UtilityRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.component, _to_reg)
+ self.assertIs(event.object.info, _info)
+ self.assertIsNone(event.object.factory)
def test_unregisterUtility_w_existing_subscr(self):
from zope.interface.declarations import InterfaceClass
@@ -738,20 +738,20 @@ class ComponentsTests(unittest.TestCase):
comp.registerUtility(_to_reg, ifoo, _name2, _info)
reg = sorted(comp.registeredUtilities(), key=lambda r: r.name)
self.assertEqual(len(reg), 2)
- self.assertTrue(isinstance(reg[0], UtilityRegistration))
- self.assertTrue(reg[0].registry is comp)
- self.assertTrue(reg[0].provided is ifoo)
- self.assertTrue(reg[0].name is _name1)
- self.assertTrue(reg[0].component is _to_reg)
- self.assertTrue(reg[0].info is _info)
- self.assertTrue(reg[0].factory is None)
- self.assertTrue(isinstance(reg[1], UtilityRegistration))
- self.assertTrue(reg[1].registry is comp)
- self.assertTrue(reg[1].provided is ifoo)
- self.assertTrue(reg[1].name is _name2)
- self.assertTrue(reg[1].component is _to_reg)
- self.assertTrue(reg[1].info is _info)
- self.assertTrue(reg[1].factory is None)
+ self.assertIsInstance(reg[0], UtilityRegistration)
+ self.assertIs(reg[0].registry, comp)
+ self.assertIs(reg[0].provided, ifoo)
+ self.assertIs(reg[0].name, _name1)
+ self.assertIs(reg[0].component, _to_reg)
+ self.assertIs(reg[0].info, _info)
+ self.assertIsNone(reg[0].factory)
+ self.assertIsInstance(reg[1], UtilityRegistration)
+ self.assertIs(reg[1].registry, comp)
+ self.assertIs(reg[1].provided, ifoo)
+ self.assertIs(reg[1].name, _name2)
+ self.assertIs(reg[1].component, _to_reg)
+ self.assertIs(reg[1].info, _info)
+ self.assertIsNone(reg[1].factory)
def test_queryUtility_miss_no_default(self):
from zope.interface.declarations import InterfaceClass
@@ -761,7 +761,7 @@ class ComponentsTests(unittest.TestCase):
ifoo = IFoo('IFoo')
comp = self._makeOne()
- self.assertTrue(comp.queryUtility(ifoo) is None)
+ self.assertIsNone(comp.queryUtility(ifoo))
def test_queryUtility_miss_w_default(self):
from zope.interface.declarations import InterfaceClass
@@ -772,7 +772,7 @@ class ComponentsTests(unittest.TestCase):
ifoo = IFoo('IFoo')
comp = self._makeOne()
_default = object()
- self.assertTrue(comp.queryUtility(ifoo, default=_default) is _default)
+ self.assertIs(comp.queryUtility(ifoo, default=_default), _default)
def test_queryUtility_hit(self):
from zope.interface.declarations import InterfaceClass
@@ -784,7 +784,7 @@ class ComponentsTests(unittest.TestCase):
_to_reg = object()
comp = self._makeOne()
comp.registerUtility(_to_reg, ifoo)
- self.assertTrue(comp.queryUtility(ifoo) is _to_reg)
+ self.assertIs(comp.queryUtility(ifoo), _to_reg)
def test_getUtility_miss(self):
from zope.interface.declarations import InterfaceClass
@@ -807,7 +807,7 @@ class ComponentsTests(unittest.TestCase):
_to_reg = object()
comp = self._makeOne()
comp.registerUtility(_to_reg, ifoo)
- self.assertTrue(comp.getUtility(ifoo) is _to_reg)
+ self.assertIs(comp.getUtility(ifoo), _to_reg)
def test_getUtilitiesFor_miss(self):
from zope.interface.declarations import InterfaceClass
@@ -902,22 +902,24 @@ class ComponentsTests(unittest.TestCase):
_monkey, _events = self._wrapEvents()
with _monkey:
comp.registerAdapter(_factory, (ibar,), ifoo, _name, _info)
- self.assertTrue(comp.adapters._adapters[1][ibar][ifoo][_name]
- is _factory)
+ self.assertIs(
+ comp.adapters._adapters[1][ibar][ifoo][_name],
+ _factory
+ )
self.assertEqual(comp._adapter_registrations[(ibar,), ifoo, _name],
(_factory, _info))
self.assertEqual(len(_events), 1)
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Registered))
- self.assertTrue(isinstance(event.object, AdapterRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Registered)
+ self.assertIsInstance(event.object, AdapterRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (ibar,))
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is _factory)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.info, _info)
+ self.assertIs(event.object.factory, _factory)
def test_registerAdapter_no_provided_available(self):
from zope.interface.declarations import InterfaceClass
@@ -958,22 +960,24 @@ class ComponentsTests(unittest.TestCase):
_monkey, _events = self._wrapEvents()
with _monkey:
comp.registerAdapter(_Factory, (ibar,), name=_name, info=_info)
- self.assertTrue(comp.adapters._adapters[1][ibar][ifoo][_name]
- is _Factory)
+ self.assertIs(
+ comp.adapters._adapters[1][ibar][ifoo][_name],
+ _Factory
+ )
self.assertEqual(comp._adapter_registrations[(ibar,), ifoo, _name],
(_Factory, _info))
self.assertEqual(len(_events), 1)
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Registered))
- self.assertTrue(isinstance(event.object, AdapterRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Registered)
+ self.assertIsInstance(event.object, AdapterRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (ibar,))
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is _Factory)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.info, _info)
+ self.assertIs(event.object.factory, _Factory)
def test_registerAdapter_no_required_available(self):
from zope.interface.declarations import InterfaceClass
@@ -1032,8 +1036,9 @@ class ComponentsTests(unittest.TestCase):
with _monkey:
comp.registerAdapter(_Factory, [None], provided=ifoo,
name=_name, info=_info)
- self.assertTrue(
- comp.adapters._adapters[1][Interface][ifoo][_name] is _Factory
+ self.assertIs(
+ comp.adapters._adapters[1][Interface][ifoo][_name],
+ _Factory
)
self.assertEqual(
comp._adapter_registrations[(Interface,), ifoo, _name],
@@ -1043,14 +1048,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Registered))
- self.assertTrue(isinstance(event.object, AdapterRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Registered)
+ self.assertIsInstance(event.object, AdapterRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (Interface,))
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is _Factory)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.info, _info)
+ self.assertIs(event.object.factory, _Factory)
def test_registerAdapter_w_required_containing_class(self):
from zope.interface.declarations import InterfaceClass
@@ -1080,8 +1085,9 @@ class ComponentsTests(unittest.TestCase):
with _monkey:
comp.registerAdapter(_Factory, [_Context], provided=ifoo,
name=_name, info=_info)
- self.assertTrue(
- comp.adapters._adapters[1][_ctx_impl][ifoo][_name] is _Factory
+ self.assertIs(
+ comp.adapters._adapters[1][_ctx_impl][ifoo][_name],
+ _Factory
)
self.assertEqual(
comp._adapter_registrations[(_ctx_impl,), ifoo, _name],
@@ -1091,14 +1097,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Registered))
- self.assertTrue(isinstance(event.object, AdapterRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Registered)
+ self.assertIsInstance(event.object, AdapterRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (_ctx_impl,))
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is _Factory)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.info, _info)
+ self.assertIs(event.object.factory, _Factory)
def test_registerAdapter_w_required_containing_junk(self):
from zope.interface.declarations import InterfaceClass
@@ -1141,22 +1147,24 @@ class ComponentsTests(unittest.TestCase):
with _monkey:
comp.registerAdapter(_Factory, provided=ifoo, name=_name,
info=_info)
- self.assertTrue(comp.adapters._adapters[1][ibar][ifoo][_name]
- is _Factory)
+ self.assertIs(
+ comp.adapters._adapters[1][ibar][ifoo][_name],
+ _Factory
+ )
self.assertEqual(comp._adapter_registrations[(ibar,), ifoo, _name],
(_Factory, _info))
self.assertEqual(len(_events), 1)
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Registered))
- self.assertTrue(isinstance(event.object, AdapterRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Registered)
+ self.assertIsInstance(event.object, AdapterRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (ibar,))
- self.assertTrue(event.object.name is _name)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is _Factory)
+ self.assertIs(event.object.name, _name)
+ self.assertIs(event.object.info, _info)
+ self.assertIs(event.object.factory, _Factory)
def test_registerAdapter_wo_event(self):
from zope.interface.declarations import InterfaceClass
@@ -1238,14 +1246,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, AdapterRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, AdapterRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (ibar,))
self.assertEqual(event.object.name, '')
self.assertEqual(event.object.info, '')
- self.assertTrue(event.object.factory is _Factory)
+ self.assertIs(event.object.factory, _Factory)
def test_unregisterAdapter_wo_explicit_provided(self):
from zope.interface.declarations import InterfaceClass
@@ -1273,14 +1281,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, AdapterRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, AdapterRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (ibar,))
self.assertEqual(event.object.name, '')
self.assertEqual(event.object.info, '')
- self.assertTrue(event.object.factory is _Factory)
+ self.assertIs(event.object.factory, _Factory)
def test_unregisterAdapter_wo_explicit_required(self):
from zope.interface.declarations import InterfaceClass
@@ -1306,14 +1314,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, AdapterRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, AdapterRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (ibar,))
self.assertEqual(event.object.name, '')
self.assertEqual(event.object.info, '')
- self.assertTrue(event.object.factory is _Factory)
+ self.assertIs(event.object.factory, _Factory)
def test_registeredAdapters_empty(self):
comp = self._makeOne()
@@ -1340,20 +1348,20 @@ class ComponentsTests(unittest.TestCase):
comp.registerAdapter(_Factory, (ibar,), ifoo, _name2, _info)
reg = sorted(comp.registeredAdapters(), key=lambda r: r.name)
self.assertEqual(len(reg), 2)
- self.assertTrue(isinstance(reg[0], AdapterRegistration))
- self.assertTrue(reg[0].registry is comp)
- self.assertTrue(reg[0].provided is ifoo)
+ self.assertIsInstance(reg[0], AdapterRegistration)
+ self.assertIs(reg[0].registry, comp)
+ self.assertIs(reg[0].provided, ifoo)
self.assertEqual(reg[0].required, (ibar,))
- self.assertTrue(reg[0].name is _name1)
- self.assertTrue(reg[0].info is _info)
- self.assertTrue(reg[0].factory is _Factory)
- self.assertTrue(isinstance(reg[1], AdapterRegistration))
- self.assertTrue(reg[1].registry is comp)
- self.assertTrue(reg[1].provided is ifoo)
+ self.assertIs(reg[0].name, _name1)
+ self.assertIs(reg[0].info, _info)
+ self.assertIs(reg[0].factory, _Factory)
+ self.assertIsInstance(reg[1], AdapterRegistration)
+ self.assertIs(reg[1].registry, comp)
+ self.assertIs(reg[1].provided, ifoo)
self.assertEqual(reg[1].required, (ibar,))
- self.assertTrue(reg[1].name is _name2)
- self.assertTrue(reg[1].info is _info)
- self.assertTrue(reg[1].factory is _Factory)
+ self.assertIs(reg[1].name, _name2)
+ self.assertIs(reg[1].info, _info)
+ self.assertIs(reg[1].factory, _Factory)
def test_queryAdapter_miss_no_default(self):
from zope.interface.declarations import InterfaceClass
@@ -1364,7 +1372,7 @@ class ComponentsTests(unittest.TestCase):
ifoo = IFoo('IFoo')
comp = self._makeOne()
_context = object()
- self.assertTrue(comp.queryAdapter(_context, ifoo) is None)
+ self.assertIsNone(comp.queryAdapter(_context, ifoo))
def test_queryAdapter_miss_w_default(self):
from zope.interface.declarations import InterfaceClass
@@ -1376,8 +1384,10 @@ class ComponentsTests(unittest.TestCase):
comp = self._makeOne()
_context = object()
_default = object()
- self.assertTrue(
- comp.queryAdapter(_context, ifoo, default=_default) is _default)
+ self.assertIs(
+ comp.queryAdapter(_context, ifoo, default=_default),
+ _default
+ )
def test_queryAdapter_hit(self):
from zope.interface.declarations import InterfaceClass
@@ -1401,8 +1411,8 @@ class ComponentsTests(unittest.TestCase):
comp = self._makeOne()
comp.registerAdapter(_Factory, (ibar,), ifoo)
adapter = comp.queryAdapter(_context, ifoo)
- self.assertTrue(isinstance(adapter, _Factory))
- self.assertTrue(adapter.context is _context)
+ self.assertIsInstance(adapter, _Factory)
+ self.assertIs(adapter.context, _context)
def test_getAdapter_miss(self):
from zope.interface.declarations import InterfaceClass
@@ -1590,9 +1600,11 @@ class ComponentsTests(unittest.TestCase):
_context2 = _Context2()
_default = object()
comp = self._makeOne()
- self.assertTrue(
+ self.assertIs(
comp.queryMultiAdapter((_context1, _context2), ifoo,
- default=_default) is _default)
+ default=_default),
+ _default
+ )
def test_queryMultiAdapter_hit(self):
from zope.interface.declarations import InterfaceClass
@@ -1623,7 +1635,7 @@ class ComponentsTests(unittest.TestCase):
comp = self._makeOne()
comp.registerAdapter(_Factory, (ibar, ibaz), ifoo)
adapter = comp.queryMultiAdapter((_context1, _context2), ifoo)
- self.assertTrue(isinstance(adapter, _Factory))
+ self.assertIsInstance(adapter, _Factory)
self.assertEqual(adapter.context, (_context1, _context2))
def test_getMultiAdapter_miss(self):
@@ -1681,7 +1693,7 @@ class ComponentsTests(unittest.TestCase):
comp = self._makeOne()
comp.registerAdapter(_Factory, (ibar, ibaz), ifoo)
adapter = comp.getMultiAdapter((_context1, _context2), ifoo)
- self.assertTrue(isinstance(adapter, _Factory))
+ self.assertIsInstance(adapter, _Factory)
self.assertEqual(adapter.context, (_context1, _context2))
def _should_not_change(self, comp):
@@ -1837,9 +1849,9 @@ class ComponentsTests(unittest.TestCase):
found = sorted(comp.getAdapters((_context1, _context2), ifoo))
self.assertEqual(len(found), 2)
self.assertEqual(found[0][0], _name1)
- self.assertTrue(isinstance(found[0][1], _Factory1))
+ self.assertIsInstance(found[0][1], _Factory1)
self.assertEqual(found[1][0], _name2)
- self.assertTrue(isinstance(found[1][1], _Factory2))
+ self.assertIsInstance(found[1][1], _Factory2)
def test_registerSubscriptionAdapter_w_nonblank_name(self):
from zope.interface.declarations import InterfaceClass
@@ -1882,21 +1894,21 @@ class ComponentsTests(unittest.TestCase):
info=_info)
reg = comp.adapters._subscribers[1][ibar][ifoo][_blank]
self.assertEqual(len(reg), 1)
- self.assertTrue(reg[0] is _factory)
+ self.assertIs(reg[0], _factory)
self.assertEqual(comp._subscription_registrations,
[((ibar,), ifoo, _blank, _factory, _info)])
self.assertEqual(len(_events), 1)
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Registered))
- self.assertTrue(isinstance(event.object, SubscriptionRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Registered)
+ self.assertIsInstance(event.object, SubscriptionRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (ibar,))
self.assertEqual(event.object.name, _blank)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is _factory)
+ self.assertIs(event.object.info, _info)
+ self.assertIs(event.object.factory, _factory)
def test_registerSubscriptionAdapter_wo_explicit_provided(self):
from zope.interface.declarations import InterfaceClass
@@ -1922,21 +1934,21 @@ class ComponentsTests(unittest.TestCase):
comp.registerSubscriptionAdapter(_Factory, (ibar,), info=_info)
reg = comp.adapters._subscribers[1][ibar][ifoo][_blank]
self.assertEqual(len(reg), 1)
- self.assertTrue(reg[0] is _Factory)
+ self.assertIs(reg[0], _Factory)
self.assertEqual(comp._subscription_registrations,
[((ibar,), ifoo, _blank, _Factory, _info)])
self.assertEqual(len(_events), 1)
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Registered))
- self.assertTrue(isinstance(event.object, SubscriptionRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Registered)
+ self.assertIsInstance(event.object, SubscriptionRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (ibar,))
self.assertEqual(event.object.name, _blank)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is _Factory)
+ self.assertIs(event.object.info, _info)
+ self.assertIs(event.object.factory, _Factory)
def test_registerSubscriptionAdapter_wo_explicit_required(self):
from zope.interface.declarations import InterfaceClass
@@ -1962,21 +1974,21 @@ class ComponentsTests(unittest.TestCase):
)
reg = comp.adapters._subscribers[1][ibar][ifoo][_blank]
self.assertEqual(len(reg), 1)
- self.assertTrue(reg[0] is _Factory)
+ self.assertIs(reg[0], _Factory)
self.assertEqual(comp._subscription_registrations,
[((ibar,), ifoo, _blank, _Factory, _info)])
self.assertEqual(len(_events), 1)
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Registered))
- self.assertTrue(isinstance(event.object, SubscriptionRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Registered)
+ self.assertIsInstance(event.object, SubscriptionRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (ibar,))
self.assertEqual(event.object.name, _blank)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is _Factory)
+ self.assertIs(event.object.info, _info)
+ self.assertIs(event.object.factory, _Factory)
def test_registerSubscriptionAdapter_wo_event(self):
from zope.interface.declarations import InterfaceClass
@@ -2022,20 +2034,20 @@ class ComponentsTests(unittest.TestCase):
comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo, info=_info)
reg = list(comp.registeredSubscriptionAdapters())
self.assertEqual(len(reg), 2)
- self.assertTrue(isinstance(reg[0], SubscriptionRegistration))
- self.assertTrue(reg[0].registry is comp)
- self.assertTrue(reg[0].provided is ifoo)
+ self.assertIsInstance(reg[0], SubscriptionRegistration)
+ self.assertIs(reg[0].registry, comp)
+ self.assertIs(reg[0].provided, ifoo)
self.assertEqual(reg[0].required, (ibar,))
self.assertEqual(reg[0].name, _blank)
- self.assertTrue(reg[0].info is _info)
- self.assertTrue(reg[0].factory is _Factory)
- self.assertTrue(isinstance(reg[1], SubscriptionRegistration))
- self.assertTrue(reg[1].registry is comp)
- self.assertTrue(reg[1].provided is ifoo)
+ self.assertIs(reg[0].info, _info)
+ self.assertIs(reg[0].factory, _Factory)
+ self.assertIsInstance(reg[1], SubscriptionRegistration)
+ self.assertIs(reg[1].registry, comp)
+ self.assertIs(reg[1].provided, ifoo)
self.assertEqual(reg[1].required, (ibar,))
self.assertEqual(reg[1].name, _blank)
- self.assertTrue(reg[1].info is _info)
- self.assertTrue(reg[1].factory is _Factory)
+ self.assertIs(reg[1].info, _info)
+ self.assertIs(reg[1].factory, _Factory)
def test_unregisterSubscriptionAdapter_w_nonblank_name(self):
from zope.interface.declarations import InterfaceClass
@@ -2111,14 +2123,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, SubscriptionRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, SubscriptionRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (ibar,))
self.assertEqual(event.object.name, '')
self.assertEqual(event.object.info, '')
- self.assertTrue(event.object.factory is None)
+ self.assertIsNone(event.object.factory)
def test_unregisterSubscriptionAdapter_hit_w_factory(self):
from zope.interface.declarations import InterfaceClass
@@ -2146,14 +2158,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, SubscriptionRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, SubscriptionRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (ibar,))
self.assertEqual(event.object.name, '')
self.assertEqual(event.object.info, '')
- self.assertTrue(event.object.factory is _Factory)
+ self.assertIs(event.object.factory, _Factory)
def test_unregisterSubscriptionAdapter_wo_explicit_provided(self):
from zope.interface.declarations import InterfaceClass
@@ -2181,14 +2193,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, SubscriptionRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, SubscriptionRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (ibar,))
self.assertEqual(event.object.name, '')
self.assertEqual(event.object.info, '')
- self.assertTrue(event.object.factory is _Factory)
+ self.assertIs(event.object.factory, _Factory)
def test_unregisterSubscriptionAdapter_wo_explicit_required(self):
from zope.interface.declarations import InterfaceClass
@@ -2214,14 +2226,14 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, SubscriptionRegistration))
- self.assertTrue(event.object.registry is comp)
- self.assertTrue(event.object.provided is ifoo)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, SubscriptionRegistration)
+ self.assertIs(event.object.registry, comp)
+ self.assertIs(event.object.provided, ifoo)
self.assertEqual(event.object.required, (ibar,))
self.assertEqual(event.object.name, '')
self.assertEqual(event.object.info, '')
- self.assertTrue(event.object.factory is _Factory)
+ self.assertIs(event.object.factory, _Factory)
def test_subscribers_empty(self):
from zope.interface.declarations import InterfaceClass
@@ -2276,8 +2288,8 @@ class ComponentsTests(unittest.TestCase):
subscribers = sorted(subscribers, key=_klassname)
self.assertEqual(len(subscribers), 2)
- self.assertTrue(isinstance(subscribers[0], _Derived))
- self.assertTrue(isinstance(subscribers[1], _Factory))
+ self.assertIsInstance(subscribers[0], _Derived)
+ self.assertIsInstance(subscribers[1], _Factory)
def test_registerHandler_w_nonblank_name(self):
from zope.interface.declarations import InterfaceClass
@@ -2316,20 +2328,20 @@ class ComponentsTests(unittest.TestCase):
comp.registerHandler(_factory, (ifoo,), info=_info)
reg = comp.adapters._subscribers[1][ifoo][None][_blank]
self.assertEqual(len(reg), 1)
- self.assertTrue(reg[0] is _factory)
+ self.assertIs(reg[0], _factory)
self.assertEqual(comp._handler_registrations,
[((ifoo,), _blank, _factory, _info)])
self.assertEqual(len(_events), 1)
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Registered))
- self.assertTrue(isinstance(event.object, HandlerRegistration))
- self.assertTrue(event.object.registry is comp)
+ self.assertIsInstance(event, Registered)
+ self.assertIsInstance(event.object, HandlerRegistration)
+ self.assertIs(event.object.registry, comp)
self.assertEqual(event.object.required, (ifoo,))
self.assertEqual(event.object.name, _blank)
- self.assertTrue(event.object.info is _info)
- self.assertTrue(event.object.factory is _factory)
+ self.assertIs(event.object.info, _info)
+ self.assertIs(event.object.factory, _factory)
def test_registerHandler_wo_explicit_required_no_event(self):
from zope.interface.declarations import InterfaceClass
@@ -2351,7 +2363,7 @@ class ComponentsTests(unittest.TestCase):
comp.registerHandler(_Factory, info=_info, event=False)
reg = comp.adapters._subscribers[1][ifoo][None][_blank]
self.assertEqual(len(reg), 1)
- self.assertTrue(reg[0] is _Factory)
+ self.assertIs(reg[0], _Factory)
self.assertEqual(comp._handler_registrations,
[((ifoo,), _blank, _Factory, _info)])
self.assertEqual(len(_events), 0)
@@ -2384,12 +2396,12 @@ class ComponentsTests(unittest.TestCase):
subscribers = sorted(comp.registeredHandlers(), key=_factory_name)
self.assertEqual(len(subscribers), 2)
- self.assertTrue(isinstance(subscribers[0], HandlerRegistration))
+ self.assertIsInstance(subscribers[0], HandlerRegistration)
self.assertEqual(subscribers[0].required, (ifoo,))
self.assertEqual(subscribers[0].name, '')
self.assertEqual(subscribers[0].factory, _factory1)
self.assertEqual(subscribers[0].info, '')
- self.assertTrue(isinstance(subscribers[1], HandlerRegistration))
+ self.assertIsInstance(subscribers[1], HandlerRegistration)
self.assertEqual(subscribers[1].required, (ifoo,))
self.assertEqual(subscribers[1].name, '')
self.assertEqual(subscribers[1].factory, _factory2)
@@ -2446,12 +2458,12 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, HandlerRegistration))
- self.assertTrue(event.object.registry is comp)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, HandlerRegistration)
+ self.assertIs(event.object.registry, comp)
self.assertEqual(event.object.required, (ifoo,))
self.assertEqual(event.object.name, '')
- self.assertTrue(event.object.factory is _factory)
+ self.assertIs(event.object.factory, _factory)
def test_unregisterHandler_hit_w_only_explicit_provided(self):
from zope.interface.declarations import InterfaceClass
@@ -2477,12 +2489,12 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, HandlerRegistration))
- self.assertTrue(event.object.registry is comp)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, HandlerRegistration)
+ self.assertIs(event.object.registry, comp)
self.assertEqual(event.object.required, (ifoo,))
self.assertEqual(event.object.name, '')
- self.assertTrue(event.object.factory is None)
+ self.assertIsNone(event.object.factory)
def test_unregisterHandler_wo_explicit_required(self):
from zope.interface.declarations import InterfaceClass
@@ -2507,13 +2519,13 @@ class ComponentsTests(unittest.TestCase):
args, kw = _events[0]
event, = args
self.assertEqual(kw, {})
- self.assertTrue(isinstance(event, Unregistered))
- self.assertTrue(isinstance(event.object, HandlerRegistration))
- self.assertTrue(event.object.registry is comp)
+ self.assertIsInstance(event, Unregistered)
+ self.assertIsInstance(event.object, HandlerRegistration)
+ self.assertIs(event.object.registry, comp)
self.assertEqual(event.object.required, (ifoo,))
self.assertEqual(event.object.name, '')
self.assertEqual(event.object.info, '')
- self.assertTrue(event.object.factory is _Factory)
+ self.assertIs(event.object.factory, _Factory)
def test_handle_empty(self):
from zope.interface.declarations import InterfaceClass
@@ -2802,38 +2814,38 @@ class UtilityRegistrationTests(unittest.TestCase):
def test___eq___identity(self):
_component = object()
ur, _registry, _name = self._makeOne(_component)
- self.assertTrue(ur == ur)
+ self.assertEqual(ur, ur)
def test___eq___hit(self):
_component = object()
ur, _registry, _name = self._makeOne(_component)
ur2, _, _ = self._makeOne(_component)
- self.assertTrue(ur == ur2)
+ self.assertEqual(ur, ur2)
def test___eq___miss(self):
_component = object()
_component2 = object()
ur, _registry, _name = self._makeOne(_component)
ur2, _, _ = self._makeOne(_component2)
- self.assertFalse(ur == ur2)
+ self.assertNotEqual(ur, ur2)
def test___ne___identity(self):
_component = object()
ur, _registry, _name = self._makeOne(_component)
- self.assertFalse(ur != ur)
+ self.assertEqual(ur, ur)
def test___ne___hit(self):
_component = object()
ur, _registry, _name = self._makeOne(_component)
ur2, _, _ = self._makeOne(_component)
- self.assertFalse(ur != ur2)
+ self.assertEqual(ur, ur2)
def test___ne___miss(self):
_component = object()
_component2 = object()
ur, _registry, _name = self._makeOne(_component)
ur2, _, _ = self._makeOne(_component2)
- self.assertTrue(ur != ur2)
+ self.assertNotEqual(ur, ur2)
def test___lt___identity(self):
_component = object()
@@ -2852,18 +2864,18 @@ class UtilityRegistrationTests(unittest.TestCase):
ur, _registry, _name = self._makeOne(_component)
ur2, _, _ = self._makeOne(_component2)
ur2.name = _name + '2'
- self.assertTrue(ur < ur2)
+ self.assertLess(ur, ur2)
def test___le___identity(self):
_component = object()
ur, _registry, _name = self._makeOne(_component)
- self.assertTrue(ur <= ur)
+ self.assertLessEqual(ur, ur)
def test___le___hit(self):
_component = object()
ur, _registry, _name = self._makeOne(_component)
ur2, _, _ = self._makeOne(_component)
- self.assertTrue(ur <= ur2)
+ self.assertLessEqual(ur, ur2)
def test___le___miss(self):
_component = object()
@@ -2871,7 +2883,7 @@ class UtilityRegistrationTests(unittest.TestCase):
ur, _registry, _name = self._makeOne(_component)
ur2, _, _ = self._makeOne(_component2)
ur2.name = _name + '2'
- self.assertTrue(ur <= ur2)
+ self.assertLessEqual(ur, ur2)
def test___gt___identity(self):
_component = object()
@@ -2884,7 +2896,7 @@ class UtilityRegistrationTests(unittest.TestCase):
ur, _registry, _name = self._makeOne(_component)
ur2, _, _ = self._makeOne(_component2)
ur2.name = _name + '2'
- self.assertTrue(ur2 > ur)
+ self.assertGreater(ur2, ur)
def test___gt___miss(self):
_component = object()
@@ -2895,7 +2907,7 @@ class UtilityRegistrationTests(unittest.TestCase):
def test___ge___identity(self):
_component = object()
ur, _registry, _name = self._makeOne(_component)
- self.assertTrue(ur >= ur)
+ self.assertGreaterEqual(ur, ur)
def test___ge___miss(self):
_component = object()
@@ -2910,7 +2922,7 @@ class UtilityRegistrationTests(unittest.TestCase):
ur, _registry, _name = self._makeOne(_component)
ur2, _, _ = self._makeOne(_component)
ur2.name = _name + '2'
- self.assertTrue(ur2 >= ur)
+ self.assertGreaterEqual(ur2, ur)
class AdapterRegistrationTests(unittest.TestCase):
@@ -3007,38 +3019,38 @@ class AdapterRegistrationTests(unittest.TestCase):
def test___eq___identity(self):
_component = object()
ar, _registry, _name = self._makeOne(_component)
- self.assertTrue(ar == ar)
+ self.assertEqual(ar, ar)
def test___eq___hit(self):
_component = object()
ar, _registry, _name = self._makeOne(_component)
ar2, _, _ = self._makeOne(_component)
- self.assertTrue(ar == ar2)
+ self.assertEqual(ar, ar2)
def test___eq___miss(self):
_component = object()
_component2 = object()
ar, _registry, _name = self._makeOne(_component)
ar2, _, _ = self._makeOne(_component2)
- self.assertFalse(ar == ar2)
+ self.assertNotEqual(ar, ar2)
def test___ne___identity(self):
_component = object()
ar, _registry, _name = self._makeOne(_component)
- self.assertFalse(ar != ar)
+ self.assertEqual(ar, ar)
def test___ne___miss(self):
_component = object()
ar, _registry, _name = self._makeOne(_component)
ar2, _, _ = self._makeOne(_component)
- self.assertFalse(ar != ar2)
+ self.assertEqual(ar, ar2)
def test___ne___hit_component(self):
_component = object()
_component2 = object()
ar, _registry, _name = self._makeOne(_component)
ar2, _, _ = self._makeOne(_component2)
- self.assertTrue(ar != ar2)
+ self.assertNotEqual(ar, ar2)
def test___ne___hit_provided(self):
from zope.interface.declarations import InterfaceClass
@@ -3051,7 +3063,7 @@ class AdapterRegistrationTests(unittest.TestCase):
ar, _registry, _name = self._makeOne(_component)
ar2, _, _ = self._makeOne(_component)
ar2.provided = ibaz
- self.assertTrue(ar != ar2)
+ self.assertNotEqual(ar, ar2)
def test___ne___hit_required(self):
from zope.interface.declarations import InterfaceClass
@@ -3065,7 +3077,7 @@ class AdapterRegistrationTests(unittest.TestCase):
ar, _registry, _name = self._makeOne(_component)
ar2, _, _ = self._makeOne(_component2)
ar2.required = (ibaz,)
- self.assertTrue(ar != ar2)
+ self.assertNotEqual(ar, ar2)
def test___lt___identity(self):
_component = object()
@@ -3084,18 +3096,18 @@ class AdapterRegistrationTests(unittest.TestCase):
ar, _registry, _name = self._makeOne(_component)
ar2, _, _ = self._makeOne(_component2)
ar2.name = _name + '2'
- self.assertTrue(ar < ar2)
+ self.assertLess(ar, ar2)
def test___le___identity(self):
_component = object()
ar, _registry, _name = self._makeOne(_component)
- self.assertTrue(ar <= ar)
+ self.assertLessEqual(ar, ar)
def test___le___hit(self):
_component = object()
ar, _registry, _name = self._makeOne(_component)
ar2, _, _ = self._makeOne(_component)
- self.assertTrue(ar <= ar2)
+ self.assertLessEqual(ar, ar2)
def test___le___miss(self):
_component = object()
@@ -3103,7 +3115,7 @@ class AdapterRegistrationTests(unittest.TestCase):
ar, _registry, _name = self._makeOne(_component)
ar2, _, _ = self._makeOne(_component2)
ar2.name = _name + '2'
- self.assertTrue(ar <= ar2)
+ self.assertLessEqual(ar, ar2)
def test___gt___identity(self):
_component = object()
@@ -3116,7 +3128,7 @@ class AdapterRegistrationTests(unittest.TestCase):
ar, _registry, _name = self._makeOne(_component)
ar2, _, _ = self._makeOne(_component2)
ar2.name = _name + '2'
- self.assertTrue(ar2 > ar)
+ self.assertGreater(ar2, ar)
def test___gt___miss(self):
_component = object()
@@ -3127,7 +3139,7 @@ class AdapterRegistrationTests(unittest.TestCase):
def test___ge___identity(self):
_component = object()
ar, _registry, _name = self._makeOne(_component)
- self.assertTrue(ar >= ar)
+ self.assertGreaterEqual(ar, ar)
def test___ge___miss(self):
_component = object()
@@ -3142,7 +3154,7 @@ class AdapterRegistrationTests(unittest.TestCase):
ar, _registry, _name = self._makeOne(_component)
ar2, _, _ = self._makeOne(_component)
ar2.name = _name + '2'
- self.assertTrue(ar2 >= ar)
+ self.assertGreaterEqual(ar2, ar)
class SubscriptionRegistrationTests(unittest.TestCase):
@@ -3229,9 +3241,9 @@ class HandlerRegistrationTests(unittest.TestCase):
def _factory(context):
raise NotImplementedError()
hr, _, _ = self._makeOne(_factory)
- self.assertTrue(hr.handler is _factory)
- self.assertTrue(hr.factory is hr.handler)
- self.assertTrue(hr.provided is None)
+ self.assertIs(hr.handler, _factory)
+ self.assertIs(hr.factory, hr.handler)
+ self.assertIsNone(hr.provided)
def test___repr___factory_w_name(self):