packages feed

cabal-buck2-0.6.0.0: buck2/prelude/erlang/common_test/common/src/ct_error_printer.erl

%% Copyright (c) Meta Platforms, Inc. and affiliates.
%%
%% This source code is licensed under both the MIT license found in the
%% LICENSE-MIT file in the root directory of this source tree and the Apache
%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
%% of this source tree.

%% @format
-module(ct_error_printer).
-moduledoc """
Helper module to format errors arising from common_test executions,
in particular as generated by the assert.hrl module.
""".
-compile([warn_missing_spec_all]).

%% Public API
-export([format_error/2, format_error/3, format_reason/1]).

-import(common_util, [unicode_characters_to_binary/1, unicode_characters_to_list/1]).

-spec format_error(term(), boolean()) -> unicode:chardata().
format_error(Reason, FormatStackTrace) ->
    format_error(error, Reason, FormatStackTrace).

-spec format_error(ErrorType, Reason, FormatStackTrace) -> unicode:chardata() when
    ErrorType :: error | exit | throw,
    Reason :: term(),
    FormatStackTrace :: boolean().
format_error(_ErrType, {'EXIT', Reason}, FormatStackTrace) ->
    format_error(Reason, FormatStackTrace);
format_error(ErrType, Err = {Reason, StackTrace}, true) when is_list(StackTrace) ->
    case format_reason(Err) of
        {ok, Output} ->
            ErrReason =
                case Reason of
                    {Type, _} -> Type;
                    _ -> exception
                end,
            ["\n", Output, erl_error:format_exception(ErrType, ErrReason, StackTrace)];
        unrecognized_error ->
            erl_error:format_exception(ErrType, Reason, StackTrace)
    end;
format_error(ErrType, Reason, true) ->
    format_error(ErrType, Reason, false);
format_error(ErrType, Reason, false) ->
    case format_reason(Reason) of
        {ok, Output} ->
            Output;
        unrecognized_error ->
            erl_error:format_exception(ErrType, Reason, [])
    end.

-spec format_reason(term()) -> {ok, unicode:chardata()} | unrecognized_error.
format_reason(Reason) ->
    blame_reason(Reason),
    {_, Result} = lists:foldl(
        fun try_format_if_necessary/2,
        {Reason, unrecognized_error},
        [
            fun maybe_custom_format/1,
            fun maybe_proper_format/1,
            fun maybe_assert_format/1
        ]
    ),
    Result.

-spec try_format_if_necessary(Formatter, Acc) -> Acc when
    Formatter :: fun((Reason) -> {ok, unicode:chardata()} | unrecognized_error),
    Acc :: {Reason, {ok, unicode:chardata()} | unrecognized_error},
    Reason :: term().
try_format_if_necessary(_Formatter, Acc = {_, {ok, _}}) -> Acc;
try_format_if_necessary(Formatter, {Reason, _Err}) -> {Reason, Formatter(Reason)}.

-spec blame_reason(term()) -> ok.
blame_reason({Reason, StackTrace}) ->
    try
        case application:get_env(common, exception_blame) of
            undefined ->
                ok;
            {ok, Blame} when is_atom(Blame) ->
                Blame:format_blame(Reason, StackTrace)
        end
    catch
        C:E:S ->
            io:format("Error: ~ts", [erl_error:format_exception(C, E, S)])
    end;
blame_reason(_Reason) ->
    ok.

-spec maybe_custom_format(term()) -> unrecognized_error | {ok, unicode:chardata()}.
maybe_custom_format({{Type, Props}, StackTrace}) when is_atom(Type), is_list(Props) ->
    try proplists:to_map(Props) of
        PropsMap -> maybe_custom_format({{Type, PropsMap}, StackTrace})
    catch
        _:_:_ -> unrecognized_error
    end;
maybe_custom_format({{Type, Props = #{formatter := Formatter}}, _StackTrace}) when is_atom(Formatter) ->
    try
        Formatter:format_assert(Type, Props)
    catch
        E:R:ST ->
            {ok, [
                io_lib:format(
                    "unexpected error when formatting assertion: ~n"
                    "~ts~n",
                    [erl_error:format_exception(E, R, ST)]
                ),
                io_lib:format("original assertion: ~n" "~tp~n", [{Type, Props}])
            ]}
    end;
maybe_custom_format(_Reason) ->
    unrecognized_error.

-spec maybe_assert_format(term()) -> unrecognized_error | {ok, unicode:chardata()}.
maybe_assert_format({{Type, Props}, _StackTrace}) -> format_assert(Type, Props);
maybe_assert_format(_Reason) -> unrecognized_error.

-doc """
Try to correctly format an error arising from a
failed assertion, see
https://github.com/erlang/otp/blob/master/bootstrap/lib/stdlib/include/assert.hrl
for the different type of errors raised depending of which macro was used.
""".
-spec format_assert(term(), term()) -> unrecognized_error | {ok, unicode:chardata()}.
format_assert(Type, Props) when is_list(Props) andalso is_atom(Type) ->
    try proplists:to_map(Props) of
        Map -> format_assert0(Type, Map)
    catch
        _:_:_ -> unrecognized_error
    end;
format_assert(_Type, _Props) ->
    unrecognized_error.

% For this macro to work we expect as local variable
% Type, Module, Line and Props
-define(FORMAT_ASSERTION(Format, Expressions, SpecificExpressions),
    {ok, [
        print_type_expression(Type, Format, Expressions),
        print_location(Module, Line),
        SpecificExpressions,
        print_comments(
            Props, string:chr(unicode_characters_to_list(lists:nth(1, SpecificExpressions)), $:)
        )
    ]}
).

-spec format_assert0(atom(), map()) -> unrecognized_error | {ok, unicode:chardata()}.
format_assert0(
    assert = Type,
    #{not_boolean := Value} = Props
) ->
    NewProps = maps:remove(not_boolean, Props),
    format_assert0(Type, NewProps#{value => Value});
format_assert0(
    assert = Type1,
    #{
        line := Line,
        module := Module,
        expression := Expression,
        expected := Expected,
        value := Value
    } = Props
) ->
    % assertNot as formatted as assert, so we need to debug that here.
    Type =
        case Expected of
            true -> Type1;
            false -> assertNot
        end,
    ?FORMAT_ASSERTION(
        "~ts",
        [Expression],
        [
            io_lib:format("   expected: ~tp~n", [Expected]),
            io_lib:format("        got: ~tp~n", [Value])
        ]
    );
format_assert0(
    assertEqual = Type,
    #{
        line := Line,
        module := Module,
        expression := Expression,
        expected := Expected,
        value := Value
    } = Props
) ->
    ?FORMAT_ASSERTION(
        "~0tp, ~ts",
        [Expected, Expression],
        [
            io_lib:format("   expected: ~tp~n", [Expected]),
            io_lib:format("        got: ~tp~n", [Value])
        ]
    );
format_assert0(
    Type,
    #{line := Line, module := Module, expression := Expression, pattern := Pattern, value := Value} =
        Props
) when
    Type =:= assertMatch orelse Type =:= assertNotMatch
->
    ?FORMAT_ASSERTION(
        "~ts, ~ts",
        [Pattern, Expression],
        [
            case Type of
                assertMatch ->
                    io_lib:format("     expected: ~ts~n", [Pattern]);
                assertNotMatch ->
                    io_lib:format(" expected not: ~ts~n", [Pattern])
            end,
            io_lib:format("          got: ~tp~n", [Value])
        ]
    );
format_assert0(
    assertNotEqual = Type,
    #{line := Line, module := Module, expression := Expression, value := Value} = Props
) ->
    ?FORMAT_ASSERTION(
        "~tp, ~ts",
        [Value, Expression],
        [
            io_lib:format(" expected not: ~tp~n", [Value]),
            io_lib:format("          got: ~tp~n", [Value])
        ]
    );
format_assert0(
    assertException = Type,
    #{module := Module, line := Line, expression := Expression, pattern := Pattern} = Props
) ->
    ValueLine =
        case Props of
            #{unexpected_success := Value} ->
                io_lib:format("          got value: ~tp~n", [Value]);
            #{unexpected_exception := {Class, Reason, StackTrace} = _Exception} ->
                io_lib:format(
                    "      got exception: ~tp ~n",
                    [{Class, Reason, StackTrace}]
                );
            _ ->
                unrecognized_error
        end,
    case ValueLine of
        unrecognized_error ->
            ValueLine;
        _ ->
            ?FORMAT_ASSERTION(
                "~ts, ~tp",
                [Pattern, Expression],
                [
                    io_lib:format(" expected exception: ~ts~n", [Pattern]),
                    ValueLine
                ]
            )
    end;
format_assert0(
    assertNotException = Type,
    #{
        module := Module,
        line := Line,
        expression := Expression,
        pattern := Pattern,
        unexpected_exception := {Class, Reason, StackTrace}
    } = Props
) ->
    ?FORMAT_ASSERTION(
        "~tp",
        [Expression],
        [
            io_lib:format(" expected no exception: ~tp~n", [Pattern]),
            io_lib:format("         got exception: ~ts~n", [
                erl_error:format_exception(Class, Reason, StackTrace)
            ])
        ]
    );
format_assert0(_Type, _Props) ->
    unrecognized_error.

-spec print_type_expression(atom(), string(), [term()]) -> unicode:chardata().
print_type_expression(Type, Format, Args) ->
    FormatStr = unicode_characters_to_binary(io_lib:format("Failure ?~tp(~ts)", [Type, Format])),
    io_lib:format(FormatStr, Args).

-spec print_location(atom(), integer()) -> unicode:chardata().
print_location(Module, Line) ->
    io_lib:format(" in ~tp.erl:~tp~n", [Module, Line]).

-spec print_comments(map(), integer()) -> unicode:chardata().
print_comments(#{comment := Comment}, Width) ->
    [io_lib:format("~*.. s ~tp~n", [Width, "comment:", Comment])];
print_comments(_Map, _Width) ->
    [].

-spec maybe_proper_format(term()) -> unrecognized_error | {ok, unicode:chardata()}.
maybe_proper_format({{property_failed, Property, Counterexample}, _ST}) ->
    {ok,
        io_lib:format(
            "Property ~ts failed with Counterexample: ~n~tp~n",
            [Property, Counterexample]
        )};
maybe_proper_format(_) ->
    unrecognized_error.