34 lines
1.1 KiB
Python
34 lines
1.1 KiB
Python
"""utils/ip.py 客户端IP获取测试。"""
|
||
import types
|
||
|
||
from utils.ip import get_client_ip
|
||
|
||
|
||
def _make_request(client_host, xff=None):
|
||
"""构造模拟 Request 对象。"""
|
||
req = types.SimpleNamespace()
|
||
req.client = types.SimpleNamespace(host=client_host)
|
||
req.headers = {'X-Forwarded-For': xff} if xff else {}
|
||
return req
|
||
|
||
|
||
def test_xff_single_ip():
|
||
"""XFF 只有一个 IP → 直接返回"""
|
||
assert get_client_ip(_make_request('10.0.0.1', xff='1.2.3.4')) == '1.2.3.4'
|
||
|
||
|
||
def test_xff_multiple_ips_returns_leftmost():
|
||
"""XFF 多个 IP → 取最左侧(真实客户端 IP)"""
|
||
assert get_client_ip(_make_request('10.0.0.1', xff='1.2.3.4, 10.0.0.1')) == '1.2.3.4'
|
||
|
||
|
||
def test_no_xff_falls_back_to_client_host():
|
||
"""无 XFF 头 → 回退到 request.client.host"""
|
||
assert get_client_ip(_make_request('203.0.113.9')) == '203.0.113.9'
|
||
|
||
|
||
def test_no_client_falls_back_to_localhost():
|
||
"""client 为 None → 回退到 127.0.0.1"""
|
||
req = types.SimpleNamespace(client=None, headers={})
|
||
assert get_client_ip(req) == '127.0.0.1'
|