单元测试遇ValueError:条件需布尔数组而非对象问题求助
问题解决:pandas where方法报错ValueError: Boolean array expected for the condition, not object
错误根源
你的测试代码里MockPandas.notnull方法返回的是包含字符串"None"的DataFrame,但实际pd.notnull应该返回布尔类型的DataFrame。data_df.where()要求第一个参数必须是布尔数组,传入非布尔的对象数组就会触发这个报错。
另外还有两个隐性问题:
- 测试断言里预期的键是
"a",但原代码里列名替换后是"a_b"(原列名是"a b") - 原代码没有将处理后的DataFrame转为字典列表,直接返回的话断言会失败(因为
result是DataFrame,和字典列表无法直接相等)
修复后的代码
修正后的测试代码
class MockPandas: def __init__(self): pass def read_csv(self, *args, **kwargs): return pd.DataFrame([{"a b": np.nan, "b": 2.33}]) def notnull(self, *args, **kwargs): # 返回布尔类型的DataFrame,匹配pd.notnull的真实行为 return pd.DataFrame([{"a_b": False, "b": True}]) @patch("path", MockPandas()) # 注意这里的"path"要替换成原代码中导入pandas的实际路径,比如"your_module.pd" def test_read_file_and_transform(self): result = self.obj.read_file_and_transform("/file_path") # 修正列名,匹配原代码的列名转换逻辑 assert result == [{"a_b": None, "b": 2.33}]
原代码补充(若需返回字典列表)
如果你的函数需要返回字典列表而非DataFrame,需在原代码末尾添加转换逻辑:
def read_file_and_transform(local_file_path): """读取CSV并转换列名、替换nan为None""" try: data_df = pd.read_csv(local_file_path) data_df.columns = data_df.columns.str.replace(' ', '_') clean_df = data_df.where(pd.notnull(data_df), None) # 转为字典列表返回,匹配测试断言的格式 return clean_df.to_dict('records') except Exception as e: logger.error("Failure in read file and transform method {}".format(e)) raise e
关键说明
pd.notnull()的核心作用是生成布尔掩码,标记非空值位置,因此Mock时必须返回布尔值的DataFrame- 确保patch路径正确:
@patch里的字符串要对应原代码中导入pandas的实际位置,比如原代码是import pandas as pd,则patch路径为"your_script_name.pd"
内容的提问来源于stack exchange,提问作者Aman Raheja
相关产品推荐
相关产品推荐

