Rewrite and expand EUnit suite; run unit tests in CI from shared test image. Refs EventHub/EventHubBack#36 [skip ci]

This commit is contained in:
2026-07-17 15:16:46 +03:00
parent 9d2780fef4
commit 4fa802702f
54 changed files with 4240 additions and 2281 deletions
+115 -103
View File
@@ -2,122 +2,134 @@
-include_lib("eunit/include/eunit.hrl").
-include("records.hrl").
-define(JWT_SECRET, <<"test-user-secret-key-32-byt!">>).
-define(ADMIN_JWT_SECRET, <<"test-admin-secret-key-32-b">>).
-define(TABLES, [admin, admin_audit, auth_session, ticket]).
-define(EMAIL, <<"admin@test.local">>).
-define(PASSWORD, <<"SecretPass1!">>).
setup() ->
ok = meck:new(logic_auth, [non_strict]),
ok = meck:new(cowboy_req, [non_strict]),
ok = meck:new(core_admin, [non_strict]),
ok = meck:new(admin_utils, [non_strict]),
mnesia:start(),
catch ets:new(eventhub_counters, [named_table, public, set, {write_concurrency, true}]),
mnesia:create_table(auth_session, [
{attributes, record_info(fields, auth_session)},
{ram_copies, [node()]}
]),
mnesia:add_table_index(auth_session, #auth_session.family_id),
mnesia:add_table_index(auth_session, #auth_session.subject_id),
application:set_env(eventhub, jwt_secret, ?JWT_SECRET),
application:set_env(eventhub, admin_jwt_secret, ?ADMIN_JWT_SECRET),
{ok, _} = application:ensure_all_started(jose).
eh_test_support:start_mnesia(),
eh_test_support:ensure_tables(?TABLES),
eh_test_support:ensure_jwt(),
catch application:ensure_all_started(argon2),
catch ets:new(eventhub_counters, [named_table, public, set, {write_concurrency, true}]),
ok.
cleanup(_) ->
application:unset_env(eventhub, jwt_secret),
application:unset_env(eventhub, admin_jwt_secret),
application:stop(jose),
catch mnesia:delete_table(auth_session),
catch ets:delete(eventhub_counters),
mnesia:stop(),
meck:unload(admin_utils),
meck:unload(core_admin),
meck:unload(cowboy_req),
meck:unload(logic_auth),
ok.
eh_test_support:unload_cowboy(),
eh_test_support:delete_tables(?TABLES),
eh_test_support:stop_mnesia(),
ok.
admin_handler_login_test_() ->
{setup, fun setup/0, fun cleanup/1, [
{"Valid admin login returns 200 and token", fun test_valid_admin_login/0},
{"Invalid credentials return 401", fun test_invalid_credentials/0},
{"Nonadmin role returns 403", fun test_insufficient_permissions/0},
{"Malformed JSON returns 400", fun test_malformed_json/0},
{"Missing body returns 400", fun test_missing_body/0},
{"Wrong HTTP method returns 405", fun test_wrong_method/0}
]}.
admin_login_test_() ->
{foreach, fun setup/0, fun cleanup/1, [
{"POST login success", fun test_login_ok/0},
{"POST login bad credentials", fun test_login_bad_credentials/0},
{"POST login insufficient permissions", fun test_login_forbidden_role/0},
{"POST login missing fields", fun test_login_missing_fields/0},
{"POST login missing body", fun test_login_missing_body/0},
{"POST login invalid JSON", fun test_login_invalid_json/0},
{"GET login method not allowed", fun test_login_wrong_method/0}
]}.
%% ── Вспомогательная функция для создания запроса и ожидания reply ──
prepare_req(Method, HasBody, Body) ->
ok = meck:expect(cowboy_req, method, fun(_) -> Method end),
ok = meck:expect(cowboy_req, has_body, fun(_) -> HasBody end),
case {HasBody, Body} of
{true, undefined} -> ok;
{true, _} ->
ok = meck:expect(cowboy_req, read_body,
fun(Req) -> {ok, Body, Req} end);
{false, _} -> ok
end,
% Устанавливаем мок на reply, который сохраняет ответ в словаре процесса
meck:expect(cowboy_req, reply,
fun(Code, Headers, RespBody, Req) ->
put(test_reply, {Code, Headers, RespBody}),
Req
end),
req.
%% argon2 is a Rust NIF; rebar hooks only build it on unix. Skip hash-dependent
%% cases when the NIF is unavailable (common on Windows without cargo).
argon2_ready() ->
case catch argon2:hash(<<"probe">>) of
{ok, _} -> true;
_ -> false
end.
%% ── Тесты ────────────────────────────────────────────────────
require_argon2(Fun) ->
case argon2_ready() of
true -> Fun();
false -> {skip, "argon2 NIF not available"}
end.
test_valid_admin_login() ->
UserMap = #{id => <<"adm1">>, email => <<"admin@test.com">>, role => <<"superadmin">>},
ok = meck:expect(logic_auth, authenticate_admin,
fun(<<"admin@test.com">>, <<"pass">>) -> {ok, UserMap} end),
ok = meck:expect(core_admin, update_last_login, fun(_) -> ok end),
ok = meck:expect(admin_utils, log_admin_action, fun(_, _, _, _, _, _) -> ok end),
Req0 = prepare_req(<<"POST">>, true, jsx:encode(#{email => <<"admin@test.com">>, password => <<"pass">>})),
{ok, _, _} = admin_handler_login:init(Req0, []),
{Code, Headers, Body} = get(test_reply),
?assertEqual(200, Code),
?assertEqual(<<"application/json">>, maps:get(<<"content-type">>, Headers)),
test_login_ok() ->
require_argon2(fun() ->
{ok, Admin} = core_admin:create(?EMAIL, ?PASSWORD, admin),
{Status, _, Body} = eh_test_support:call(admin_handler_login, #{
method => <<"POST">>,
path => <<"/v1/admin/login">>,
auth => none,
body => jsx:encode(#{<<"email">> => ?EMAIL, <<"password">> => ?PASSWORD})
}),
?assertEqual(200, Status),
Resp = jsx:decode(Body, [return_maps]),
?assert(is_map_key(<<"token">>, Resp)),
?assert(is_map_key(<<"refresh_token">>, Resp)),
?assertEqual(<<"superadmin">>, maps:get(<<"role">>, maps:get(<<"user">>, Resp))).
User = maps:get(<<"user">>, Resp),
?assertEqual(Admin#admin.id, maps:get(<<"id">>, User)),
?assertEqual(?EMAIL, maps:get(<<"email">>, User)),
?assertEqual(<<"admin">>, maps:get(<<"role">>, User)),
Audits = core_admin_audit:list(),
?assert(length(Audits) >= 1)
end).
test_invalid_credentials() ->
ok = meck:expect(logic_auth, authenticate_admin,
fun(_, _) -> {error, bad_credentials} end),
Req0 = prepare_req(<<"POST">>, true, jsx:encode(#{email => <<"bad@test.com">>, password => <<"wrong">>})),
{ok, _, _} = admin_handler_login:init(Req0, []),
{Code, _, Body} = get(test_reply),
?assertEqual(401, Code),
#{<<"error">> := <<"bad_credentials">>} = jsx:decode(Body, [return_maps]).
test_login_bad_credentials() ->
%% Unknown email does not need password verification.
{Status, _, Body} = eh_test_support:call(admin_handler_login, #{
method => <<"POST">>,
path => <<"/v1/admin/login">>,
auth => none,
body => jsx:encode(#{<<"email">> => <<"nobody@test.local">>, <<"password">> => <<"x">>})
}),
?assertEqual(401, Status),
#{<<"error">> := <<"invalid_credentials">>} = jsx:decode(Body, [return_maps]).
test_insufficient_permissions() ->
UserMap = #{id => <<"user1">>, email => <<"user@test.com">>, role => <<"user">>},
ok = meck:expect(logic_auth, authenticate_admin,
fun(_, _) -> {ok, UserMap} end),
Req0 = prepare_req(<<"POST">>, true, jsx:encode(#{email => <<"user@test.com">>, password => <<"pass">>})),
{ok, _, _} = admin_handler_login:init(Req0, []),
{Code, _, Body} = get(test_reply),
?assertEqual(403, Code),
#{<<"error">> := <<"insufficient_permissions">>} = jsx:decode(Body, [return_maps]).
test_login_forbidden_role() ->
require_argon2(fun() ->
{ok, Hash} = logic_auth:hash_password(?PASSWORD),
eh_test_support:seed_admin(#{
id => <<"adm_guest">>,
email => <<"guest@test.local">>,
password_hash => Hash,
role => guest
}),
{Status, _, Body} = eh_test_support:call(admin_handler_login, #{
method => <<"POST">>,
path => <<"/v1/admin/login">>,
auth => none,
body => jsx:encode(#{
<<"email">> => <<"guest@test.local">>,
<<"password">> => ?PASSWORD
})
}),
?assertEqual(403, Status),
#{<<"error">> := <<"insufficient_permissions">>} = jsx:decode(Body, [return_maps])
end).
test_malformed_json() ->
Req0 = prepare_req(<<"POST">>, true, <<"not a json">>),
{ok, _, _} = admin_handler_login:init(Req0, []),
{Code, _, Body} = get(test_reply),
?assertEqual(400, Code),
#{<<"error">> := <<"Invalid JSON">>} = jsx:decode(Body, [return_maps]).
test_login_missing_fields() ->
{Status, _, _} = eh_test_support:call(admin_handler_login, #{
method => <<"POST">>,
path => <<"/v1/admin/login">>,
auth => none,
body => jsx:encode(#{<<"email">> => ?EMAIL})
}),
?assertEqual(400, Status).
test_missing_body() ->
Req0 = prepare_req(<<"POST">>, false, undefined),
{ok, _, _} = admin_handler_login:init(Req0, []),
{Code, _, Body} = get(test_reply),
?assertEqual(400, Code),
#{<<"error">> := <<"Missing request body">>} = jsx:decode(Body, [return_maps]).
test_login_missing_body() ->
{Status, _, _} = eh_test_support:call(admin_handler_login, #{
method => <<"POST">>,
path => <<"/v1/admin/login">>,
auth => none,
has_body => false
}),
?assertEqual(400, Status).
test_wrong_method() ->
Req0 = prepare_req(<<"GET">>, false, undefined),
{ok, _, _} = admin_handler_login:init(Req0, []),
{Code, _, Body} = get(test_reply),
?assertEqual(405, Code),
#{<<"error">> := <<"Method not allowed">>} = jsx:decode(Body, [return_maps]).
test_login_invalid_json() ->
{Status, _, _} = eh_test_support:call(admin_handler_login, #{
method => <<"POST">>,
path => <<"/v1/admin/login">>,
auth => none,
body => <<"not-json">>
}),
?assertEqual(400, Status).
test_login_wrong_method() ->
{Status, _, _} = eh_test_support:call(admin_handler_login, #{
method => <<"GET">>,
path => <<"/v1/admin/login">>,
auth => none
}),
?assertEqual(405, Status).