1

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 Answers1

0

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") 
chepner
  • 497,756
  • 71
  • 530
  • 681
  • You answer cleared things up for me. Thank you. Now the test also passes with argparse.ArgumentTypeError. I was getting "NameError: name 'argparse' is not defined". I forgot to import argparse in the unittest file. – Thomas Juul Dyhr Jan 06 '22 at 16:03