11from castle .test import unittest , mock
22from castle .extractors .ip import ExtractorsIp
3+ from castle .configuration import configuration
34
45
56def request_ip ():
@@ -22,7 +23,23 @@ def request_with_ip_remote_addr():
2223 return req
2324
2425
26+ def request_with_ip_x_forwarded_for ():
27+ req = mock .Mock (spec = ['environ' ])
28+ req .environ = {'HTTP_X_FORWARDED_FOR' : request_ip ()}
29+ return req
30+
31+
32+ def request_with_ip_cf_connecting_ip ():
33+ req = mock .Mock (spec = ['environ' ])
34+ req .environ = {'HTTP_CF_CONNECTING_IP' : request_ip_next ()}
35+ return req
36+
37+
2538class ExtractorsIpTestCase (unittest .TestCase ):
39+ @classmethod
40+ def tearDownClass (cls ):
41+ configuration .ip_headers = []
42+
2643 def test_extract_ip (self ):
2744 self .assertEqual (ExtractorsIp (request ()).call (), request_ip ())
2845
@@ -31,3 +48,19 @@ def test_extract_ip_from_wsgi_request_remote_addr(self):
3148 ExtractorsIp (request_with_ip_remote_addr ()).call (),
3249 request_ip ()
3350 )
51+
52+ def test_extract_ip_from_wsgi_request_configured_ip_header_first (self ):
53+ configuration .ip_headers = ["HTTP_CF_CONNECTING_IP" ]
54+ self .assertEqual (
55+ ExtractorsIp (request_with_ip_cf_connecting_ip ()).call (),
56+ request_ip_next ()
57+ )
58+ configuration .ip_headers = []
59+
60+ def test_extract_ip_from_wsgi_request_configured_ip_header_second (self ):
61+ configuration .ip_headers = ["HTTP_CF_CONNECTING_IP" , "HTTP_X_FORWARDED_FOR" ]
62+ self .assertEqual (
63+ ExtractorsIp (request_with_ip_x_forwarded_for ()).call (),
64+ request_ip ()
65+ )
66+ configuration .ip_headers = []
0 commit comments