python 为什么没有引发ValueError?

bzzcjhmw  于 2023-11-16  发布在  Python
关注(0)|答案(1)|浏览(81)

我目前正在做我的python类的作业,需要一些帮助。我写了下面的函数:

def get_funcs(funcs: dict, file_name: str, table_name: str) -> None:
    '''
    Read the given *.csv file, store the data inside the database and store the functions in a dict
    
    Args:
        functions dict: Dictionary to store the functions object
        file_name str: The file name of the csv-file with file extension
        table_name str: The name of the SQL table
    '''    
    
    global update_database

    try:
        if file_name == "test.csv" or file_name == "test":
            raise ValueError("The function for the test data is not neccessary.")
        elif file_name != "train.csv" and file_name != "train" and file_name != "ideal.csv" and file_name != "ideal":
            raise ValueError("Given a completly wrong / empty file or a directorys.")
        
        # store the complete path to the file in a variable
        complete_path = os.path.join(dataset_dir, file_name)
        # check file to be correct
        file_extension = os.path.splitext(file_name)[1]
        if file_extension == "":
            print_log(MessageType.Warn, "get_funcs", "Missing file extension. Added "".csv"" automatically!")
            complete_path += ".csv"        
        if not os.path.exists(complete_path):
            raise FileNotFoundError()
        
        # read csv file and store it in a data frame
        data = pd.read_csv(complete_path, sep=",")
        print_log(MessageType.Info, "get_funcs", "Successfully read \"" + file_name + "\"!")
    except PermissionError as error:
        print_log(MessageType.Error, "get_funcs", "Cannot open the given csv file!")
        return
    except Exception as error:
        print_log(MessageType.Error, "get_funcs", error)
        return

字符串
任务的一部分是编写单元测试。所以我写了以下代码:

import main
import unittest

class UnitTestPythonTask(unittest.TestCase):
    def test_check_test_function(self):
        '''
        Checks the file validation of the given .csv files
        '''
        self.assertRaises(ValueError, main.get_funcs({}, "test.csv", "TestFunction"))


测试失败,因为没有引发ValueError。如果我设置一个断点并观察单个步骤,我可以看到,ValueError被引发并被记录(print_log)。
我尝试在try... except...块外设置raise ValueError("Given a completly wrong / empty file or a directorys."),但没有成功。在测试成功后,当我检查是否引发异常时,我添加了一个addtionall,除了ValueError。同样没有成功。
有谁能告诉我,为什么测试失败,尽管ValueError被提出?

mwg9r5ms

mwg9r5ms1#

你的函数except Exception as error:中有一个广泛的异常,它捕获了在调用print_log后从函数中引发并返回None的任何错误。这就是为什么你在测试中没有看到任何异常。
在你的问题中,你没有说print_log是什么,所以我实现了一个占位符保持器,它假设你打印到stdout

from datetime import datetime
import io
import unittest.mock
import main

class UnitTestPythonTask(unittest.TestCase):
    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    @unittest.mock.patch(
        "main.get_log_time", unittest.mock.MagicMock(return_value=datetime(1972, 1, 1))
    )
    def test_check_test_function(self, mock_stdout):
        """
        Checks the file validation for test.csv file
        """
        expected_output = ("MessageType.Error "
                           "- 1972-01-01 00:00:00 - get_funcs "
                           "- The function for the test data is not necessary.\n")
        main.get_funcs(funcs={}, file_name="test.csv", table_name="TestFunction")
        self.assertEqual(mock_stdout.getvalue(), expected_output)

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    @unittest.mock.patch(
        "main.get_log_time", unittest.mock.MagicMock(return_value=datetime(1972, 1, 1))
    )
    def test_check_wrong_file(self, mock_stdout):
        """
        Checks the file validation for a bad .csv file
        """
        expected_output = ("MessageType.Error "
                           "- 1972-01-01 00:00:00 - get_funcs "
                           "- Given a completly wrong / empty file or a directory.\n")
        main.get_funcs(funcs={}, file_name="bad_file.csv", table_name="TestFunction")
        self.assertEqual(mock_stdout.getvalue(), expected_output)

字符串
作为参考,这是我的main.py包含的内容:

from datetime import datetime
from enum import Enum, auto
import os

dataset_dir = "/tmp"

class MessageType(Enum):
    Warn = auto()
    Error = auto()

def get_log_time():
    return datetime.now()

def print_log(msg_type, func, msg):
    print(f"{msg_type} - {get_log_time()} - {func} - {msg}")

def get_funcs(funcs: dict, file_name: str, table_name: str) -> None:
    """
    Read the given *.csv file, store the data inside the database and store the functions in a dict

    Args:
        functions dict: Dictionary to store the functions object
        file_name str: The file name of the csv-file with file extension
        table_name str: The name of the SQL table
    """
    global update_database

    try:
        if file_name == "test.csv" or file_name == "test":
            raise ValueError("The function for the test data is not necessary.")
        elif (
            file_name != "train.csv"
            and file_name != "train"
            and file_name != "ideal.csv"
            and file_name != "ideal"
        ):
            raise ValueError("Given a completly wrong / empty file or a directorys.")

        # store the complete path to the file in a variable
        complete_path = os.path.join(dataset_dir, file_name)
        # check file to be correct
        file_extension = os.path.splitext(file_name)[1]
        if file_extension == "":
            print_log(
                MessageType.Warn,
                "get_funcs",
                "Missing file extension. Added " ".csv" " automatically!",
            )
            complete_path += ".csv"
        if not os.path.exists(complete_path):
            raise FileNotFoundError()

        # read csv file and store it in a data frame
        data = pd.read_csv(complete_path, sep=",")
        print_log(
            MessageType.Info, "get_funcs", 'Successfully read "' + file_name + '"!'
        )
    except PermissionError as error:
        print_log(MessageType.Error, "get_funcs", "Cannot open the given csv file!")
        return
    except Exception as error:
        print_log(MessageType.Error, "get_funcs", error)
        return

相关问题