Commit fa4668e3 authored by Michal Vaner's avatar Michal Vaner
Browse files

Be more explicit about what is raised

And also raise something "nicer"

git-svn-id: svn://bind10.isc.org/svn/bind10/branches/trac353@3233 e5f2f494-b856-4b98-b285-d166d9295462
parent 8ec371d5
......@@ -16,12 +16,20 @@
"""Module where address representations live."""
import socket
class InvalidAddress(ValueError):
"""Exception for invalid addresses."""
pass
class IPAddr:
"""Stores an IPv4 or IPv6 address."""
family = None
addr = None
def __init__(self, addr):
"""
Creates the address object from a string representation. It raises
an InvalidAddr exception if the provided string isn't valid address.
"""
try:
a = socket.inet_pton(socket.AF_INET, addr)
self.family = socket.AF_INET
......@@ -35,8 +43,8 @@ class IPAddr:
self.family = socket.AF_INET6
self.addr = a
return
except Exception as e:
raise e
except socket.error as e:
raise InvalidAddress(str(e))
def __str__(self):
return socket.inet_ntop(self.family, self.addr)
......@@ -17,7 +17,7 @@
Checking and parsing of ports and IP addresses.
"""
from isc.net.addr import IPAddr
from isc.net.addr import IPAddr, InvalidAddress
import socket
def port_parse(port):
......@@ -43,6 +43,6 @@ def addr_parse(addr):
"""
try:
return IPAddr(addr)
except socket.error:
except InvalidAddress:
raise ValueError('Value ' + addr +
' is not valid IPv4 or IPv6 address')
......@@ -16,7 +16,7 @@
"""Tests for the isc.net.addr module."""
import unittest
import socket
from isc.net.addr import IPAddr
from isc.net.addr import IPAddr, InvalidAddress
class TestIPAddr(unittest.TestCase):
"""Test for the IPAddr class."""
......@@ -34,15 +34,15 @@ class TestIPAddr(unittest.TestCase):
def test_badaddr(self):
"""Test if we raise on wrong address."""
self.assertRaises(socket.error, IPAddr, 'foobar')
self.assertRaises(socket.error, IPAddr, 'foo::bar')
self.assertRaises(socket.error, IPAddr, '123')
self.assertRaises(socket.error, IPAddr, '123.456.789.0')
self.assertRaises(socket.error, IPAddr, '127/8')
self.assertRaises(socket.error, IPAddr, '0/0')
self.assertRaises(socket.error, IPAddr, '1.2.3.4/32')
self.assertRaises(socket.error, IPAddr, '0')
self.assertRaises(socket.error, IPAddr, '')
self.assertRaises(InvalidAddress, IPAddr, 'foobar')
self.assertRaises(InvalidAddress, IPAddr, 'foo::bar')
self.assertRaises(InvalidAddress, IPAddr, '123')
self.assertRaises(InvalidAddress, IPAddr, '123.456.789.0')
self.assertRaises(InvalidAddress, IPAddr, '127/8')
self.assertRaises(InvalidAddress, IPAddr, '0/0')
self.assertRaises(InvalidAddress, IPAddr, '1.2.3.4/32')
self.assertRaises(InvalidAddress, IPAddr, '0')
self.assertRaises(InvalidAddress, IPAddr, '')
if __name__ == '__main__':
unittest.main()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment