
在进行数据处理和分析时,为pandas dataframe编写健壮的测试至关重要。hypothesis库通过生成多样化的输入数据,极大地简化了这一过程。然而,在实际应用中,开发者可能会遇到生成的数据缺乏多样性,总是趋向于最小值的问题。本教程将深入探讨如何正确使用hypothesis生成可变dataframe,并推荐更专业的解决方案。
许多开发者在尝试使用Hypothesis生成自定义数据结构时,会倾向于使用@st.composite装饰器来组合多个策略。例如,以下代码片段展示了一个生成DataFrame的尝试:
import pandas as pd
from hypothesis import given, strategies as st
from hypothesis.extra.pandas import column, data_frames, range_indexes
@st.composite
def create_hypothesis_df(draw):
num_rows = draw(st.integers(min_value=1, max_value=10))
data = [
(
draw(st.text(min_size=0, max_size=)), # 错误:max_size未指定
'1750',
draw(st.datetimes()),
draw(st.datetimes()),
draw(st.floats(min_value=1, max_value=1000)),
draw(st.floats(min_value=1, max_value=1000)),
draw(st.floats(min_value=1, max_value=1000)),
draw(st.text(min_size=0, max_size=100)),
draw(st.text(min_size=0, max_size=100)),
) for _ in range(num_rows)
]
columns = ["col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8", "col9"]
return pd.DataFrame(data, columns=columns)当执行上述代码时,用户可能会发现生成的DataFrame中的数据总是趋近于策略的最小值(例如,浮点数总是1.0,日期总是2001-01-01,字符串为空)。这通常是由于代码中存在语法错误导致Hypothesis无法正确执行策略,或者在某些情况下,策略配置不当导致其倾向于生成最小值。
在本例中,st.text(min_size=0, max_size=)存在一个明显的语法错误,max_size参数没有指定值。这种语法错误会导致代码无法正常运行,进而影响Hypothesis生成多样化数据的能力。一旦修正这个语法错误,Hypothesis通常就能按预期生成多样化的数据。
为了让上述@st.composite策略能够正常工作并生成多样化的数据,我们需要修正st.text中的语法错误,并确保所有策略参数都已正确配置。
import pandas as pd
from hypothesis import given, strategies as st
@st.composite
def create_hypothesis_df_corrected(draw):
num_rows = draw(st.integers(min_value=1, max_value=10))
data = [
(
draw(st.text(min_size=0, max_size=10)), # 修正:max_size指定为10
'1750', # 这是一个固定值,不会变化
draw(st.datetimes()),
draw(st.datetimes()),
draw(st.floats(min_value=1, max_value=1000)),
draw(st.floats(min_value=1, max_value=1000)),
draw(st.floats(min_value=1, max_value=1000)),
draw(st.text(min_size=0, max_size=100)),
draw(st.text(min_size=0, max_size=100)),
) for _ in range(num_rows)
]
columns = ["col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8", "col9"]
return pd.DataFrame(data, columns=columns)
# 验证修正后的策略
@given(create_hypothesis_df_corrected())
def test_dataframe_generation(df):
print("--- Generated DataFrame ---")
print(df)
assert not df.empty
# 可以在这里添加更多断言来测试DataFrame的属性
# 例如:assert (df['col5'] >= 1).all() and (df['col5'] <= 1000).all()
# 运行测试(需要安装pytest或直接调用test_dataframe_generation()多次)
# test_dataframe_generation()通过修正max_size参数,st.text策略现在可以正常工作,Hypothesis将能够生成各种长度的字符串。运行上述测试函数,您会观察到DataFrame中的数据会呈现出预期的多样性,不再局限于最小值。
尽管@st.composite方法可以解决问题,但Hypothesis为Pandas DataFrame提供了更专业、更强大且通常更高效的生成方式,即通过hypothesis.extra.pandas模块。这个模块专为Pandas数据结构设计,提供了data_frames、column和range_indexes等策略,使得DataFrame的生成更加灵活和可控。
以下是使用hypothesis.extra.pandas模块生成相同DataFrame的示例:
import pandas as pd
from hypothesis import given, strategies as st
from hypothesis.extra.pandas import column, data_frames, range_indexes
def create_hypothesis_df_pandas_extra():
return data_frames(
[
column("col1", st.text(min_size=0, max_size=10)),
column("col2", st.just("1750")), # 使用st.just生成固定值
column("col3", st.datetimes()),
column("col4", st.datetimes()),
column("col5", st.floats(min_value=1, max_value=1000)),
column("col6", st.floats(min_value=1, max_value=1000)),
column("col7", st.floats(min_value=1, max_value=1000)),
column("col8", st.text(min_size=0, max_size=100)),
column("col9", st.text(min_size=0, max_size=100)),
],
index=range_indexes(min_size=1, max_size=10), # 控制行数
)
# 验证推荐策略
@given(create_hypothesis_df_pandas_extra())
def test_dataframe_generation_pandas_extra(df):
print("--- Generated DataFrame (using hypothesis.extra.pandas) ---")
print(df)
assert not df.empty
assert len(df.columns) == 9
assert df.index.min() >= 0 # range_indexes通常从0开始
# 运行测试
# test_dataframe_generation_pandas_extra()虽然两种方法都能生成所需的DataFrame,但hypothesis.extra.pandas模块具有显著的优势:
在为Pandas DataFrame生成测试数据时,避免因语法错误或策略配置不当导致的数据多样性不足是关键。@st.composite装饰器是一个通用的解决方案,但对于DataFrame这种结构化的数据,强烈推荐使用hypothesis.extra.pandas模块。它不仅能提供更清晰、更灵活的代码结构,还能在处理复杂场景和优化性能方面带来显著优势。通过采纳这些最佳实践,开发者可以更有效地利用Hypothesis库,为Pandas数据处理逻辑构建出覆盖更广、更可靠的自动化测试。
以上就是Hypothesis与Pandas:高效生成测试数据帧的实践指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号