11from django .core .exceptions import ValidationError
22from django .forms import GenericIPAddressField
33from django .test import SimpleTestCase
4+ from django .utils .ipv6 import MAX_IPV6_ADDRESS_LENGTH
45
56
67class GenericIPAddressFieldTest (SimpleTestCase ):
@@ -125,6 +126,35 @@ def test_generic_ipaddress_as_ipv6_only(self):
125126 ):
126127 f .clean ("1:2" )
127128
129+ def test_generic_ipaddress_max_length_custom (self ):
130+ # Valid IPv4-mapped IPv6 address, len 45.
131+ addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228"
132+ f = GenericIPAddressField (max_length = len (addr ))
133+ f .clean (addr )
134+
135+ def test_generic_ipaddress_max_length_validation_error (self ):
136+ # Valid IPv4-mapped IPv6 address, len 45.
137+ addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228"
138+
139+ cases = [
140+ ({}, MAX_IPV6_ADDRESS_LENGTH ), # Default value.
141+ ({"max_length" : len (addr ) - 1 }, len (addr ) - 1 ),
142+ ]
143+ for kwargs , max_length in cases :
144+ max_length_plus_one = max_length + 1
145+ msg = (
146+ f"Ensure this value has at most { max_length } characters (it has "
147+ f"{ max_length_plus_one } ).'"
148+ )
149+ with self .subTest (max_length = max_length ):
150+ f = GenericIPAddressField (** kwargs )
151+ with self .assertRaisesMessage (ValidationError , msg ):
152+ f .clean ("x" * max_length_plus_one )
153+ with self .assertRaisesMessage (
154+ ValidationError , "This is not a valid IPv6 address."
155+ ):
156+ f .clean (addr )
157+
128158 def test_generic_ipaddress_as_generic_not_required (self ):
129159 f = GenericIPAddressField (required = False )
130160 self .assertEqual (f .clean ("" ), "" )
@@ -150,7 +180,8 @@ def test_generic_ipaddress_as_generic_not_required(self):
150180 f .clean (" fe80::223:6cff:fe8a:2e8a " ), "fe80::223:6cff:fe8a:2e8a"
151181 )
152182 self .assertEqual (
153- f .clean (" 2a02::223:6cff:fe8a:2e8a " ), "2a02::223:6cff:fe8a:2e8a"
183+ f .clean (" " * MAX_IPV6_ADDRESS_LENGTH + " 2a02::223:6cff:fe8a:2e8a " ),
184+ "2a02::223:6cff:fe8a:2e8a" ,
154185 )
155186 with self .assertRaisesMessage (
156187 ValidationError , "'This is not a valid IPv6 address.'"
0 commit comments