ModuleNotFoundError


ModuleNotFoundError is raised when Python cannot find a module that is given in an import statement. A Python module is a file that ends in .py. Any folder that contains an __init__.py is also a Python module

requirements

test_module_not_found_error

RED: make it fail

  • I change test_failure to test_module_not_found_error

    1import unittest
    2
    3
    4class TestModuleNotFoundError(unittest.TestCase):
    5
    6    def test_module_not_found_error(self):
    7        import src.module_00
    

    the terminal shows ModuleNotFoundError

    ModuleNotFoundError: No module called 'src.module_00'
    

    because Python cannot find module_00.py in the src folder

  • I add the error to the list of Exceptions encountered in test_module_not_found_error.py

    10# Exceptions Encountered
    11# AssertionError
    12# ModuleNotFoundError
    

GREEN: make it pass

I change module_not_found_error.py in the src folder to module_00.py and the test passes

REFACTOR: make it better

  • I add another import statement to test_module_not_found_error.py

    6    def test_module_not_found_error(self):
    7        import src.module_00
    8        import src.module_01
    

    the terminal shows ModuleNotFoundError

    ModuleNotFoundError: No module named 'src.module_01'
    

    I make a new file named module_01.py in the src folder and the test passes

  • I close the file

  • I continue with another import statement in test_module_not_found_error.py

    6    def test_module_not_found_error(self):
    7        import src.module_00
    8        import src.module_01
    9        import src.module_02
    

    the terminal shows ModuleNotFoundError

    ModuleNotFoundError: No module called 'src.module_02'
    

    I add module_02.py to the src folder and the terminal shows green again

  • I close the file

  • I add one last failing import statement for practice in test_module_not_found_error.py

     6    def test_module_not_found_error(self):
     7        import src.module_00
     8        import src.module_01
     9        import src.module_02
    10        import src.module_03
    

    the terminal shows

    ModuleNotFoundError: No module called 'src.module_03'
    
  • I add the file to the src folder and the test passes

  • I close the file


review

I ran a test for ModuleNotFoundError to practice making Python modules. Would you like to test AttributeError?


Click Here for the code I wrote in this chapter