How to unittest validation of arguments in argparse using assertRaises() in Python?

Viewed 43

When trying to Unittest validations of arguments in argparse the following works:

mymodule:

def validate_mac_addr(mac_addr):
    regex = re.compile(r'^((([a-f0-9]{2}:){5})|(([a-f0-9]{2}-){5}))[a-f0-9]{2}$', re.IGNORECASE)

    if re.match(regex, mac_addr) is not None:
        return mac_addr
    msg = f"[-] Invalid MAC address: '{mac_addr}'"
    raise argparse.ArgumentTypeError(msg)

test:

import mymodule
import unittest

  def test_mac_address_false(self):
            self.assertRaises(Exception, mymodule.validate_mac_addr,"n0:ma:ca:dd:re:ss:here") 

But I wanted to catch a the more specific 'ArgumentTypeError' but this is apparently not possible with arssertRaises() in this example!? What is going on with the general usage of Exception in assertRaises()?

BTW

isinstance(argparse.ArgumentTypeError, Exception)

Returns False?!

Ref.: class ArgumentTypeError(Exception):

1 Answers

argparse.ArgumentTypeError is a subclass, not an instance, of Exception, and is the type of exception you should be asserting gets raised.

import argparse


def test_mac_address_false(self):
    self.assertRaises(argparse.ArgumentTypeError, mymodule.validate_mac_addr, "n0:ma:ca:dd:re:ss:here") 
Related