From 6a49dfd6b90455a2f3e7a8a0a3d6746189cbb4bc Mon Sep 17 00:00:00 2001 From: Stefaan Lippens Date: Thu, 4 Mar 2021 16:04:43 +0100 Subject: [PATCH] Issue #41: strip Sphinx cross-referencing syntax from reason in warning message --- CHANGELOG.rst | 2 ++ deprecated/sphinx.py | 19 +++++++++++++++++++ tests/test_sphinx.py | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 5a5f79e..efc6975 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -36,6 +36,8 @@ Other - Change in Tox and Travis CI configurations: enable unit testing on Python 3.10. +- Fix #41: ``deprecated.sphinx``: strip Sphinx cross-referencing syntax from warning message. + v1.2.11 (2021-01-17) ==================== diff --git a/deprecated/sphinx.py b/deprecated/sphinx.py index b6f9b50..f5e1a4c 100644 --- a/deprecated/sphinx.py +++ b/deprecated/sphinx.py @@ -134,6 +134,25 @@ def __call__(self, wrapped): return wrapped return super(SphinxAdapter, self).__call__(wrapped) + def get_deprecated_msg(self, wrapped, instance): + """ + Get the deprecation warning message (without Sphinx cross-referencing syntax) for the user. + + :param wrapped: Wrapped class or function. + + :param instance: The object to which the wrapped function was bound when it was called. + + :return: The warning message. + + .. versionchanged:: 1.2.12 + Strip Sphinx cross-referencing syntax from warning message. + + """ + msg = super(SphinxAdapter, self).get_deprecated_msg(wrapped, instance) + # Strip Sphinx cross reference syntax (like ":function:", ":py:func:" and ":py:meth:") + msg = re.sub(r"(:[a-z]{2,3})?:[a-z]{2,8}:(`.*?`)", r"\2", msg) + return msg + def versionadded(reason="", version="", line_length=70): """ diff --git a/tests/test_sphinx.py b/tests/test_sphinx.py index 20c9b01..e6749a7 100644 --- a/tests/test_sphinx.py +++ b/tests/test_sphinx.py @@ -361,3 +361,38 @@ def test_can_catch_warnings(): warnings.simplefilter("always") warnings.warn("A message in a bottle", category=DeprecationWarning, stacklevel=2) assert len(warns) == 1 + + +@pytest.mark.parametrize( + ["reason", "expected"], + [ + ( + "Use :function:`bar` instead", + "Use `bar` instead" + ), + ( + "Use :py:func:`bar` instead", + "Use `bar` instead"), + ( + "Use :py:meth:`Bar.bar` instead", + "Use `Bar.bar` instead"), + ( + "Use :py:class:`Bar` instead", + "Use `Bar` instead" + ), + ( + "Use :py:func:`bar` or :py:meth:`Bar.bar` instead", + "Use `bar` or `Bar.bar` instead" + ), + ] +) +def test_sphinx_syntax_trimming(reason, expected): + + @deprecated.sphinx.deprecated(version="4.5.6", reason=reason) + def foo(): + pass + + with warnings.catch_warnings(record=True) as warns: + foo() + warn = warns[0] + assert expected in str(warn.message)