如何使用 python 的 unittest 来 1) 从要测试的主代码生成一个 csv 文件和 2) 测试 csv 文件是否已生成

问题描述 投票:0回答:0

我正在学习使用 python 的单元测试(第一次)并且遇到了一些麻烦。我有查询数据库、对数据进行排序并将排序后的数据输出到 csv 文件的代码。它工作得很好。但是,当我尝试从测试模块生成 csv 时,它永远不会生成,因此单元测试在检查文件是否在路径中生成时失败。在我的其他测试函数中,要测试的函数正在被调用并且正在通过单元测试。当我从另一个非测试 python 脚本调用它时生成 csv 文件,但它只是不是从测试模块生成的,所以问题出在测试模块中。

这是我的代码:

from my_code_to_be_tested import my_code_to_be_tested as mc

...

@mock.patch('my_code_to_be_tested.my_code_to_be_tested.create_file')

    def test_create_file(self, mock_create_file):

        data = self._get_data(self) # get the data to output, this works

        file_name = self._get_filename(self) #also works 

    

        mc.create_file(data, file_name) #this line never executes

   

        test_dir = os.path.dirname(os.path.abspath(__file__))

        file_path = os.path.join(test_dir, file_name)

   
        assert os.path.isfile(file_path)

my_code_to_be_tested.py文件中的create_file函数如下:

def create_file(report: DataFrame, file_name: string) -> None:
    """
    Save data to .csv file
    Args:
        report: a sorted dataframe consisting of the requested columns
        file_name: the name of the report

    Returns:
        None
    """
 
    filename = f'{file_name}.csv'
    report.to_csv(filename, index=False)

我检查了各种文件路径,看它是否在不同的文件夹中生成,但根本没有生成,所以我一定是调用不正确。我以这种方式调用了我的其他函数并且它们起作用了,但是它们都返回了一个值,因此它们的语法略有不同。

谢谢!

python unit-testing python-unittest python-unittest.mock
© www.soinside.com 2019 - 2024. All rights reserved.