How to raise an AttributeError?

704 Views Asked by At

I am trying to raise an AttributeError for unit testing but could not succeed. The problem is the error is not raised.

import unittest
class TestErrors(unittest.TestCase):
    """Unit testing of errors"""
    def test_get_it(self):
        """Error tests for get_it"""
        with self.assertRaises(AttributeError):
            get_it_tester("Foo", "Bar")

The code for get_it_tester:

def get_it_tester(path, cont):
    """Tester function for get_it"""
    files = glob.glob(f"{path}{os.sep}i*")
    files += glob.glob(f"{path}{os.sep}i*{os.sep}{cont}*")
    return get_it(files)

The code for get_it:

def get_it(files):
    """Get a list of iterations"""
    try:
        return [int(re.search(f"{os.sep}i([0-9]+)", f).groups(0)[0]) for f in files]
    except AttributeError:
        print(f"ERROR: The path must be in format of 'path{os.sep}to{os.sep}i1'")
1

There are 1 best solutions below

2
rasjani On
def get_it(files):
    """Get a list of iterations"""
    try:
        return [int(re.search(f"{os.sep}i([0-9]+)", f).groups(0)[0]) for f in files]
    except AttributeError:
        print(f"ERROR: The path must be in format of 'path{os.sep}to{os.sep}i1'")
        raise