-module(admin_handler_user_verification_token_tests). -include_lib("eunit/include/eunit.hrl"). -include("records.hrl"). -define(TABLES, [admin, admin_audit, user, verification, ticket]). -define(ADMIN_ID, <<"adm_test_1">>). setup() -> eh_test_support:start_mnesia(), eh_test_support:ensure_tables(?TABLES), eh_test_support:ensure_jwt(), eh_test_support:seed_admin(#{id => ?ADMIN_ID}), ok. cleanup(_) -> eh_test_support:unload_cowboy(), eh_test_support:delete_tables(?TABLES), eh_test_support:stop_mnesia(), ok. admin_user_verification_token_test_() -> {foreach, fun setup/0, fun cleanup/1, [ {"GET – create token", {timeout, 60, fun test_create/0}}, {"GET – reuse existing token", {timeout, 60, fun test_reuse/0}}, {"GET – user not found", {timeout, 60, fun test_not_found/0}}, {"GET – unauthorized", {timeout, 60, fun test_unauthorized/0}}, {"POST – method not allowed", {timeout, 60, fun test_wrong_method/0}} ]}. seed_user() -> User = eh_test_support:make_user(#{ id => <<"u_verify">>, email => <<"verify@test.local">>, nickname => <<"verify">>, status => pending }), ok = mnesia:dirty_write(User), User. test_create() -> User = seed_user(), Id = User#user.id, {Status, _, Body} = eh_test_support:call(admin_handler_user_verification_token, #{ method => <<"GET">>, path => <<"/v1/admin/users/", Id/binary, "/verification-token">>, bindings => #{id => Id}, auth => ?ADMIN_ID }), ?assertEqual(200, Status), Result = jsx:decode(Body, [return_maps]), ?assert(is_binary(maps:get(<<"token">>, Result))), ?assert(is_binary(maps:get(<<"expires_at">>, Result))). test_reuse() -> User = seed_user(), Id = User#user.id, {ok, Token1, _} = core_verification:create_token(Id), {Status, _, Body} = eh_test_support:call(admin_handler_user_verification_token, #{ method => <<"GET">>, path => <<"/v1/admin/users/", Id/binary, "/verification-token">>, bindings => #{id => Id}, auth => ?ADMIN_ID }), ?assertEqual(200, Status), Result = jsx:decode(Body, [return_maps]), ?assertEqual(Token1, maps:get(<<"token">>, Result)). test_not_found() -> {Status, _, _} = eh_test_support:call(admin_handler_user_verification_token, #{ method => <<"GET">>, path => <<"/v1/admin/users/missing/verification-token">>, bindings => #{id => <<"missing">>}, auth => ?ADMIN_ID }), ?assertEqual(404, Status). test_unauthorized() -> {Status, _, _} = eh_test_support:call(admin_handler_user_verification_token, #{ method => <<"GET">>, path => <<"/v1/admin/users/x/verification-token">>, bindings => #{id => <<"x">>}, auth => none }), ?assertEqual(401, Status). test_wrong_method() -> {Status, _, _} = eh_test_support:call(admin_handler_user_verification_token, #{ method => <<"POST">>, path => <<"/v1/admin/users/x/verification-token">>, bindings => #{id => <<"x">>}, auth => ?ADMIN_ID }), ?assertEqual(405, Status).