Python 参数化列表和数据框夹具的pytest
我正在Python 参数化列表和数据框夹具的pytest,python,pandas,pytest,Python,Pandas,Pytest,我正在pytest中为pandasDataFrame的自定义子类创建测试。我想测试我的类构造函数是否同时适用于列表和数据帧。我怎样才能参数化我的测试,使test\u构造函数既能接受samp\u list又能接受samp\u df,而不是有重复的test\u构造函数和test\u构造函数和
pytest
中为pandasDataFrame
的自定义子类创建测试。我想测试我的类构造函数是否同时适用于列表和数据帧。我怎样才能参数化我的测试,使test\u构造函数
既能接受samp\u list
又能接受samp\u df
,而不是有重复的test\u构造函数和test\u构造函数和
测试函数
@pytest.fixture(scope='module')
def sample():
samp_list = [{'timestamp': '2020-01-01', 'group': 'a', 'dollar_gains': 100},
{'timestamp': '2020-01-01', 'group': 'b', 'dollar_gains': 100},
{'timestamp': '2020-01-01', 'group': 'c', 'dollar_gains': 110},
{'timestamp': '2020-01-01', 'group': 'a', 'dollar_gains': 110},
{'timestamp': '2020-01-01', 'group': 'b', 'dollar_gains': 90},
{'timestamp': '2020-01-01', 'group': 'd', 'dollar_gains': 100}]
samp_df = pd.DataFrame(samp_list)
return samp_list, samp_df
def test_constructor(sample):
print('hi')
hist_dg = HistDollarGains(sample, 'group', 'timestamp')
assert hist_dg.group == 'group'
assert hist_dg.timestamp_col == 'timestamp'
这对你来说可能太晚了,但我今天遇到了一个类似的问题。似乎有一个选项可以将参数传递给fixture,并且它将针对传递的每个值运行
Martin Winkel在这里写了一篇很好的文章:
就你的情况而言,我认为你应该这样做:
import pandas as pd
import pytest
opt_dict = {'samp_list': [{'timestamp': '2020-01-01', 'group': 'a', 'dollar_gains': 100},
{'timestamp': '2020-01-01', 'group': 'b', 'dollar_gains': 100},
{'timestamp': '2020-01-01', 'group': 'c', 'dollar_gains': 110},
{'timestamp': '2020-01-01', 'group': 'a', 'dollar_gains': 110},
{'timestamp': '2020-01-01', 'group': 'b', 'dollar_gains': 90},
{'timestamp': '2020-01-01', 'group': 'd', 'dollar_gains': 100}],
'samp_df':pd.DataFrame([{'timestamp': '2020-01-01', 'group': 'a', 'dollar_gains': 100},
{'timestamp': '2020-01-01', 'group': 'b', 'dollar_gains': 100},
{'timestamp': '2020-01-01', 'group': 'c', 'dollar_gains': 110},
{'timestamp': '2020-01-01', 'group': 'a', 'dollar_gains': 110},
{'timestamp': '2020-01-01', 'group': 'b', 'dollar_gains': 90},
{'timestamp': '2020-01-01', 'group': 'd', 'dollar_gains': 100}]),
'samp_bad_input':'this should result in a failed test'}
@pytest.fixture(params=opt_dict.keys())
def df_opt(request):
'''
I haven't looked into why request works without a definition; it is some kind of pytest built-in for use with fixtures
'''
return opt_dict[request.param]
def test_sample(df_opt):
if isinstance(df_opt,list):
sample_df = pd.DataFrame(df_opt)
else:
sample_df = df_opt
assert isinstance(sample_df,pd.DataFrame), "somehow, we didn't end up with a dataframe"