diff --git a/pyfiglet/__init__.py b/pyfiglet/__init__.py index 545d9d9..e0aaf5a 100755 --- a/pyfiglet/__init__.py +++ b/pyfiglet/__init__.py @@ -170,16 +170,25 @@ def preloadFont(cls, font:str): @classmethod def isValidFont(cls, font:str): + """ + This function checks if the font given is valid or not. + Font file name is taken as argument. Hence, ".flf" and ".tlf" must be added + to the argument; otherwise, the function returns False. + + """ if not font.endswith(('.flf', '.tlf')): return False f = None full_file = os.path.join(SHARED_DIRECTORY, font) - if os.path.isfile(font): - f = open(font, 'rb') - elif os.path.isfile(full_file): - f = open(full_file, 'rb') - else: - f = importlib.resources.files('pyfiglet.fonts').joinpath(font).open('rb') + try: # Catches FileNotFoundError in case any of the open()s encounters it. + if os.path.isfile(font): + f = open(font, 'rb') + elif os.path.isfile(full_file): + f = open(full_file, 'rb') + else: + f = importlib.resources.files('pyfiglet.fonts').joinpath(font).open('rb') + except FileNotFoundError: + return False if zipfile.is_zipfile(f): # If we have a match, the ZIP file spec says we should just read the first file in the ZIP. diff --git a/pyfiglet/test.py b/pyfiglet/test.py index 7df002c..5eaabed 100755 --- a/pyfiglet/test.py +++ b/pyfiglet/test.py @@ -5,6 +5,7 @@ import sys from optparse import OptionParser from pyfiglet import Figlet +from pyfiglet import FigletFont from subprocess import Popen, PIPE try: from colorama import init @@ -101,6 +102,8 @@ def check_result(self): print('FAILED = %s' % set(self.failed)) return self.failed, self.oked + def test_invalid_font_file(): + assert FigletFont.isValidFont("does_not_exist.flf") is False def banner(text): cprint(Figlet().renderText(text), "blue") @@ -122,6 +125,7 @@ def main(): test.check_text("Averylongwordthatwillbecutatsomepoint I hope", False) banner("TESTING explicit new line") test.check_text("line1\nline2", True) + test.test_invalid_font_file() if len(test.check_result()[0]) == 0: return 0 else: