Files
EventHubBack/test/unit/admin_utils_tests.erl
T
2026-07-13 14:53:51 +03:00

38 lines
1.3 KiB
Erlang

-module(admin_utils_tests).
-include_lib("eunit/include/eunit.hrl").
client_ip_test_() ->
{setup,
fun() -> ok = meck:new(cowboy_req, [non_strict]) end,
fun(_) -> meck:unload(cowboy_req) end,
[
{"Uses X-Forwarded-For when present", fun test_forwarded_for/0},
{"Falls back to X-Real-IP", fun test_real_ip/0},
{"Falls back to peer address", fun test_peer_fallback/0},
{"ip_to_binary handles IPv4 tuple", fun test_ipv4_tuple/0}
]}.
test_forwarded_for() ->
ok = meck:expect(cowboy_req, header, fun
(<<"x-forwarded-for">>, _) -> <<"203.0.113.10, 10.0.0.1">>;
(_, _) -> undefined
end),
ok = meck:expect(cowboy_req, peer, fun(_) -> {10, 0, 0, 2} end),
?assertEqual(<<"203.0.113.10">>, admin_utils:client_ip(req)).
test_real_ip() ->
ok = meck:expect(cowboy_req, header, fun
(<<"x-real-ip">>, _) -> <<"198.51.100.5">>;
(_, _) -> undefined
end),
ok = meck:expect(cowboy_req, peer, fun(_) -> {10, 0, 0, 2} end),
?assertEqual(<<"198.51.100.5">>, admin_utils:client_ip(req)).
test_peer_fallback() ->
ok = meck:expect(cowboy_req, header, fun(_, _) -> undefined end),
ok = meck:expect(cowboy_req, peer, fun(_) -> {127, 0, 0, 1} end),
?assertEqual(<<"127.0.0.1">>, admin_utils:client_ip(req)).
test_ipv4_tuple() ->
?assertEqual(<<"192.168.1.1">>, admin_utils:ip_to_binary({192, 168, 1, 1})).