[Python] Accessing instance object from mocked method

Discussão em 'Python' iniciado por Stack, Julho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to test a function that creates and transforms a dataframe. At the end of the function the dataframe is saved as a csv. Is there a way to "hook" into the function and retrieve the end state of the dataframe? I tried to mock the to_csv method at the very end of the function but I can't figure out how to retrieve the dataframe instance from that call.

    I know that I could:

    • Read the resulting csv and verify it that way but I'd prefer not to because the runner of these tests has an unpredictable file system.
    • Return the dataframe, however, my actual function is used in airflow which doesn't allow dataframes to be passed around

    Here's a stripped down runnable example:

    foo.py:

    import pandas as pd

    def bar():
    df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
    # assume df is transformed in some way
    df.to_csv('test.csv')


    test.py:

    import unittest
    from unittest.mock import patch, call
    from foo import bar

    class TestBar(unittest.TestCase):

    @patch("pandas.DataFrame.to_csv")
    def test_bar(self, mock_to_csv):
    bar()

    # How do I access df?
    self.assertEqual(mock_to_csv.mock_calls, [call('test.csv')])

    Continue reading...

Compartilhe esta Página