I am currently working on a project that uses many dataframe wrangling. The intention is to write test to check that the output functions are correct.
I have written a test for a dataframe function that transforms a dataframe of operations into another dataframe that contains the volumen of the operations for each of the containing days.
My question is:
Is this a good test for a function that receives a DataFrame and returns a DataFrame?
Should I do something different?
This is is my code:
import pandas as pd
class Operations:
def disaggregate_ops_volume_date(self, df: DataFrame):
""" Given a DataFrame with operations it generates an operation for each of the days it contains """
if df.empty:
return df
ops = df.copy()
ops['NDAYS'] = ops[['SEQ_PERIODSTART', 'SEQ_PERIODEND']].apply(
lambda row: (row['SEQ_PERIODEND'] - row['SEQ_PERIODSTART']).days, axis=1)
# Add a copy of each operation NDAYS times
ops = ops.loc[np.repeat(ops.index, ops['NDAYS'])]
# Correct the date based on the TradeId operation
ops['SEQ_PERIODSTART'] += pd.to_timedelta(ops.groupby('TRADEID').cumcount(), unit='d')
ops['SEQ_PERIODEND'] = ops['SEQ_PERIODSTART'] + pd.Timedelta(1, unit='d')
ops = ops.reset_index(drop=True)
return ops
This is the test I have developed:
from pandas.util.testing import assert_frame_equal
import unittest
import pandas as pd
class TestOperations(unittest.TestCase):
def test_minimal(self):
"""To make sure at least a test is passed"""
self.assertEqual('foo'.upper(), 'FOO')
def test_disaggregate_ops_volume_date(self):
input = pd.DataFrame(
{'SEQ_PERIODSTART':
['2019-02-10', '2019-02-12', '2019-02-13'],
'SEQ_PERIODEND':
['2019-02-11', '2019-02-14', '2019-02-18'],
'ID': [0, 1, 2]})
input['SEQ_PERIODSTART'] = pd.to_datetime(input['SEQ_PERIODSTART'])
input['SEQ_PERIODEND'] = pd.to_datetime(input['SEQ_PERIODEND'])
expected = pd.DataFrame(
{'SEQ_PERIODSTART':
['2019-02-10', '2019-02-12', '2019-02-13', '2019-02-13', '2019-02-14', '2019-02-15', '2019-02-16', '2019-02-17'],
'SEQ_PERIODEND':
['2019-02-11', '2019-02-13',
'2019-02-14', '2019-02-14', '2019-02-15', '2019-02-16', '2019-02-17', '2019-02-18'],
'ID': [0, 1, 2, 3, 4, 5, 6, 7],
'NDAYS': [1, 2, 2, 5, 5, 5, 5, 5]
})
expected['SEQ_PERIODSTART'] = pd.to_datetime(expected['SEQ_PERIODSTART'])
expected['SEQ_PERIODEND'] = pd.to_datetime(expected['SEQ_PERIODEND'])
myops = Operations()
assert_frame_equal(expected, myops.disaggregate_ops_volume_date(input))
if __name__ == '__main__':
unittest.main()