I have the following function with unit tests:
#!/usr/bin/env python3
# https://docs.python.org/3/library/ipaddress.html
# https://docs.python.org/3.4/library/unittest.html
import ipaddress
import unittest
from unittest.mock import patch
from unittest import TestCase
def validate_IP():
"""Prompt user for IPv4 address, then validate."""
while True:
try:
return ipaddress.IPv4Address(input('Enter a valid IPv4 address: '))
except ValueError:
print('Bad value, try again.')
class validate_IP_Test(unittest.TestCase):
@patch('builtins.input', return_value='192.168.1.1')
def test_validate_IP_01(self, input):
self.assertIsInstance(validate_IP(), ipaddress.IPv4Address)
@patch('builtins.input', return_value='10.0.0.1')
def test_validate_IP_02(self, input):
self.assertIsInstance(validate_IP(), ipaddress.IPv4Address)
@patch('builtins.input', return_value='Derp!')
def test_validate_IP_03(self, input):
self.assertRaises(ValueError, msg=none)
if __name__ == '__main__':
unittest.main()
The function uses the ipaddress
module in Python3 to validate user input, i.e. checks that user input is an actual IPv4 address
. My first two tests work as expected. I'm not clear, though, on how to test for invalid input using Python3's unittest
module for the exception portion of the function, as in the third test.
When invalid input is entered, the test should recognize that an exception was thrown and pass the test. For reference, here's the relevant output from an interpreter when I enter an invalid address:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File
raise AddressValueError("Expected 4 octets in %r" % ip_str)
ipaddress.AddressValueError: Expected 4 octets in 'derp'`