Skip to content

Commit

Permalink
fix(richmap): hocon_schmea:richmap_to_map/1 failed on atom_key maps
Browse files Browse the repository at this point in the history
  • Loading branch information
terry-xiaoyu committed Jun 19, 2021
1 parent 8dda618 commit c770db9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
21 changes: 14 additions & 7 deletions src/hocon_schema.erl
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
-type loggerfunc() :: fun((atom(), map()) -> ok).
-type opts() :: #{ logger => loggerfunc()
, atom_key => boolean()
, return_plain => boolean()
%% By default allow all fields to be undefined.
%% if `nullable` is set to `false`
%% map or check APIs fail with validation_error.
Expand Down Expand Up @@ -255,7 +256,7 @@ check(Schema, Conf) ->
check(Schema, Conf, #{}).

check(Schema, Conf, Opts0) ->
Opts = maps:merge(#{atom_key => false}, Opts0),
Opts = maps:merge(#{is_richmap => true, atom_key => false}, Opts0),
do_check(Schema, Conf, Opts, all).

%% @doc Check plain-map input against schema.
Expand All @@ -282,12 +283,18 @@ do_check(Schema, Conf, Opts0, RootNames) ->
Opts = maps:merge(#{nullable => false}, Opts0),
%% discard mappings for check APIs
{_DiscardMappings, NewConf} = map(Schema, Conf, RootNames, Opts),
case maps:get(atom_key, Opts) of
true ->
atom_key_map(NewConf);
false ->
NewConf
end.
maybe_covert_keys_to_atom(
maybe_convert_to_plain_map(NewConf, Opts), Opts).

maybe_convert_to_plain_map(Conf, #{is_richmap := true, return_plain := true}) ->
richmap_to_map(Conf);
maybe_convert_to_plain_map(Conf, _Opts) ->
Conf.

maybe_covert_keys_to_atom(Conf, #{atom_key := true}) ->
atom_key_map(Conf);
maybe_covert_keys_to_atom(Conf, _Opts) ->
Conf.

-spec map(schema(), hocon:config()) -> {[proplists:property()], hocon:config()}.
map(Schema, Conf) ->
Expand Down
11 changes: 10 additions & 1 deletion test/hocon_schema_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,6 @@ richmap_to_map_test_() ->
#{<<"b">> => [1, 2, #{<<"x">> => <<"foo">>}]}}, F("a.b = [1,2,{x=foo}]"))
].


env_test_() ->
F = fun (Str, Envs) ->
{ok, M} = hocon:binary(Str, #{format => richmap}),
Expand Down Expand Up @@ -297,6 +296,16 @@ atom_key_array_test() ->
{ok, PlainMap} = hocon:binary(Conf, #{}),
?assertEqual(#{arr => [#{id => 1}, #{id => 2}]},
hocon_schema:check_plain(Sc, PlainMap, #{atom_key => true})).
return_plain_test() ->
Sc = #{structs => [?VIRTUAL_ROOT],
fields => [ {metadata, hoconsc:t(string())}
, {type, hoconsc:t(string())}
, {value, hoconsc:t(string())}
]},
StrConf = "type=t, metadata=m, value=v",
{ok, M} = hocon:binary(StrConf, #{format => richmap}),
?assertMatch(#{metadata := "m", type := "t", value := "v"},
hocon_schema:check(Sc, M, #{atom_key => true, return_plain => true})).

validator_test() ->
Sc = #{structs => [?VIRTUAL_ROOT],
Expand Down

0 comments on commit c770db9

Please sign in to comment.