0

How could I cover the tests in the case of a function that returns a dataframe that can change at any time? I am starting tests and I have no idea how to cover my code with unit tests, what do you advise me to do?

def update_with_formulario(date):
    df_formulario = _get_formulario(date)
    assert df_formulario is not None, 'Dataframe df_formulario is null'
    df_csv = utilities.get_data_csv_with_pandas('df.csv')
    assert df_csv is not None, 'Dataframe df_csv is null'
    df = df_formulario.merge(df_csv, 'left')
    utilities.write_csv_dataframe(f"{ROOT_WRITE_PATH}df.csv", df)


def _get_formulario(date):
    global cnn
    try:
        repo = Repository()
        cnn = repo.connect()
        query = f"""SELECT DISTINCT fecha,
                                   hora ,
                                   coalesce(valor_copia, valor) AS value
                    FROM table
                    WHERE VARIABLE IN ('variable')
                      AND fecha_data = '{date} 00:00:00'"""
        df_formulario = pd.read_sql_query(query, cnn)
        return df_formulario
    except:
        logging.exception(exc_msg.EXC_PROCEDURE_EXCEPT_MSG)
    finally:
        if cnn:
            cnn.close()
            logging.info(exc_msg.CNN_CLOSED_MSG)
  • Have a look at the answers to [this question: How do you unittest Python dataframes](https://stackoverflow.com/questions/41852686/how-do-you-unit-test-python-dataframes). – MrBean Bremen Jun 10 '20 at 15:44
  • It depends what you want the unit test to uncover. If you don't expect the Database to change for prior data then you can get your expected output for some static date and then use something like [`assert_frame_equals`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.testing.assert_frame_equal.html) to check that it never changes from that. But if the Database is expected to be retroactively updated, then perhaps it's best to check features of the returned DataFrame, like the columns, the dtypes, the index values (should it be a RangeIndex?), ... – ALollz Jun 10 '20 at 15:49
  • @ALollz I like your comment, but that's really what I want to get as a final answer, how to make each option you tell me. – kmiiloberrio-dev Jun 10 '20 at 15:55
  • @MrBeanBremen Those answers are not very convincing to me. I still value your comment. – kmiiloberrio-dev Jun 10 '20 at 15:57

0 Answers0