【问题标题】:Unit test for reading an excel file witth pandas使用 pandas 读取 excel 文件的单元测试
【发布时间】:2019-05-11 10:45:56
【问题描述】:

我需要为下面的代码编写一个单元测试用例:

    def read_data(self, data):

    """Read data from excel file.

    :param data:str, data in file
    :return:str, data after reading excel file
    """
    try:
        read_data = pd.read_excel(data)
        return read_data
    except Exception as e:
        logger.info("Not able to read data. Error :- {}".format(e))
        raise e

我在上面的代码中读取一个 excel 文件,它给了我这样的数据: refer screenshot.

那么,如何将上述数据从 excel 表读取后存储为虚拟数据,以便我可以将其断言到我的原始数据?

谢谢

【问题讨论】:

    标签: excel python-2.7 unit-testing


    【解决方案1】:

    因为我有同样的需要,所以发布这个。

    this answer 可以为您指明正确的方向:

    另请参阅 XlsxWriter 文档中的 Saving the Dataframe 输出到字符串。

    从示例中您可以构建如下内容:

    import pandas as pd
    import io
    
    # Create a Pandas dataframe from the data.
    df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
    
    output = io.BytesIO()
    
    # Use the BytesIO object as the filehandle.
    writer = pd.ExcelWriter(output, engine='xlsxwriter')
    
    # Write the data frame to the BytesIO object.
    df.to_excel(writer, sheet_name='Sheet1', index=False)
    writer.save()
    
    # Read the BytesIO object back to a data frame - here you should use your method
    xlsx_data = pd.read_excel(output)
    
    # Assert that the data frame is the same as the original
    pd.testing.assert_frame_equal(xlsx_data, df)
    

    基本上,您可以解决问题:您构建一个包含一些数据的数据框,将其保存在一个类似文件的临时对象中,将该对象传递给您的方法,然后断言数据与该数据相同你创造的。

    注意:它需要 pandas 0.17+

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 2014-05-21
      • 2016-11-12
      • 2017-09-04
      • 2016-02-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多