Commit 7d04315d authored by John L. Villalovos's avatar John L. Villalovos Committed by Nejc Habjan
Browse files

chore: add `show_caller` argument to `utils.warn()`

This allows us to not add the caller's location to the UserWarning
message.
parent 93586405
Loading
Loading
Loading
Loading
+4 −1
Original line number Diff line number Diff line
@@ -177,6 +177,7 @@ def warn(
    *,
    category: Optional[Type[Warning]] = None,
    source: Optional[Any] = None,
    show_caller: bool = True,
) -> None:
    """This `warnings.warn` wrapper function attempts to show the location causing the
    warning in the user code that called the library.
@@ -196,8 +197,10 @@ def warn(
        frame_dir = str(pathlib.Path(frame.filename).parent.resolve())
        if not frame_dir.startswith(str(pg_dir)):
            break
    if show_caller:
        message += warning_from
    warnings.warn(
        message=message + warning_from,
        message=message,
        category=category,
        stacklevel=stacklevel,
        source=source,
+21 −0
Original line number Diff line number Diff line
@@ -123,6 +123,27 @@ class TestWarningsWrapper:
        assert __file__ in str(warning.message)
        assert warn_source == warning.source

    def test_warn_no_show_caller(self):
        warn_message = "short and stout"
        warn_source = "teapot"

        with warnings.catch_warnings(record=True) as caught_warnings:
            utils.warn(
                message=warn_message,
                category=UserWarning,
                source=warn_source,
                show_caller=False,
            )
        assert len(caught_warnings) == 1
        warning = caught_warnings[0]
        # File name is this file as it is the first file outside of the `gitlab/` path.
        assert __file__ == warning.filename
        assert warning.category == UserWarning
        assert isinstance(warning.message, UserWarning)
        assert warn_message in str(warning.message)
        assert __file__ not in str(warning.message)
        assert warn_source == warning.source


@pytest.mark.parametrize(
    "source,expected",