【问题标题】:How to Test Pandas Function with Mutable Argument如何使用可变参数测试 Pandas 函数
【发布时间】:2021-06-27 06:55:08
【问题描述】:

如何测试带有可变参数的 pandas 函数?如图所示,该函数在程序和测试中工作,但在测试中返回None 类型。它需要针对 pandas DataFrame <class 'pandas.core.frame.DataFrame'> 进行测试。

两个类似的问题对编写assert 函数没有多大帮助:

注意:这不是一个可变的默认问题。

prog.py

import pandas as pd

def new_year(df):
    df.Class += 1
    # print(".", df)

df = pd.DataFrame({'Name':['Jack', 'Jill'], 'Class':[4, 5]})
new_year(df)
print(df)
(tst) E:\venv\tst>python prog.py
   Name  Class
0  Jack      5
1  Jill      6

test_prog.py

import unittest
import pandas as pd
from pandas._testing import assert_frame_equal
from prog import new_year

def test_new_year():
    df1 = pd.DataFrame({'Name':['Jack', 'Jill'], 'Class':[4, 5]})
    df2 = pd.DataFrame({'Name':['Jack', 'Jill'], 'Class':[5, 6]})
    assert_frame_equal(new_year(df1), df2)
(tst) E:\venv\tst>pytest -vv tests
=================================================== test session starts ===================================================
platform win32 -- Python 3.9.0, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- e:\venv\tst\scripts\python.exe
cachedir: .pytest_cache
rootdir: E:\venv\tst
collected 1 item

tests/test_prog.py::test_new_year FAILED                                                                             [100%]

======================================================== FAILURES =========================================================
______________________________________________________ test_new_year ______________________________________________________

    def test_new_year():
        df1 = pd.DataFrame({'Name':['Jack', 'Jill'], 'Class':[4, 5]})
        df2 = pd.DataFrame({'Name':['Jack', 'Jill'], 'Class':[5, 6]})
>       assert_frame_equal(new_year(df1), df2)

tests\test_prog.py:9:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

left = None, right =    Name  Class
0  Jack      5
1  Jill      6, cls = <class 'pandas.core.frame.DataFrame'>

    def _check_isinstance(left, right, cls):
        """
        Helper method for our assert_* methods that ensures that
        the two objects being compared have the right type before
        proceeding with the comparison.

        Parameters
        ----------
        left : The first object being compared.
        right : The second object being compared.
        cls : The class type to check against.

        Raises
        ------
        AssertionError : Either `left` or `right` is not an instance of `cls`.
        """
        cls_name = cls.__name__

        if not isinstance(left, cls):
>           raise AssertionError(
                f"{cls_name} Expected type {cls}, found {type(left)} instead"
            )
E           AssertionError: DataFrame Expected type <class 'pandas.core.frame.DataFrame'>, found <class 'NoneType'> instead

lib\site-packages\pandas\_testing.py:508: AssertionError
================================================= short test summary info =================================================
FAILED tests/test_parse_methods.py::test_clean_date - AssertionError: DataFrame Expected type <class 'pandas.core.frame.D...
FAILED tests/test_prog.py::test_new_year - AssertionError: DataFrame Expected type <class 'pandas.core.frame.DataFrame'>,...
=============================================== 1 failed in 0.91s ===============================================

【问题讨论】:

    标签: python pandas unit-testing


    【解决方案1】:

    你可以在new_year函数中尝试returndf

    def new_year(df):
        df.Class += 1
        return df
    

    就目前而言,new_year 函数没有明确的return 语句,因此它返回None,因此返回AssertionError

    【讨论】:

    • 在真正的代码上并不是那么简单。处理列TypeError: 'NoneType' object is not subscriptable
    • @flywire 你能分享一下什么代码导致了这个错误吗?因为这里没有使用[] 语法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多