From cf8970dad24dfa480b88be69fd305b5d5f36b7a0 Mon Sep 17 00:00:00 2001 From: SpiveeWorks Date: Fri, 24 Jan 2025 16:17:25 +1100 Subject: [PATCH] Add unit tests for some simple coercions --- src/hz.erl | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/src/hz.erl b/src/hz.erl index 0001cef..017ca71 100644 --- a/src/hz.erl +++ b/src/hz.erl @@ -77,6 +77,7 @@ -export_type([chain_node/0, network_id/0, chain_error/0]). +-include_lib("eunit/include/eunit.hrl"). -type chain_node() :: {inet:ip_address(), inet:port_number()}. -type network_id() :: string(). @@ -2140,3 +2141,58 @@ eu(N, Size) -> % /v3/debug/check-tx/pool/{hash} % /v3/debug/token-supply/height/{height} % /v3/debug/crash + + +try_coerce(Type, Sophia, Fate) -> + FateActual = coerce(Type, Sophia, to_fate), + SophiaActual = coerce(Type, Fate, from_fate), + case {ok, Fate} == FateActual of + true -> + ok; + false -> + erlang:error({to_fate_failed, Fate, FateActual}) + end, + case {ok, Sophia} == SophiaActual of + true -> + ok; + false -> + erlang:error({from_fate_failed, Sophia, SophiaActual}) + end, + ok. + +coerce_int_test() -> + {ok, Type} = flatten_opaque_type(integer, #{}), + try_coerce(Type, 123, 123). + +coerce_record_test() -> + {ok, Type} = flatten_opaque_type({record, [{"a", integer}, {"b", integer}]}, #{}), + try_coerce(Type, #{"a" => 123, "b" => 456}, {tuple, {123, 456}}). + +aaci_from_string(String) -> + case so_compiler:from_string(String, [{aci, json}]) of + {ok, #{aci := ACI}} -> {ok, prepare_aaci(ACI)}; + Error -> Error + end. + +record_substitution_test() -> + Contract = " + contract C = + record pair('t) = { a : 't, b : 't } + entrypoint f(): pair(int) = { a = 1, b = 2 } + ", + {ok, AACI} = aaci_from_string(Contract), + {ok, {[], Output}} = aaci_lookup_spec(AACI, "f"), + try_coerce(Output, #{"a" => 123, "b" => 456}, {tuple, {123, 456}}). + +namespace_coerce_test() -> + Contract = " + namespace N = + record pair = { a : int, b : int } + + contract C = + entrypoint f(): N.pair = { a = 1, b = 2 } + ", + {ok, AACI} = aaci_from_string(Contract), + {ok, {[], Output}} = aaci_lookup_spec(AACI, "f"), + try_coerce(Output, #{"a" => 123, "b" => 456}, {tuple, {123, 456}}). +